import Taro, { Component } from '@tarojs/taro';
import ListView from '@components/ListView'
import './index.scss'
import { connect } from '@tarojs/redux'
import { queryCustomerList, addFollowRecord } from '@services/person'
import { transferImage } from '@utils/tools'
import * as noticeType from '@constants/common.js'

const maleImg = require('@assets/person/male.png')
const femaleImg = require('@assets/person/female.png')
const phoneImg = require('@assets/person/dianhua.png')
const communicateImg = require('@assets/person/communicate.png')


@connect(({ user, city }) => ({ user, city }))
export default class transactionCustomer extends Taro.Component {

  config = {
    navigationBarTitleText: '成交客户'
  }

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

  componentDidShow() {
    Taro.showLoading()
    this.loadList(1)

  }
  loadList(pageNumber) {
    const payload = {
      type: 'clinch',
      pageNumber,
      pageSize: 9999
    }
    queryCustomerList(payload.type, payload).then(res => {
      const { records, list, total, current, pages } = res || {}
      const _list = records || list || []
      const newList = current <= 1 ? _list : this.state.customerList.concat(_list)
      this.setState({
        customerList: newList,
        isEmpty: total == 0,
        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
  }
  // 跳转我的客户详情
  toMyCustomer(customerId) {
    Taro.navigateTo({
      url: `/pages/person/customerAnalysis/myCustomer?customerId=` + customerId
    })
  }
  // 拨打电话
  handleTelClick(item, e) {
    e.stopPropagation()
    Taro.makePhoneCall({
      phoneNumber: item.phone
    })
    const params = {
      recordType: '拨打电话',
      customerSex: item.sex,
      customerId: item.customerId,
    }
    addFollowRecord(params).then(res => {

    })
    this.setState({
      followVisible: false,
    })
  }
  handleChatClick(item, e) {
    e.stopPropagation()

    const { user: { userInfo: { miniApp: { tpls }, person: { personId, nickname, name } } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_NOTICE && x.isSubscribe == true))[0].tplId
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {
      },
      fail(res) {

      },
      complete() {
        Taro.navigateTo({
          url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(name || nickname)}&receiverId=${item.personId}&receiverName=${encodeURIComponent(item.name || item.nickname)}`
        })
      }
    })
  }

  render() {
    const { customerList, isEmpty, hasMore } = this.state

    return (
      <View style="padding:0 10px 10px 10px">
        <ListView
          className="wrap"
          needInit
          isEmpty={isEmpty}
          emptyText="暂无成交客户~"
          hasMore={hasMore}
          onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
          onScrollToLower={fn => this.onScrollToLower(fn)}
        >
          <View className="list">
            {
              customerList.length &&
              customerList.map((item, index) => (
                <View class="item" key={index + 'transaction'} onClick={this.toMyCustomer.bind(this, item.customerId)}>
                  <Image src={transferImage(item.picture) || require('@assets/default-avatar.png')} className='img'></Image>
                  <View className="name">
                    <Text class="name-text">{item.name}</Text>
                    {
                      item.sex == '1' && <Image style="width:36rpx;height:38rpx;margin-left:20rpx" src={maleImg} />
                    }
                    {
                      item.sex == '2' && <Image style="width:36rpx;height:36rpx;margin-left:20rpx" src={femaleImg} />
                    }
                  </View>
                  <View className="phone">{item.phone} </View>
                  <Image className="phone-icon" src={phoneImg} onClick={this.handleTelClick.bind(this, item)} />
                  <Image className="goutong-icon" onClick={this.handleChatClick.bind(this, item)} src={communicateImg} ></Image>

                </View>
              ))
            }
          </View>
        </ListView>
      </View>
    )
  }
}