import { useState, useEffect } from 'react'
import Taro from "@tarojs/taro";
import withLayout from '@/layout'
import '@/assets/css/iconfont.css'
import { Image, Textarea } from '@tarojs/components'
import { fetch } from '@/utils/request'
import { API_GET_CUSTOMER_INFO } from '@/constants/api'
import { getCustomerDetail, addFollowRecord } from '@/services/person'
import { getImgURL } from '@/utils/image'
import { BIZ_STATUS } from '@/constants/user'
import './index.scss'
import UserDetailBasicInfo from '../components/UserDetailBasicInfo/index'
import UserDetailViewRecord from '../components/UserDetailViewRecord/index'
import UserDetailActivityInfo from '../components/UserDetailActivityInfo/index'
import UserDetailFollowRecord from '../components/UserDetailFollowRecord/index'

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

  const [custBaseInfo, setCustBaseInfo] = useState({})
  const [CustomerInfo, setCustomerInfo] = useState({})
  const [ShowAddFollow, setShowAddFollow] = useState(false)
  const [MenuList] = useState([
    { name: '基本信息', id: 1 },
    { name: '访问记录', id: 2 },
    { name: '活动信息', id: 3 },
    { name: '跟进记录', id: 4 }
  ])
  const [CurrentMenuId, setCurrentMenuId] = useState(1)
  const [FollowContent, setFollowContent] = useState('')
  const [FollowAddCounts, setFollowAddCounts] = useState(0)

  const UpdateCustomerInfo = () => {
    fetch({ url: `${API_GET_CUSTOMER_INFO}/${CustomerId}` }).then((res) => {
      setCustomerInfo(res || {})
    })
  }

  const CutMenu = (item) => {
    return () => {
      setCurrentMenuId(item.id)
    }
  }

  const AddFollow = () => {
    setShowAddFollow(true)
  }

  const FollowInput = (e) => {
    setFollowContent(e.detail.value.substring(0, 10))
  }

  const SaveFollow = () => {
    const payload = {
      recordType: '添加跟进',
      recordContent: FollowContent,
      customerSex: CustomerInfo.sex,
      customerId: CustomerId,
    }
    addFollowRecord(payload).then(() => {
      Taro.showToast({
        title: '添加跟进成功',
        icon: 'none'
      })
      setShowAddFollow(false)
      setFollowContent('')
      if (CurrentMenuId === 4) {
        setFollowAddCounts(FollowAddCounts + 1)
      }
    }).catch(() => {
      Taro.showToast({
        title: '添加跟进失败',
        icon: 'none'
      })
    })
  }

  const CancelAddFollow = () => {
    setShowAddFollow(false)
    setFollowContent('')
  }

  useEffect(() => {
    if (CustomerId) {
      UpdateCustomerInfo()

      getCustomerDetail(CustomerId).then((res) => setCustBaseInfo(res || {}))
    }
  }, [CustomerId])

  const ToChat = () => {
    if(CustomerInfo.personId) {
      Taro.navigateTo({
        url: `/pages/chat/chatDetail/index?friend=${CustomerInfo.personId}`
      })
    } else {
      Taro.showToast({
        title: '当前人员未登录本小程序',
        icon: 'none'
      })
    }
  }


  return (
    <view className='Page customerDetail flex-v'>

      <view className='UserInfo'>
        <view>
          <view>
            <view className='centerLabel'>
              <view className='flex-h'>
                <view className='Icon'>
                  <Image mode='aspectFill' src={getImgURL(custBaseInfo.avatarurl || custBaseInfo.picture)}></Image>
                </view>
                <view className='flex-item'>
                  <view>
                    <text>{custBaseInfo.name}</text>
                    <text className={custBaseInfo.sex - 0 === 1 ? 'iconfont icon-nanxing' : 'iconfont icon-nvxing'}></text>
                  </view>
                  <text>{custBaseInfo.phone}</text>
                </view>
                <text className='iconfont icon-liaotian' onClick={ToChat}></text>
                <text className='iconfont icon-dianhua' onClick={() => { Taro.makePhoneCall({ phoneNumber: custBaseInfo.phone }) }}></text>
              </view>
            </view>
            <text className='Status'>{BIZ_STATUS[custBaseInfo.status] || '报备'}</text>
            <text className='Tips'>NEW</text>
            <text className='Tips'>NEW</text>
          </view>
        </view>
      </view>

      <view className='MenuList'>
        <view>
          {
            MenuList.map((item, index) => (
              <text key={`MenuItem-${index}`} className={CurrentMenuId === item.id ? 'active' : ''} onClick={CutMenu(item)}>{item.name}</text>
            ))
          }
        </view>
      </view>

      <view className='flex-item'>
        <view>

          {/* 基本信息 */}
          {
            CurrentMenuId === 1 &&
            <UserDetailBasicInfo CustomerId={CustomerId} CustomerInfo={CustomerInfo} AddFollow={AddFollow} Update={UpdateCustomerInfo}></UserDetailBasicInfo>
          }

          {/* 访问记录 */}
          {
            CurrentMenuId === 2 &&
            <UserDetailViewRecord CustomerId={CustomerId} AddFollow={AddFollow}></UserDetailViewRecord>
          }

          {/* 活动信息 */}
          {
            CurrentMenuId === 3 &&
            <UserDetailActivityInfo CustomerId={CustomerId} AddFollow={AddFollow}></UserDetailActivityInfo>
          }

          {/* 跟进记录 */}
          {
            CurrentMenuId === 4 &&
            <UserDetailFollowRecord CustomerId={CustomerId} AddFollow={AddFollow} AddFollowCounts={FollowAddCounts}></UserDetailFollowRecord>
          }
        </view>
      </view>

      {
        ShowAddFollow &&
        <view className='AddFollow'>
          <view className='centerLabel'>
            <view>
              <view>
                <text>跟进内容</text>
                <view className='FollowContent'>
                  <Textarea placeholder='不超过150字' maxLength={150} value={FollowContent} onInput={FollowInput} />
                </view>
                <view className='Save flex-h'>
                  <view className='flex-item'>
                    <text onClick={CancelAddFollow}>取消</text>
                  </view>
                  <view className='flex-item'>
                    <text onClick={SaveFollow}>保存</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      }

    </view>
  )
})
