
import { Button, Image, Input, NavigationBar, Navigator, Text, Textarea, View } from '@tarojs/components'
import Taro, { setNavigationBarTitle, useRouter } from '@tarojs/taro'
import { useEffect, useRef, useState } from 'react'
import SelectEnterpriseType from './components/SelectEnterpriseType'
import FromListCertification from '@/components/FromListCertification'
import { certificationDetailApi, certificationSaveApi } from '@/api/certification'
import { alert, retrieval } from '@/common/common'
import './index.scss'
import useUploadCDNImg from '@/use/useUploadImage'
import Message from '@/components/Message'
import { IMG_CND_Prefix } from '@/common/constant'
import { useSelector } from '@/reducers/hooks'
import useLogin from '@/use/useLogin'

const Certification = () => {
  const { getAdminUserInfo } = useLogin()
  const { adminUserInfo } = useSelector(state => state.userInfo)
  // 保存
  const [formData, setFormData] = useState({
    authentication_type: 0,
    authentication_type_name: '',
    business_license_url: '',
    legal_person: '',
    legal_person_identity: '',
    business_license: '',
    legal_person_identity_url: [],
    name: '',
  })
  // 获取认证信息
  const { fetchData: getFromData } = certificationDetailApi()
  const initalFormData = async() => {
    const detail = await getFromData()
    setFormData({
      ...detail.data ?? {},
      legal_person_identity_url: detail?.data?.legal_person_identity_url ?? [],
      // business_license_url: "https://test.cdn.zzfzyc.com/mall/827082e888860dd9da10f0fbb0ac3cf023081456.png"
    } as any)
  }
  useEffect(() => {
    initalFormData()
  }, [])

  const rules = {
    // authentication_type: [{
    //   message: "请选择认证类型"
    // }],
    name: [{
      message: '请输入企业名称',
    }],
    business_license: [{
      message: '请输入企业营业执照',
    }],
    business_license_url: [{
      message: '请上传营业执照',
    }],
    legal_person: [{
      message: '请输入法人名称',
    }],
    legal_person_identity: [{
      message: '请输入正确法人身份证',
      regex: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
    }],
    legal_person_identity_url: [{
      message: '请上传法人身份证',
      validator: (value: any, rule: any) => {
        if (!value[0] || !value[1]) {
          return true
        }
        return false
      },
    }],
  }
  const { fetchData } = certificationSaveApi()
  const handleSave = () => {
    retrieval(formData, rules).then(async() => {
      const result = await fetchData({ ...formData, authentication_type: 2 })
      if (result.success) {
        // Taro.eventCenter.trigger("weightList:refresh");
        getAdminUserInfo()
        Taro.navigateBack()
        alert.success('保存成功')
      }
      else {
        alert.error(result.msg)
      }
    }).catch((message) => {
      alert.none(message)
    })
  }
  // 监听表单完善
  const [hozon, setHozon] = useState(false)
  useEffect(() => {
    if (retrieval) {
      retrieval(formData).then(() => setHozon(true)).catch(() => setHozon(false))
    }
  }, [formData])
  // 选择类型弹窗显示
  const selectTypeRef = useRef(null)
  const handleSelectTypeModalShow = () => {
    (selectTypeRef.current as any).setShow(true)
  }
  // 选择类型确定
  const handleSelectTypeConfirm = (item) => {
    setFormData({
      ...formData,
      authentication_type: item.id,
      authentication_type_name: item.name,
    })
  }
  // 上传图片
  const { getWxPhoto } = useUploadCDNImg()
  const handleUploadImage = async(text: any) => {
    const result = await getWxPhoto('mall')
    if (text == 'business_license_url') {
      formData.business_license_url = IMG_CND_Prefix + (result as any).url
    }
    else {
      formData.legal_person_identity_url[text] = IMG_CND_Prefix + (result as any).url as never
    }
    setFormData({ ...formData })
  }
  // 查看图片
  const handleViewImage = (event, url) => {
    event.stopPropagation()
    Taro.previewImage({
      current: url,
      urls: [url],
    })
  }

  return (
    <View className="certification">
      {(adminUserInfo as any)?.authentication_status == 3 && <Message text={`认证不通过，原因：${(formData as any).authentication_feedback}，请重新认证`} />}
      <View className="certification-content">
        <View className="certification-title">企业认证</View>
        {/* <FromListCertification type="select" onClick={handleSelectTypeModalShow} value={(formData as any)?.authentication_type_name} label="认证类型" placeholder="企业认证"/> */}
        <SelectEnterpriseType ref={selectTypeRef} confirm={handleSelectTypeConfirm} />
        <FromListCertification onInput={(ev: any) => setFormData({ ...formData, name: ev.detail.value })} value={formData.name} label="企业名称" placeholder="请输入营业执照上的企业名称" required />
        {/* <FromListCertification type="select" style={{border: "0"}}label="企业营业执照" placeholder="注册号、统一社会信用代码、组织机构代码" required showIcon={false}/> */}
        <FromListCertification onInput={(ev: any) => setFormData({ ...formData, business_license: ev.detail.value })} value={formData.business_license} style={{ border: '0' }} label="企业营业执照" placeholder="注册号、统一社会信用代码、组织机构代码" required />
        <View onClick={() => handleUploadImage('business_license_url')} className="certification-upload">
          {(formData as any)?.business_license_url
            ? <>
              <Text>营业执照正面</Text>
              <View className="certification-button">
                <View onClick={e => handleViewImage(e, (formData as any)?.business_license_url)}>查看证件</View>
                <View>重新上传</View>
              </View>
              <Image mode="aspectFit" src={(formData as any)?.business_license_url} />
            </>
            : <View className="certification-upload-no">
              <View className="certification-upload-no-icon">+</View>
              <View className="certification-upload-no-tips">上传营业执照正面</View>
            </View>
          }
        </View>
      </View>
      <View className="certification-content">
        <View className="certification-title">法人认证</View>
        <FromListCertification onInput={(ev: any) => setFormData({ ...formData, legal_person: ev.detail.value })} value={formData.legal_person} label="法人代表" placeholder="填写法人名称" required />
        <FromListCertification style={{ border: '0' }} onInput={(ev: any) => setFormData({ ...formData, legal_person_identity: ev.detail.value })} value={formData.legal_person_identity} label="法人身份" placeholder="填写法人代表身份证号" required />
        <View onClick={() => handleUploadImage(0)} className="certification-upload">
          {(formData as any)?.legal_person_identity_url[0]
            ? <>
              <Text>营业执照正面</Text>
              <View className="certification-button">
                <View onClick={e => handleViewImage(e, (formData as any)?.legal_person_identity_url[0])}>查看证件</View>
                <View>重新上传</View>
              </View>
              <Image mode="aspectFit" src={(formData as any)?.legal_person_identity_url[0]} />
            </>
            : <View className="certification-upload-no">
              <View className="certification-upload-no-icon">+</View>
              <View className="certification-upload-no-tips">上传身份证正面</View>
            </View>
          }
        </View>
        <View onClick={() => handleUploadImage(1)} className="certification-upload">
          {(formData as any)?.legal_person_identity_url[1]
            ? <>
              <Text>营业执照正面</Text>
              <View className="certification-button">
                <View onClick={e => handleViewImage(e, (formData as any)?.legal_person_identity_url[1])}>查看证件</View>
                <View>重新上传</View>
              </View>
              <Image mode="aspectFit" src={(formData as any)?.legal_person_identity_url[1]} />
            </>
            : <View className="certification-upload-no">
              <View className="certification-upload-no-icon">+</View>
              <View className="certification-upload-no-tips">上传身份证正面</View>
            </View>
          }
        </View>
      </View>
      <View className="certification-footer">
        <View className="certification-footer-button">
          <Navigator openType="navigateBack">取消</Navigator>
          <View onClick={handleSave}>{[3, 4].includes((adminUserInfo as any)?.authentication_status) ? '重新认证' : '提交'}</View>
        </View>
      </View>
    </View>
  )
}

export default Certification
