import Taro, { Component } from '@tarojs/taro';
import ListView from '@/components/ListView'
import { connect } from '@tarojs/redux'
import './index.scss'
import { getSharePersonInfoList, judgeBindCustomer, getConsulantVisitRecord } from '@/services/person'
import { savePoint, updatePoint } from '@/services/common'
import * as noticeType from '@/constants/common.js'
import dayjs from 'dayjs';

@connect(state => state.user)

export default class Person extends Component {
  config = {
    navigationBarTitleText: '访客信息'
  }

  state = {
    recordId: undefined, // 埋点ID
    recordList: [],
    hasMore: true,
    isEmpty: false,
    pageIndex: 1,
  }

  componentWillMount() {
    savePoint({
      event: 'list',
      eventType: 'activity',
      propertyName: '访客信息',
      data: '{}'
    }).then(res => {
      this.setState({
        recordId: res.recordId
      })
      console.log('访客信息')
    })
  }
  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }
  componentDidShow() {

    Taro.showLoading()
    this.loadList(1)
  }
  loadList(pageNumber) {
    console.log(this.props, "this.props")
    const { targetId, eventType } = this.$router.params
    const { userInfo: { person } } = this.props
    console.log(targetId)
    const payload = {
      userId: person.userId,
      targetId,
      eventType,
      pageNumber,
      pageSize: 10
    }
    getConsulantVisitRecord(payload).then(res => {
      const { records, list, total, current, pages } = res || {}
      const _list = records || list || []
      const newList = current <= 1 ? _list : this.state.recordList.concat(_list)
      this.setState({
        recordList: newList,
        isEmpty: total == 0 || !res,
        hasMore: current < pages,
        pageIndex: current >= pages ? pages : current
      })
      Taro.hideLoading()

    })

  }
  onScrollToLower = async (fn) => {
    const { pageIndex } = this.state;
    this.loadList(pageIndex + 1)
    fn && fn();
  }
  onPullDownRefresh = (rest) => {
    // debugger
    if (this.refreshing) return
    this.refreshing = true
    this.loadList(1)
    rest && rest()
    this.refreshing = false
  }
  handleChatClick(item, e) {
    e.stopPropagation()
    const { userInfo: { person: { personId, nickname, name } } } = this.props
    const { userInfo: { miniApp: { tpls } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_NOTICE && x.isSubscribe == true)[0] || {}).tplId
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {
        Taro.navigateTo({
          url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(name || nickname)}&receiverId=${item.personId}&receiverName=${encodeURIComponent(item.name || item.nickname)}`
        })
      },
      fail(res) {
        Taro.navigateTo({
          url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(name || nickname)}&receiverId=${item.personId}&receiverName=${encodeURIComponent(item.name || item.nickname)}`
        })
      }
    })
  }

  goCustomerDetail(item) {
    console.log(item, "item")

    if (item.myCustomer == 1) {
      Taro.navigateTo({
        url: `/useless/pages/person/customerAnalysis/myCustomer?customerId=` + item.customerId
      })
    } else {
      Taro.showToast({
        title: 'TA不是你的客户，无法查看详细信息',
        duration: 2000,
        icon: 'none',
      })
    }
  }

  render() {
    const { isEmpty, hasMore, recordList } = this.state
    return (
      <Block>
        <ListView
          className="wrap"
          needInit
          isEmpty={isEmpty}
          emptyText="暂无访客信息~"
          hasMore={hasMore}
          onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
          onScrollToLower={fn => this.onScrollToLower(fn)}
        >
          <View className='access-page'>
            {
              recordList.map(item => (
                <View className='item' key={String(item + 'more')} onClick={this.goCustomerDetail.bind(this, item)} >
                  {item.myCustomer == 1 && <View className="tag">我的客户</View>}
                  <Image className="touxiang" src={item.avatarurl || require('@/assets/default-avatar.png')}></Image>
                  <View className="info-top">
                    <View className="name">{item.userName || item.nickname || '　'}</View>
                    <View style="display: flex;align-items: center;" onClick={this.handleChatClick.bind(this, item)}><Image className="goutong-icon" src={require('@/assets/person/zixun.png')}></Image><Text className="goutong">在线沟通</Text></View>
                  </View>
                  <View className="activity-time">
                    {`${dayjs(item.visitTime).format('YYYY-MM-DD HH:mm:ss')}`}
                  </View>
                </View>
              ))
            }
          </View>
        </ListView>
      </Block >
    )
  }
}
