import React, { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import withLayout from '@/layout'
import { getChannelCustomerStatus, getCustomerDetail, getCustomerInfo } from '@/services/person'
import { ScrollView, Image } from '@tarojs/components'
import Modal from '@/components/Modal'
import { ROLE_CODE } from '@/constants/user'
import { API_CUSTOMER_DETAILINFO } from '@/constants/api'
import { fetch } from '@/utils/request'
import { formatDate } from '@/utils/chatDate'
import icon24 from '@/assets/mine-icon24.png'
import icon25 from '@/assets/mine-icon25.png'
import EditUserDetailBasicInfo from '../components/EditUserDetailBasicInfo'
import useFollow from './hooks/useFollow'

import './index.scss'

const addDays = (dt, days) => {
  const zone8 = 8 * 3600 * 100 // 中国时区, 因为 toJSON 是 ISO 时间
  const ret = new Date(new Date(dt).valueOf() + (days - 1) * 24 * 3600 * 1000 + zone8)
  return ret.toJSON().substring(0, 10)
}

export default withLayout((props) => {
  const { router, person } = props
  const { id } = router.params

  const [custBaseInfo, setCustBaseInfo] = useState({})
  const [custMoreInfo, setCustMoreInfo] = useState({})
  const [statusInfo, setStatusInfo] = useState({})
  const [followContent, setFollowContent] = useState()
  const [showUserEditor, setShowUserEditor] = useState(false)
  const [showFollowModal, setShowFollowModal] = useState(false)
  const [followList, followSubmitting, addFollow] = useFollow(custBaseInfo)

  const { channelCustomer, building } = statusInfo
  const expirationDate = building?.expirationDate ?
    addDays(channelCustomer?.createDate, building?.expirationDate) :
    '暂无'

  const handleAddFollow = () => {
    addFollow(followContent)
    const t = setTimeout(() => {
      setShowFollowModal(false)
      clearTimeout(t)
    }, 1500)
  }

  useEffect(() => {
    if (id) {
      fetch({ url: `${API_CUSTOMER_DETAILINFO}/${id}` }).then((x) => {
        setCustBaseInfo(x || {})
      })

      getChannelCustomerStatus(id).then((x) => {
        setStatusInfo(x || {})
      })

      getCustomerInfo(id).then((x) => {
        setCustMoreInfo(x || {})
      })
    }
  }, [id, person])

  return (
    <view className='Page myCustomerDetail'>
      <ScrollView scrollY>
        <view className='PageContent'>

          {/* 基本信息 */}
          <view className='BasicInfo'>
            <view className='Title flex-h'>
              <text>基本信息</text>
            </view>
            <view className='Content'>
              <view className='UserInfo flex-h'>
                <view className='Icon'>
                  <Image mode='aspectFill' src={custBaseInfo.avatarurl || custBaseInfo.picture}></Image>
                </view>
                <view className='flex-item' onClick={() => setShowUserEditor(true)}>
                  <text>{custBaseInfo.name}</text>
                  <text>{custBaseInfo.phone}</text>
                </view>
                <text className='iconfont icon-jiantouright'></text>
              </view>
              <view className='Status'>
                {/* <view className='flex-h'>
                  <view className='flex-item'>
                    <text>对楼盘意向值:</text>
                    <text>xxxxxxxxxxx</text>
                  </view>
                </view> */}
                <view className='flex-h'>
                  <view className='flex-item'>
                    <text>跟进状态:</text>
                    <text>跟进中</text>
                  </view>
                  <view className='flex-item'>
                    <text>报备状态:</text>
                    <text>报备中</text>
                  </view>
                </view>
                <view className='flex-h'>
                  <view className='flex-item'>
                    <text>跟进结果:</text>
                    <text>{statusInfo.followed ? '今日已跟进' : '今日未跟进'}</text>
                  </view>
                  <view className='flex-item'>
                    <text>报备结果:</text>
                    <text>{custBaseInfo.status > 1 ? '已到访' : '已报备'}</text>
                  </view>
                </view>
                <view className='flex-h'>
                  <view className='flex-item'>
                    <text>预计收回时间:</text>
                    <text>{expirationDate}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          {/* 房源订单 */}
          {
            custBaseInfo.customerSignatory?.length > 0 && (
              <view className='Order'>
                <view className='Title flex-h'>
                  <text>房源订单</text>
                </view>
                <view className='Content'>
                  {
                    custBaseInfo.customerSignatory.map((item) => {
                      const apartment = item.buildingApartment || {}
                      const { apartmentName } = apartment
                      const nameShow = apartmentName ? `(${apartmentName})` : ''
                      const status = item.status === 5 ? '结佣' : '签约'
                      const icon = item.status === 5 ? icon24 : icon25
                      const buildingArea = item.buildingArea ? `${Number(item.buildingArea).toFixed(1)}㎡` : '暂无'
                      const insideArea = item.insideArea ? `${Number(item.insideArea).toFixed(1)}㎡` : '暂无'

                      return (
                        <view key={item.customerSignatoryId}>
                          <view className='flex-h'>
                            <view className='flex-item'>
                              <text>{`${item.price}${nameShow}`}</text>
                            </view>
                            <Image mode='heightFix' src={icon}></Image>
                            <text className='active'>{status}</text>
                            <text className='iconfont icon-jiantouright'></text>
                          </view>
                          <view className='Info'>
                            <text>{`建筑面积: ${buildingArea}`}</text>
                            <text></text>
                            <text>{`套内面积: ${insideArea}`}</text>
                          </view>
                        </view>
                      )
                    })
                  }
                </view>
              </view>
            )
          }

          {/* 操作人员 */}
          {/* <view className='OptUser'>
            <view className='Title flex-h'>
              <text>操作人员</text>
              <view className='flex-item'></view>
              <view className='More'>
                <text>更多</text>
                <text className='iconfont icon-jiantouright'></text>
              </view>
            </view>
            <view className='Content'>
              <view className='UserInfo flex-h'>
                <view className='Icon'>
                  <Image mode='aspectFill' src={null}></Image>
                </view>
                <view className='flex-item'>
                  <text>最后跟进人</text>
                  <text>跟进时间</text>
                </view>
              </view>
            </view>
          </view> */}

          {/* 跟进记录 */}
          <view className='Record'>
            <view className='Title flex-h'>
              <text>跟进记录</text>
              <view className='Edit' onClick={() => setShowFollowModal(true)}>
                <Image mode='heightFix' src={require('@/assets/mine-icon26.png')}></Image>
                <text>新增</text>
              </view>
              <view className='flex-item'></view>
              {/* <view className='More'>
                <text>更多</text>
                <text className='iconfont icon-jiantouright'></text>
              </view> */}
            </view>
            <view className='Content'>
              {
                followList.map((item, index) => (
                  <view key={`Item-${index}`}>
                    <view className='flex-h'>
                      <text>范丞丞</text>
                      <view className='flex-item'></view>
                      <text>{formatDate(item.createDate, 'yyyy-MM-dd hh:mm')}</text>
                    </view>
                    <view className='Desc'>
                      <text>{item.recordContent}</text>
                    </view>
                  </view>
                ))
              }
            </view>
          </view>
        </view>
      </ScrollView>
      <Modal visible={showFollowModal} title='添加跟进' onClose={() => setShowFollowModal(false)}>
        <view>
          <textarea style={{border: '1px solid rgba(0,0,0, .1)', borderRadius: '4px', margin: '1em', padding: '.5em'}} value={followContent} placeholder='请填写跟进内容' onInput={(e) => setFollowContent(e.detail.value)} />
          <button loading={followSubmitting} style={{ background: '#193c83', color: '#fff', borderRadius: 0 }} onClick={handleAddFollow}>确定</button>
        </view>
      </Modal>
      <page-modal show={showUserEditor} position='bottom' onClose={() => setShowUserEditor(false)} height='90vh'>
        <EditUserDetailBasicInfo Data={custMoreInfo} CustomerId={id} close={() => setShowUserEditor(false)} />
      </page-modal>
    </view>
  )
})
