import { useState, useEffect } from 'react'
import withLayout from '@/layout'
import { ScrollView, Input, Image, Block, Picker } from '@tarojs/components'
import '@/assets/css/iconfont.css'
import { getCardList } from '@/services/card'
import { fetch } from '@/utils/request'
import Taro from '@tarojs/taro'
import { API_SURE_CHIP, API_BUILDING_HOUSE_TYPE, API_SURE_SIGN, API_SURE_BUY } from '@/constants/api'
import './index.scss'

export default withLayout((props) => {

  const { router } = props
  const { name, buildingId, type, id, channelId } = router.params

  const RenChouData = {
    name,
    realtyConsultant: '',
    remark: '',
  }

  const QianYueData = {
    name,
    realtyConsultant: '',
    remark: '',
    dividendsName: '',
    dividendsPer: '',
    houseInfo: '',
    houseType: '',
    price: '',
    successDate: '',
  }

  const [FormData, setFormData] = useState({ ...RenChouData })

  const [ConsultantList, setConsultantList] = useState([])
  const [HouseTypeList, setHouseTypeList] = useState([])
  const [CurrnetConsultant, setCurrnetConsultant] = useState({})

  const [SuccessDate, setSuccessDate] = useState(null)

  const [StatusList] = useState([
    { name: '认筹', id: 3 },
    { name: '签约', id: 4 },
    { name: '结佣', id: 5 },
  ])
  const [CurrentStatusId, setCurrentStatusId] = useState(3)

  const [CurrentRoomTypeId, setCurrentRoomTypeId] = useState(null)

  useEffect(() => {
    if (channelId !== null && channelId !== 'null') {

    }
  }, [])

  useEffect(() => {
    if (buildingId) {
      const params = {
        pageNumber: 1,
        pageSize: 50,
        buildingId,
      }
      getCardList(params).then((res) => {
        const { records } = res
        setConsultantList(records || [])
      })
    }
  }, [buildingId])

  useEffect(() => {
    if (CurrentStatusId - 0 !== 3 && buildingId) {
      fetch({ url: `${API_BUILDING_HOUSE_TYPE}?buildingId=${buildingId}&pageSize=${500}`, method: 'get' }).then((res) => {
        setHouseTypeList(res.records || [])
      })
    }
  }, [CurrentStatusId, buildingId])

  const CutStatus = (item) => {
    return () => {
      setCurrentStatusId(item.id)
      if (item.id === 3) {
        setFormData({ ...RenChouData })
      } else if (item.id === 4) {
        setFormData({ ...QianYueData })
      } else if (item.id === 5) {
        setFormData({ ...QianYueData })
      }
    }
  }

  const CutRoomType = (item) => {
    return () => {
      let resData = { ...FormData }
      resData.houseType = item.apartmentId
      setFormData({ ...resData })
      setCurrentRoomTypeId(item.apartmentId)
    }
  }

  const InputChange = (key, e) => {
    let resData = { ...FormData }
    resData[key] = e.detail.value
    console.log('---------resData---------', resData)
    setFormData({ ...resData })
  }

  console.log('---------FormData---------', FormData)

  const PickerChange = (key, e) => {
    let resData = { ...FormData }
    if (key === 'realtyConsultant') {
      resData[key] = ConsultantList[e.detail.value].id
      resData.realtyConsultantName = ConsultantList[e.detail.value].name
      setCurrnetConsultant(ConsultantList[e.detail.value])
    }
    setFormData({ ...resData })
  }

  const CheckForm = () => {
    if (CurrentStatusId === 3) { // 认筹
      if (FormData.name === '') {
        Taro.showToast({ title: '姓名不能为空', icon: 'none', duration: 2000 })
        return false
      }
      if (FormData.realtyConsultant === '') {
        Taro.showToast({ title: '请选择内场接待', icon: 'none', duration: 2000 })
        return false
      }
    } else if (CurrentStatusId === 4) { // 签约

    }
    return true
  }

  const ToSubmit = () => {
    // if (!CheckForm()) return false
    if (CurrentStatusId === 3) {
      fetch({ url: API_SURE_CHIP, method: 'put', payload: { customerId: id, customerPreparatory: { ...FormData, channelId: channelId === 'null' || channelId === null ? '' : channelId } } }).then(() => {
        Taro.showToast({ title: '修改成功', icon: 'none', duration: 2000 })
      })
    } else if (CurrentStatusId === 4) {
      let params = {}
      for (let key in FormData) {
        if (key !== 'dividendsName' && key !== 'dividendsPer') {
          params[key] = { ...FormData }[key]
        }
      }
      params.dividendsName = `${FormData.dividendsName}|${FormData.dividendsPer}%`
      fetch({ url: API_SURE_SIGN, method: 'put', payload: { customerId: id, customerSignatory: { ...params, channelId: channelId === 'null' || channelId === null ? '' : channelId } } }).then(() => {
        Taro.showToast({ title: '修改成功', icon: 'none', duration: 2000 })
      })
    } else if (CurrentStatusId === 5) {
      let params = {}
      for (let key in FormData) {
        if (key !== 'dividendsName' && key !== 'dividendsPer') {
          params[key] = { ...FormData }[key]
        }
      }
      params.dividendsName = `${FormData.dividendsName}|${FormData.dividendsPer}%`
      fetch({ url: API_SURE_BUY, method: 'put', payload: { customerId: id, customerSignatory: { ...params, channelId: channelId === 'null' || channelId === null ? '' : channelId } } }).then(() => {
        Taro.showToast({ title: '修改成功', icon: 'none', duration: 2000 })
      })
    }
  }

  const SuccessDateChange = (e) => {
    let resData = { ...FormData }
    resData.successDate = new Date(e.detail.value)
    setFormData(resData.successDate)
    setSuccessDate(e.detail.value)
  }

  return (
    <view className='Page changeVisit'>

      <ScrollView scroll-y>
        <view className='PageContent'>

          <text className='required'>变更状态</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <view className='CheckBoxList'>
                {
                  StatusList.map((item, index) => (
                    <view key={`StatusItem-${index}`} onClick={CutStatus(item)} style={{ marginRight: index === 2 ? '0px' : '44rpx' }}>
                      <text>{item.name}</text>
                      {
                        CurrentStatusId === item.id &&
                        <Image mode='widthFix' src={require('@/assets/findHouse-icon1.png')}></Image>
                      }
                    </view>
                  ))
                }
              </view>
            </view>
          </view>

          <text className='required'>客户姓名</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='请输入姓名' disabled={CurrentStatusId === 5} value={FormData.name} onInput={InputChange.bind(this, 'name')}></Input>
            </view>
          </view>


          <text>归属渠道</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='请输入渠道' disabled value={type === 'customer' ? '-' : ''}></Input>
            </view>
          </view>

          <text className='required'>内场接待</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Picker range-key='name' range={ConsultantList} value={0} onChange={PickerChange.bind(this, 'realtyConsultant')}>{CurrnetConsultant.name || '请选择'}</Picker>
            </view>
          </view>

          {
            (CurrentStatusId === 4 || CurrentStatusId === 5) &&
            <Block>
              <text className='required'>业绩分成人|占比/%</text>
              <view className='FormLine flex-h'>
                <view className='flex-item'>
                  <Input placeholder='请输入业绩分成人' onInput={InputChange.bind(this, 'dividendsName')}></Input>
                </view>
                <view className='flex-item'>
                  <Input placeholder='请输入占比%' type='number' onInput={InputChange.bind(this, 'dividendsPer')}></Input>
                </view>
              </view>
            </Block>
          }

          {
            (CurrentStatusId === 4 || CurrentStatusId === 5) &&
            <Block>
              <text className='required'>户型</text>
              <view className='FormLine flex-h'>
                <view className='flex-item'>
                  <view className='CheckBoxList'>
                    {
                      HouseTypeList.map((item, index) => (
                        <view key={`RoomTypeItem-${index}`} onClick={CutRoomType(item)}>
                          <text>{item.apartmentName}</text>
                          {
                            CurrentRoomTypeId === item.apartmentId &&
                            <Image mode='widthFix' src={require('@/assets/findHouse-icon1.png')}></Image>
                          }
                        </view>
                      ))
                    }
                  </view>
                </view>
              </view>
            </Block>
          }

          {
            (CurrentStatusId === 4 || CurrentStatusId === 5) &&
            <Block>
              <text className='required'>房号</text>
              <view className='FormLine flex-h'>
                <view className='flex-item'>
                  <Input placeholder='请输入房号' onInput={InputChange.bind(this, 'houseInfo')}></Input>
                </view>
              </view>
            </Block>
          }

          {
            (CurrentStatusId === 4 || CurrentStatusId === 5) &&
            <Block>
              <text className='required'>签约日期</text>
              <view className='FormLine flex-h'>
                <view className='flex-item'>
                  <Picker mode='date' value={null} onChange={SuccessDateChange}>{SuccessDate || '请选择开始日期'}</Picker>
                </view>
                <text className='iconfont icon-jiantoudown'></text>
              </view>
            </Block>
          }

          {
            (CurrentStatusId === 4 || CurrentStatusId === 5) &&
            <Block>
              <text className='required'>成交金额</text>
              <view className='FormLine flex-h'>
                <view className='flex-item'>
                  <Input placeholder='请输入金额' onInput={InputChange.bind(this, 'price')}></Input>
                </view>
              </view>
            </Block>
          }


          <text>备注</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='补充说明（选填）' value={FormData.remark} onInput={InputChange.bind(this, 'remark')}></Input>
            </view>
          </view>

          <view className='Btn'>
            <text onClick={ToSubmit}>提交</text>
          </view>

        </view>
      </ScrollView>

    </view>
  )
})
