import Taro, { Component } from '@tarojs/taro';
import Authorize from '@components/authorize'
import ListView from '@components/ListView'
import './index.scss'
import { savePoint, updatePoint } from '@services/common'
import { connect } from '@tarojs/redux'
import { View, Text, Picker } from '@tarojs/components';
import { queryCustomerList, addFollowRecord } from '@services/person'
const iconImg = require('@assets/person/icon.png')

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

  config = {
    navigationBarTitleText: '跟进客户'
  }


  state = {
    recordId: undefined, // 埋点ID
    customerList: [],
    inputValue: '',
    screenVisible: false,
    statusList: ['全部状态', '报备', '到访', '认筹'],
    statusIndex: -1,
    startArrivalDate: '',
    endArrivalDate: '',
    startReportDate: '',
    endReportDate: '',
    hasMore: true,
    isEmpty: false,
    pageIndex: 1
  }

  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }
  componentDidShow() {
    Taro.showLoading()
    this.loadList(1)

  }

  loadList(pageNumber) {
    const payload = {
      type: 'follow',
      pageNumber,
      pageSize: 10
    }
    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
  }


  changeInput = e => {
    this.setState({
      inputValue: e.detail.value
    })
  }
  // 查询
  searchBtn() {

    this.filterCustomerList();

  }
  // 筛查跟进客户
  filterCustomerList() {

    const payload = {
      type: 'follow',
      pageNumber: 0,
      pageSize: 9999,
      name: this.state.inputValue,
      status: (this.state.statusIndex == 0 || this.state.statusIndex == -1) ? '' : this.state.statusIndex,
      startArrivalDate: this.state.startArrivalDate,
      endArrivalDate: this.state.endArrivalDate,
      startReportDate: this.state.startReportDate,
      endReportDate: this.state.endReportDate,
    }
    queryCustomerList(payload.type, payload).then(res => {

      this.setState({
        customerList: res.records || []
      })
      Taro.hideLoading()
    })
  }
  saveBtn() {
    this.filterCustomerList();
    this.setState({
      screenVisible: false,
    })
  }
  // 显示筛查弹框
  screenShow() {
    this.setState({
      screenVisible: true,
    })
  }
  // 选择状态
  chooseStatus(item, inx) {
    this.setState({
      statusIndex: inx,
    })
  }
  // 到访开始时间
  onVisitDateChange = e => {
    this.setState({
      startArrivalDate: e.detail.value
    })
  }
  // 到访结束时间
  onVisitDateChange2 = e => {
    this.setState({
      endArrivalDate: e.detail.value
    })
  }
  // 报备开始时间
  onReportDateChange = e => {
    this.setState({
      startReportDate: e.detail.value
    })
  }
  // 报备结束时间
  onReportDateChange2 = e => {
    this.setState({
      endReportDate: e.detail.value
    })
  }
  // 取消筛查
  cancelBtn() {
    this.setState({
      screenVisible: false,
      statusIndex: -1,
      startArrivalDate: '',
      endArrivalDate: '',
      startReportDate: '',
      endReportDate: '',
    })
  }
  // 跳转我的客户详情
  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,
    })
  }

  renderScreenBox() {
    const { statusList, statusIndex, startArrivalDate, endArrivalDate, startReportDate, endReportDate } = this.state
    return (
      <View className="mask">
        <View className="content">
          <View style="color:#333;font-size:14px">精准筛选</View>
          <View className="status-box">
            {
              statusList.map((item, index) => (
                <View key={index + 'status'} className={index == statusIndex ? 'checked' : 'status-item'} onClick={this.chooseStatus.bind(this, item, index)}>{item}</View>
              ))
            }
          </View>
          <View className="time-box">
            到访时间：
              <Picker mode='date' onChange={this.onVisitDateChange}>
              <View className='picker'>
                {startArrivalDate}
                {!startArrivalDate && <Text className="placeholder">起始时间</Text>}
              </View>
            </Picker>-<Picker mode='date' onChange={this.onVisitDateChange2}>
              <View className='picker'>
                {endArrivalDate}
                {!endArrivalDate && <Text className="placeholder">结束时间</Text>}
              </View>
            </Picker>
          </View>
          <View className="time-box" style="margin-top:16px">
            报备时间：
              <Picker mode='date' onChange={this.onReportDateChange}>
              <View className='picker'>
                {startReportDate}
                {!startReportDate && <Text className="placeholder">起始时间</Text>}
              </View>
            </Picker>-<Picker mode='date' onChange={this.onReportDateChange2}>
              <View className='picker'>
                {endReportDate}
                {!endReportDate && <Text className="placeholder">结束时间</Text>}
              </View>
            </Picker>
          </View>
          <View className="bottom-btn">
            <View className="save" onClick={this.saveBtn}>
              保存
            </View>
            <View className="cancel" onClick={this.cancelBtn}>
              取消
          </View>
            <View>
            </View>
          </View>
        </View>
      </View>
    )
  }

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

    return (
      <View>
        <View className="top-screen" onClick={this.screenShow}>
          精准筛选<Image src={require('@assets/person/screen.png')} className="screen-img"></Image>
        </View>
        {screenVisible && this.renderScreenBox()}
        <View className="search-box">
          <Input class="input" placeholderClass='placeholder' autoFocus onInput={this.changeInput} placeholder="请输入用户名/手机号" />
          <Button className="btn" onClick={this.searchBtn} >搜索</Button>
        </View>
        <View style="padding: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 &&
                <View></View>
                // <View style="margin:50px auto;text-align:center;font-size:14px;color:#888">暂无跟进客户~</View>
              }
              {
                customerList.length &&
                customerList.map((item, index) => (
                  <View class="item" key={index + 'customerList'} onClick={this.toMyCustomer.bind(this, item.customerId)}>
                    <Image src={item.picture || require('@assets/default-avatar.png')} className='img'></Image>
                    <View className="name">
                      {item.name}
                      {
                        item.sex == '1' && <View style={`margin-left:20rpx;background-image: url(${iconImg});background-size: 100%;background-position: 0rpx -40rpx;width: 36rpx;height: 36rpx;`}></View>
                      }
                      {
                        item.sex == '2' && <View style={`margin-left:20rpx;background-image: url(${iconImg});background-size: 100%;background-position: 0rpx 0px;width: 36rpx;height: 36rpx;`}></View>
                      }
                    </View>
                    <View className="phone" onClick={this.handleTelClick.bind(this, item)}>{item.phone}<View style={`background-image: url(${iconImg});background-size: 100%;background-position: 0rpx -88rpx;width: 44rpx;height: 44rpx;margin-left:10rpx`}></View> </View>
                    <View className="status">报备</View>
                  </View>
                ))
              }
            </View>
          </ListView>


        </View>
      </View>
    )
  }
}