import Taro, { Component } from '@tarojs/taro';
import { AtTabs, AtTabsPane } from 'taro-ui'
import ListView from '@components/ListView'
import "taro-ui/dist/style/components/tabs.scss"
import { savePoint, updatePoint } from '@services/common'
import { getCustomerDetail, getVisitRecord, getActivityList, getFollowRecord, addFollowRecord, commitCustomerInfo } from '@services/person'
import { connect } from '@tarojs/redux'
import './index.scss'
import ActivityItem from './item'
import dayjs from 'dayjs'
const iconImg = require('@assets/person/icon.png')
import emptyImg from '@assets/empty.png'

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

  config = {
    navigationBarTitleText: '我的客户'
  }

  state = {
    current: 0,
    recordId: undefined, // 埋点ID
    activityList: [],
    followVisible: false,
    baseVisible: false,
    followValue: '', //跟进内容
    desc: '', //客户描述
    selector: ['高层', '别墅', '公寓'],
    sexSelector: ['男', '女'],
    customerDetail: {},
    followRecord: [],
    visitRecord: [],
    baseInfo: {}, // 完善信息弹框数据
    hasMore: true,
    isEmpty: false,
    pageIndex: 1,
    hasMore2: true,
    isEmpty2: false,
    pageIndex2: 1,
    hasMore3: true,
    isEmpty3: false,
    pageIndex3: 1,
  }

  componentWillUnmount() {

    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

  handleClick(value) {
    this.setState({
      current: value
    })
    if (value == 1) {
      this.queryVisitRecord(1);
    } else if (value == 2) {
      this.queryActivityList(1);
    } else if (value == 3) {
      this.queryFollowRecord(1);
    }
  }
  // 访问记录上拉加载下拉刷新
  onScrollToLower = async (fn) => {
    const { pageIndex } = this.state;
    this.queryVisitRecord(pageIndex + 1)
    fn && fn();
  }
  onPullDownRefresh = (rest) => {
    // debugger
    if (this.refreshing) return
    this.refreshing = true
    this.queryVisitRecord(1)
    rest && rest()
    this.refreshing = false
  }
  // 活动信息上拉加载下拉刷新
  onScrollToLower2 = async (fn) => {
    const { pageIndex2 } = this.state;
    this.queryActivityList(pageIndex2 + 1)
    fn && fn();
  }
  onPullDownRefresh2 = (rest) => {
    // debugger
    if (this.refreshing) return
    this.refreshing = true
    this.queryActivityList(1)
    rest && rest()
    this.refreshing = false
  }
  // 跟进记录上拉加载下拉刷新
  onScrollToLower3 = async (fn) => {
    const { pageIndex3 } = this.state;
    this.queryFollowRecord(pageIndex3 + 1)
    fn && fn();
  }
  onPullDownRefresh3 = (rest) => {
    // debugger
    if (this.refreshing) return
    this.refreshing = true
    this.queryFollowRecord(1)
    rest && rest()
    this.refreshing = false
  }
  // 获取访问记录
  queryVisitRecord(pageNumber) {
    const { customerId } = this.$router.params
    const payload = {
      pageNumber,
      pageSize: '10',
      customerId,
    }
    getVisitRecord(payload).then(res => {
      const { records, list, total, current, pages } = res || {}
      const _list = records || list || []
      const newList = current <= 1 ? _list : this.state.visitRecord.concat(_list)
      this.setState({
        visitRecord: newList,
        isEmpty: total == 0,
        hasMore: current < pages,
        pageIndex: current >= pages ? pages : current
      })
    })
  }
  // 获取活动信息
  queryActivityList(pageNumber) {
    const { customerId } = this.$router.params
    const payload = {
      pageNumber,
      pageSize: '10',
      customerId,
    }
    getActivityList(payload).then(res => {
      const { records, list, total, current, pages } = res || {}
      const _list = records || list || []
      const newList = current <= 1 ? _list : this.state.activityList.concat(_list)
      this.setState({
        activityList: newList,
        isEmpty2: total == 0,
        hasMore2: current < pages,
        pageIndex2: current >= pages ? pages : current
      })
    })
  }
  // 获取跟进记录
  queryFollowRecord(pageNumber) {
    const { customerId } = this.$router.params
    const payload = {
      pageNumber,
      pageSize: '10',
      customerId,
    }
    getFollowRecord(payload).then(res => {
      const { records, list, total, current, pages } = res || {}
      const _list = records || list || []
      const newList = current <= 1 ? _list : this.state.followRecord.concat(_list)
      this.setState({
        followRecord: newList,
        isEmpty3: total == 0,
        hasMore3: current < pages,
        pageIndex3: current >= pages ? pages : current
      })
    })
  }
  componentDidShow() {
    this.loadList()
    // Taro.getSystemInfo({
    //   success: function (res) {
    //     console.log(res, "9999999999999")
    //     this.setState({
    //       tabHeight: res.screenHeight - 380 + 'px'
    //     })
    //   },
    // })

  }
  loadList() {
    const { customerId } = this.$router.params
    getCustomerDetail(customerId).then(res => {
      this.setState({
        customerDetail: res || {}
      })
    })
  }
  handleItemClick(item) {
    // if (item.status == 0) {
    //   Taro.showToast({
    //     title: '当前活动已失效',
    //     icon: 'none'
    //   })
    // } else {
    switch (item.type) {
      case 'help':
        Taro.navigateTo({
          url: '/pages/activity/detail/assistance?id=' + item.id
        })
        return
      case 'group':
        Taro.navigateTo({
          url: '/pages/activity/detail/assemble?id=' + item.id
        })
        return
      default:
        Taro.navigateTo({
          url: '/pages/activity/detail/index?id=' + item.id
        })
        return
    }
    // }
  }
  addFollow() {
    this.setState({
      followVisible: true,
    })
  }
  addFollowRecord
  followSaveBtn() {
    const { customerId } = this.$router.params
    const params = {
      recordType: '添加跟进',
      recordContent: this.state.followValue,
      customerSex: this.state.customerDetail.sex,
      customerId,
    }
    addFollowRecord(params).then(res => {
      this.queryFollowRecord(1)
      Taro.showToast({
        title: '添加跟进成功',
        icon: 'none'
      })
    }).catch(err => {
      Taro.showToast({
        title: '添加跟进失败',
        icon: 'none'
      })
    })
    this.setState({
      followVisible: false,
      followValue: '',
    })
  }
  followCancelBtn() {
    this.setState({
      followVisible: false,
      followValue: '',
    })
  }
  onTextareaChange(e) {
    this.setState({
      followValue: e.target.value
    })
  }
  renderFollowBox() {
    const { followValue } = this.state
    return (
      <View className="mask">
        <View className="content">
          <View style="display:flex;justify-content: space-between;">
            <View style="font-size:14px;color:#666">
              跟进内容：
            </View>
            <Textarea
              className="textarea"
              value={followValue}
              onInput={this.onTextareaChange}
              maxLength={150}
              placeholder='不超过150字'
            />
          </View>
          <View className="bottom-btn">
            <View className="save" onClick={this.followSaveBtn}>
              保存
            </View>
            <View className="cancel" onClick={this.followCancelBtn}>
              取消
          </View>
          </View>
        </View>
      </View>
    )
  }
  perfectInformation() {
    this.setState({
      baseVisible: true,
      baseInfo: this.state.customerDetail,
    })
  }
  // 保存
  baseSaveBtn() {
    const { customerId } = this.$router.params
    const { baseInfo } = this.state
    commitCustomerInfo(customerId, baseInfo).then(res => {
      this.setState({
        customerDetail: res || {}
      })
      const params = {
        recordType: '添加跟进',
        customerSex: this.state.customerDetail.sex,
        customerId,
      }
      addFollowRecord(params).then(res => {
        this.queryFollowRecord(1)
      })
    })
    this.setState({
      baseVisible: false,
    })
  }
  // 取消
  baseCancelBtn() {
    this.setState({
      baseVisible: false,
    })
  }
  onNameChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        name: e.target.value
      }
    })
  }
  onSexChange = e => {

    let sex = e.detail.value == '0' ? '1' : e.detail.value == '1' ? '2' : ''
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        sex,
      }
    })
  }
  onManageTypeChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        realtyManageType: e.target.value
      }
    })
  }
  onPriceRangeChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        priceRange: e.target.value
      }
    })
  }
  onChange = e => {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        demandType: this.state.selector[e.detail.value]
      }
    })
  }
  onBaseTextareaChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        describe: e.target.value
      }
    })
  }
  // 拨打电话
  handleTelClick(customer, e) {
    e.stopPropagation()
    Taro.makePhoneCall({
      phoneNumber: customer.phone
    })
    const params = {
      recordType: '拨打电话',
      customerSex: customer.sex,
      customerId: customer.customerId,
    }
    addFollowRecord(params).then(res => {
      this.queryFollowRecord(1)
    })
    this.setState({
      followVisible: false,
    })
  }
  renderBaseBox() {
    const { baseInfo, desc, selector, sexSelector } = this.state
    return (
      <View className="mask">
        <View className="base-con">
          <View className="con-item">
            <View style="font-size:14px;color:#666">
              姓名：
            </View>
            <Input className="input" value={baseInfo.name} onInput={this.onNameChange} placeholder='' />
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">
              性别：
            </View>
            <View className="con-picker" >
              <View>
                <Picker mode='selector' range={sexSelector} onChange={this.onSexChange}>
                  <View className='picker'>
                    {baseInfo.sex == '1' ? '男' : baseInfo.sex == '2' ? '女' : '　'}
                  </View>
                </Picker>
              </View>
              <View className="right-icon"></View>
            </View>
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">
              物业类型：
            </View>
            <Input className="input" value={baseInfo.realtyManageType} onInput={this.onManageTypeChange} placeholder='' />
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">
              项目类型：
            </View>
            <View className="con-picker" >
              <View>
                <Picker mode='selector' range={selector} onChange={this.onChange}>
                  <View className='picker'>
                    {baseInfo.demandType || '　'}
                  </View>
                </Picker>
              </View>
              <View className="right-icon"></View>
            </View>
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">
              价格区间：
            </View>
            <Input className="input" value={baseInfo.priceRange} onInput={this.onPriceRangeChange} placeholder='' />
          </View>
          <View style="display:flex;justify-content: space-between;">
            <View style="font-size:14px;color:#666">
              客户描述：
            </View>
            <Textarea
              className="textarea"
              value={baseInfo.describe}
              onInput={this.onBaseTextareaChange}
              maxLength={150}
              placeholder=''
            />
          </View>
          <View className="bottom-btn">
            <View className="save" onClick={this.baseSaveBtn}>
              保存
            </View>
            <View className="cancel" onClick={this.baseCancelBtn}>
              取消
          </View>
          </View>
        </View>
      </View>
    )
  }


  render() {

    const tabList = [{ title: '基本信息' }, { title: '访问记录' }, { title: '活动信息' }, { title: '跟进记录' }]
    const { customerDetail, visitRecord, activityList, followRecord, followVisible, baseVisible, isEmpty, hasMore, isEmpty2, hasMore2, isEmpty3, hasMore3 } = this.state
    return (
      <View>
        {followVisible && this.renderFollowBox()}
        {baseVisible && this.renderBaseBox()}
        <View className="user_con">
          <Image className="bg" src={require('@assets/shop/background.jpg')} ></Image>
          <Image className="user__left__headimg" src={customerDetail.picture || require('@assets/default-avatar.png')} />
          <View className='user__left__name'>
            {customerDetail.name}
            {
              customerDetail.sex == '1' && <View style={`margin-left:10px;background-image: url(${iconImg});background-size: 100%;background-position: 0px -20px;width: 18px;height: 18px;`}></View>
            }
            {
              customerDetail.sex == '2' && <View style={`margin-left:10px;background-image: url(${iconImg});background-size: 100%;background-position: 0px 0px;width: 18px;height: 18px;`}></View>
            }
          </View>
          <View onClick={this.handleTelClick.bind(this, customerDetail)} className='user__left__phone'>{customerDetail.phone}<View style={`background-image: url(${iconImg});background-size: 100%;background-position: 0rpx -88rpx;width: 44rpx;height: 44rpx;margin-left:10rpx`}></View></View>
        </View>
        <AtTabs height="calc(100vh - 400rpx)" className="my-tab" current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
          <AtTabsPane current={this.state.current} index={0} >
            <View className="tab-pane1 pane">
              <View className="status">{customerDetail.status == 1 ? '报备' : customerDetail.status == 2 ? '到访' : customerDetail.status == 3 ? '认筹' : '签约'}</View>
              <View className="base-item">意向项目：<View className="con">{customerDetail.intention || '暂无'}</View></View>
              <View className="base-item">物业类型：<View className="con">{customerDetail.realtyManageType || '暂无'}</View></View>
              <View className="base-item">项目类型：<View className="con">{customerDetail.demandType || '暂无'}</View></View>
              <View className="base-item">价格区间：<View className="con">{customerDetail.priceRange || '暂无'}</View></View>
              <View className="base-item">客户描述：<View className="con">{customerDetail.describe || '暂无'}</View></View>
              <View className="btn" onClick={this.perfectInformation}>完善信息</View>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={1}>
            <View className="tab-pane2 pane">
              <ListView
                className="wrap"
                style="height:calc(100vh - 400rpx)"
                needInit
                isEmpty={isEmpty}
                emptyText="暂无访问记录~"
                hasMore={hasMore}
                onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
                onScrollToLower={fn => this.onScrollToLower(fn)}
              >
                <View className="list">
                  {visitRecord.length && visitRecord.map((item, index) => (
                    <View className="record-item" key={index + 'follow'}>
                      <View className="title" >{item.activity}</View>
                      <View className="time">{dayjs(item.visitTime).format('YYYY年MM月DD日 HH:mm:ss') || '　'}</View>
                    </View>
                  ))
                  }
                  {!visitRecord.length &&
                    <View className="empty">
                      {/* <Image className="empty__img" mode="widthFix" src={emptyImg}></Image>
                  <View className="empty__text">暂无访问记录~</View> */}
                    </View>
                  }
                </View>
              </ListView>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={2}>
            <View className="tab-pane3 pane">
              <ListView
                className="wrap"
                style="height:calc(100vh - 400rpx)"
                needInit
                isEmpty={isEmpty2}
                emptyText="暂无活动信息~"
                hasMore={hasMore2}
                onPullDownRefresh={fn => this.onPullDownRefresh2(fn)}
                onScrollToLower={fn => this.onScrollToLower2(fn)}
              >
                <View className="list">
                  {!activityList.length &&
                    <View className="empty">
                      {/* <Image className="empty__img" mode="widthFix" src={emptyImg}></Image>
                  <View className="empty__text">暂无活动信息~</View> */}
                    </View>
                  }
                  {activityList.length &&
                    activityList.map(item => (
                      <ActivityItem
                        data={item}
                        key={item.id + 'activity'}
                        onClick={this.handleItemClick}>
                      </ActivityItem>
                    ))
                  }
                </View>
              </ListView>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={3}>
            <View style="padding:10px 20px 20px 20px">
              <ListView
                className="wrap"
                needInit
                style="height:calc(100vh - 600rpx)"
                isEmpty={isEmpty3}
                emptyText="暂无跟进记录~"
                hasMore={hasMore3}
                onPullDownRefresh={fn => this.onPullDownRefresh3(fn)}
                onScrollToLower={fn => this.onScrollToLower3(fn)} >
                <View className="list">
                  {followRecord.length && followRecord.map(item => (
                    <View key={item.followUpRecordId + 'follow'}>
                      <View style=" display:flex;justify-content: space-between;align-items: center;color: #333;font-size: 16px; margin-bottom:20rpx;">
                        <View style=" display: flex;align-items: center;"><View style="width:8px;height:8px;margin-right:20rpx;display:inline-block;background:rgba(246,182,29,1);border-radius: 50%;"></View>{item.recordType}</View>
                        <View classNam="time" style=" font-size: 26rpx;color: #999;">{dayjs(item.createDate).format('YYYY年MM月DD日 HH:mm:ss') || '　'}</View>
                      </View>
                      {
                        item.recordContent &&
                        <View style="font-size:28rpx;color:#666;padding-left:32rpx;margin-bottom:20rpx;">
                          {item.recordContent}
                        </View>
                      }

                    </View>
                  ))
                  }
                  {!followRecord.length &&
                    <View className="empty">
                      {/* <Image className="empty__img" mode="widthFix" src={emptyImg}></Image>
                  <View className="empty__text">暂无跟进记录~</View> */}
                    </View>
                  }
                </View>
              </ListView>
              <View className="btn" style="margin:40rpx auto;" onClick={this.addFollow}>添加跟进</View>
            </View>
          </AtTabsPane>
        </AtTabs>
      </View>
    )
  }
}