import { useState, useEffect } from 'react'
import withLayout from '@/layout'
import { ScrollView, Input, Image, Block, View, Button } from '@tarojs/components'
import '@/assets/css/iconfont.css'
import { fetch } from '@/utils/request'
import BottomMoadl from '@/components/BottomMoadl/index'

import { API_USER_ADD_CUSTOMER, API_CHANNEL_REPORT } from '@/constants/api'
import { ROLE_CODE } from '@/constants/user'
import Taro from '@tarojs/taro'
import Picker from '@/components/Picker'
// import BuildingPicker from './components/BuildingPicker'
import ConsultantPicker from './components/ConsultantPicker'

import './index.scss'


const defaultSpecialImage = 'https://yz-websit.oss-cn-hangzhou.aliyuncs.com/xlk/index-icon19.jpg'

const sexDicts = [
  { name: '男', id: '1' },
  { name: '女', id: '2' },
]

export default withLayout((props) => {
  const { router, person } = props
  const { personId, personType } = person
  const { buildingId: originBuiding } = router.params

  const [loading, setLoading] = useState(false)
  const [buildingId, setBuildingId] = useState(null)
  const [CardId, setCardId] = useState(null)
  const [SexId, setSexId] = useState(null)
  const [FormData, setFormData] = useState({
    name: '', // 姓名
    phone: '', // 电话
    sex: '', // 性别
    intention: '', // 意向楼盘
    realtyConsultant: '', // 置业顾问
    remark: '', // 描述
  })

  useEffect(() => {
    console.log('------originBuiding------>', originBuiding)
    if (originBuiding) {
      setBuildingId(originBuiding)
    }
  }, [originBuiding])

  const preSubmit = (payload) => {
    if (payload.name === '') {
      Taro.showToast({ title: '请填写客户姓名', icon: 'none' })
      return false
    }
    if (SexId === null) {
      Taro.showToast({ title: '请选择客户性别', icon: 'none' })
      return false
    }
    if (payload.phone === '') {
      Taro.showToast({ title: '请填写客户电话', icon: 'none' })
      return false
    }
    if (!(/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(payload.phone)) || payload.phone.length != 11) {
      Taro.showToast({ title: '请填写正确的客户电话', icon: 'none' })
      return false
    }
    if (buildingId === null) {
      Taro.showToast({ title: '请选择客户的意向楼盘', icon: 'none' })
      return false
    }
    if (buildingId === null && personType !== ROLE_CODE.CUSTOMER) {
      Taro.showToast({ title: '请选择客户的意向楼盘', icon: 'none' })
      return false
    }

    return true
  }

  const onSubmit = () => {
    const payload = personType === ROLE_CODE.CONSULTANT ?
      {
        name: FormData.name, // 姓名
        phone: FormData.phone, // 电话
        sex: SexId, // 性别
        describe: FormData.describe, // 描述
        buildingId,
      } :
      {
        ...FormData,
        sex: SexId,
        buildingId,
        realtyConsultant: CardId
      };

    if (!preSubmit(payload)) {
      return;
    }

    setLoading(true)
    let url = null
    if (personType === ROLE_CODE.CONSULTANT || personType === ROLE_CODE.CUSTOMER) {
      // url = API_REPORT_CUETOMER
      url = API_USER_ADD_CUSTOMER
    } else if (personType === ROLE_CODE.CHANNEL_AGENT) {
      url = API_CHANNEL_REPORT
    } else if (personType === ROLE_CODE.CUSTOMER) {
      // url = API_USER_ADD_CUSTOMER
    }
    fetch({ url, method: 'post', payload }).then(() => {
      setLoading(false)
      Taro.showToast({ title: '操作成功', icon: 'none' })

      const t = setTimeout(() => {
        Taro.navigateBack({ delta: 1 })
        clearTimeout(t)
      }, 1500)
    }).catch(() => {
      setLoading(false)
    })
  }

  const FormInput = (e) => {
    let Data = { ...FormData }
    Data[e.currentTarget.dataset.type] = e.detail.value
    setFormData(Data)
  }

  const handleBuildingSelect = (bid, building) => {
    setBuildingId(bid)
  }

  return (
    <view className='Page addCustomer'>


      <ScrollView scroll-y refresher-enabled={false} refresher-background='#fff'>
        <view className='PageContent'>

          <text>客户姓名</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='请输入客户真实姓名' data-type='name' onInput={FormInput.bind(this)}></Input>
            </view>
          </view>

          <text>客户电话</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Input placeholder='请输入手机号' data-type='phone' onInput={FormInput.bind(this)}></Input>
            </view>
          </view>

          <text>性别</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <Picker kv={['name', 'id']} dicts={sexDicts} onChange={setSexId} value={SexId} />
            </view>
            {/* <text className='iconfont icon-jiantoudown'></text> */}
          </view>

          <text>意向楼盘</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              {/* <BuildingPicker change={BuildingChange} value={buildingId} type={personType} /> */}
              {/* <View onClick={() => setShowFrame(true)} >{buildingName}</View> */}
              <BottomMoadl onChange={handleBuildingSelect} role={personType} />
            </view>
          </view>

          {
            personType === ROLE_CODE.CONSULTANT || ROLE_CODE.CUSTOMER ?
              <Block>
                <text>内场接待（选填）</text>
                <view className='FormLine flex-h'>
                  <view className='flex-item'>
                    <ConsultantPicker onChange={setCardId} value={CardId} buildingId={buildingId} />
                  </view>
                  {/* <Image mode='heightFix' src={defaultSpecialImage}></Image>
                <text>选择</text> */}
                </view>

                <text>备注</text>
                <view className='FormLine flex-h'>
                  <view className='flex-item'>
                    {
                      //解决事件穿透
                      <Input placeholder='补充说明（选填）' dataType='remark' onInput={FormInput.bind(this)}></Input>
                    }
                  </view>
                </view>
              </Block> : ''
          }
          <view className='Btn'>
            <Button loading={loading} onClick={onSubmit}>提交</Button>
          </view>

        </view>
      </ScrollView>

    </view>
  )
})
