import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import { getWindowHeight } from '@/utils/style'
import { queryChatFriends } from '@/services/chat'

import EmptyPage from '@/components/empty-page'
import Item from './item'
import ready from '@/utils/ready'

import { DECREASE_UNREADNUM } from '@/constants/user'
import { getStore, connect } from '@tarojs/redux'
import * as noticeType from '@/constants/common.js'

@connect(state => state.user)
export default class Index extends Component {
  config = {
    navigationBarTitleText: '我的聊天记录'
  }
  state = {
    list: [],
    scrollTop: 0,
    loading: false,
    pagination: {
      pageNumber: 1,
      pageSize: 50,
    },
    loaded: false,
    params: {
      id: 0,
      type: 'card'
    }
  }
  componentDidShow() {
    ready.queue(() => {
      this.loadList()
    })
  }
  loadList() {
    Taro.showLoading()
    const { pagination } = this.state
    queryChatFriends(pagination).then(res => {
      const { current, records, size, total } = res
      Taro.hideLoading()
      this.setState({
        loaded: true,
        list: records,
        pagination: {
          pageSize: size,
          pageNumber: current,
        }
      }, () => {
        const totalUnRead = (records || []).reduce((acc, item) => (acc + item.unReadNum), 0)
        if (!totalUnRead) {
          // 如果未读为 0, 那么更新 提示组件也为 0

          const { dispatch } = getStore()
          dispatch({ type: DECREASE_UNREADNUM })
        }
      })
    })
  }

  onScrolltolower() {
    !this.state.lastPage && !this.state.loading && this.loadList()
  }

  toChat(person) {
    const { userInfo: { person: { personId, nickname, name } } } = this.props
    const { friendId: receivePersonId, name: receivePersonName } = person
    // debugger
    Taro.navigateTo({
      url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(name || nickname)}&receiverId=${receivePersonId}&receiverName=${encodeURIComponent(receivePersonName)}`
    })
  }

  handleItemClick = ({ unReadNum }) => person => {
    const { userInfo: { miniApp: { tpls } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_NOTICE && x.isSubscribe == true)[0] || {}).tplId
    const that = this
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {

      },
      fail(res) {

      },
      complete() {
        if (unReadNum > 0) {
          const { dispatch } = getStore()
          dispatch({ type: DECREASE_UNREADNUM, payload: unReadNum })
        }

        return that.toChat(person);
      }
    })

  }

  render() {
    const { list } = this.state
    return (
      <ScrollView
        scrollY
        scroll-with-animation
        enable-back-to-top
        className="list"
        style={{
          height: getWindowHeight()
        }}>

        {(loaded && list.length === 0) ? <EmptyPage text="暂无好友哦~" /> : list.map(item => <Item key={item.sendPerson} data={item} onClick={this.handleItemClick(item)} />)}

        {/* <Loadmore nodata={!list.length} loading={loading} loadend={loadend}></Loadmore> */}
      </ScrollView>
    );
  }
}