import React, { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import withLayout from '@/layout'
import { ScrollView, Input, Image } from '@tarojs/components'
import Picker from '@/components/Picker'
import { getChannelCustomerDetail } from '@/services/person'
import { getCardList } from '@/services/card'
import { uploadFiles, fetch } from '@/utils/request'
import { API_MARKETING_VISIT } from '@/constants/api'
import { formatDate } from '@/utils/chatDate'
import '@/assets/css/iconfont.css'
import './index.scss'

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

  const [loading, setLoading] = useState(false)
  const [channelCustomer, setChannelCustomer] = useState({})
  const [consultantList, setConsultantList] = useState([])
  const [consultant, setConsultant] = useState()
  const [visitDate, setVisitDate] = useState(formatDate(Date.now(), 'yyyy-MM-dd'))
  const [imageUrl, setImageUrl] = useState()
  const [remark, setRemark] = useState()

  const openAlbum = (e) => {
    e.stopPropagation()

    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        Taro.showLoading({
          title: '加载中',
        })
        uploadFiles(res.tempFilePaths).then(data => {
          setImageUrl(data[0])
          Taro.hideLoading()
        }).catch(() => {
          Taro.hideLoading()
        })
      },
      complete: () => {
        Taro.hideLoading()
      }
    })
  }

  const handleSubmit = () => {
    const payload = {
      id,
      type: 'report',
      realtyConsultant: consultant,
      customerVisit: {
        buildingId: channelCustomer.buildingId,
        name: channelCustomer.name,
        recommendPerson: channelCustomer.recommendPerson,
        realtyConsultant: consultant,
        imageUrl,
        visitDate: `${visitDate}T12:00:00.000Z`,  // 随便造了一个时刻
        remark,
        channelId: channelCustomer.channelId,
      }
    }

    setLoading(true)
    fetch({ url: API_MARKETING_VISIT, payload, method: 'PUT' }).then((res) => {
      setLoading(false)
      Taro.showToast({
        title: '操作成功',
        icon: 'none'
      })
      const t = setTimeout(() => {
        Taro.navigateBack({ delta: 1 })
        clearTimeout(t)
      }, 1500)
    }).catch((e) => {
      setLoading(false)
    })
  }

  useEffect(() => {
    if (id) {
      getChannelCustomerDetail(id).then((res) => {
        setChannelCustomer(res || {})

        setConsultant(res?.realtyConsultant)

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

  // const [PageProps] = useState(props)

  return (
    <view className='Page sureVisit'>

      <ScrollView scrollY>
        <view className='PageContent'>

          <text>客户姓名</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <text>{channelCustomer.name}</text>
              {/* <Input placeholder='请输入姓名' value={channelCustomer.name}></Input> */}
            </view>
          </view>

          <text>归属渠道</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <text>{channelCustomer.channelName}</text>
              {/* <Input placeholder='请输入渠道' value={channelCustomer.channelName}></Input> */}
            </view>
          </view>

          <text>内场接待（选填）</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              {/* <Input placeholder='请输入内场接待'></Input> */}
              <Picker kv={['name', 'id']} value={consultant} placeholder='请输入内场接待' dicts={consultantList} onChange={setConsultant} />
            </view>
          </view>

          <text>到访时间</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              {/* <text>请选择</text> */}
              <Picker mode='date' value={visitDate} onChange={setVisitDate} />
            </view>
            {/* <text className='iconfont icon-jiantoudown'></text> */}
          </view>

          <text>到访照片（选填）</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              {/* <view className='UploadImg'>
                <text className='iconfont icon-xiangji centerLabel'></text>
              </view> */}
              <Image src={imageUrl} className='UploadImg' onClick={openAlbum} mode="aspectFill"></Image>
            </view>
          </view>

          <text>备注</text>
          <view className='FormLine flex-h'>
            <view className='flex-item'>
              <textarea placeholder='补充说明（选填）' value={remark} onInput={(e) => setRemark(e.detail.value)} ></textarea>
            </view>
          </view>

          <view className='Btn'>
            <button loading={loading} onClick={handleSubmit}>提交</button>
          </view>

        </view>
      </ScrollView>

    </view>
  )
})
