import {useEffect, useState} from "react";
import {Image} from '@nutui/nutui-react-taro'
import {ConfigProvider} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'

import {
  Form,
  Button,
  Input,
  Radio,
} from '@nutui/nutui-react-taro'
import {UserVerify} from "@/api/system/userVerify/model";
import {addUserVerify, myUserVerify, updateUserVerify} from "@/api/system/userVerify";
import {uploadFile} from "@/api/system/file";
import {pushReviewReminder} from "@/api/sdy/sdyTemplateMessage";

function Index() {
  const [isUpdate, setIsUpdate] = useState<boolean>(false)
  const [submitText, setSubmitText] = useState<string>('提交')

  const [FormData, setFormData] = useState<UserVerify>({
    userId: undefined,
    type: undefined,
    phone: undefined,
    avatar: undefined,
    realName: undefined,
    idCard: undefined,
    birthday: undefined,
    sfz1: undefined,
    sfz2: undefined,
    zzCode: undefined,
    zzImg: undefined,
    status: undefined,
    statusText: undefined,
    comments: undefined
  })
  const reload = () => {
    myUserVerify({}).then(data => {
      if (data) {
        setIsUpdate(true);
        setFormData(data)
        if(data.status == 2){
          setSubmitText('重新提交')
        }
      } else {
        setFormData({
          type: 0
        })
      }
    })
  }

  // 提交表单
  const submitSucceed = (values: any) => {
    console.log('提交表单', values);
    if (FormData.status != 2 && FormData.status != undefined) return false;
    if (FormData.type == 0) {
      if (!FormData.sfz1 || !FormData.sfz2) {
        Taro.showToast({
          title: '请上传身份证正反面',
          icon: 'none'
        });
        return false;
      }
      if (!FormData.realName || !FormData.idCard) {
        Taro.showToast({
          title: '请填写真实姓名和身份证号码',
          icon: 'none'
        });
        return false;
      }
    }
    if (FormData.type == 1) {
      if (!FormData.zzImg) {
        Taro.showToast({
          title: '请上传营业执照',
          icon: 'none'
        });
        return false;
      }
      if (!FormData.name || !FormData.zzCode) {
        Taro.showToast({
          title: '请填写主体名称和营业执照号码',
          icon: 'none'
        });
        return false;
      }
    }
    if(!FormData.realName){
      Taro.showToast({
        title: '请填写真实姓名',
        icon: 'none'
      });
      return false;
    }
    const saveOrUpdate = isUpdate ? updateUserVerify : addUserVerify;
    saveOrUpdate({...FormData, status: 0}).then(() => {
      Taro.showToast({title: `提交成功`, icon: 'success'})
      if(!isUpdate){
        // 发送派单成功提醒 0FBKFCWXe8WyjReYXwSDEXf1-pxYKQXE0quZre3GYIM
        pushReviewReminder({
          realName: FormData.realName,
        }).then()
      }
      setTimeout(() => {
        return Taro.navigateBack()
      }, 1000)
    }).catch(() => {
      Taro.showToast({
        title: '提交失败',
        icon: 'error'
      });
    }).finally(() => {
      reload();
    })
  }
  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  const uploadSfz1 = () => {
    if (FormData.status != 2 && FormData.status != undefined) return false;
    uploadFile().then(data => {
      setFormData({
        ...FormData,
        sfz1: data.url
      })
    });
  }

  const uploadSfz2 = () => {
    if (FormData.status != 2 && FormData.status != undefined) return false;
    uploadFile().then(data => {
      setFormData({
        ...FormData,
        sfz2: data.url
      })
    });
  }


  const uploadZzImg = () => {
    if (FormData.status != 2 && FormData.status != undefined) return false;
    uploadFile().then(data => {
      setFormData({
        ...FormData,
        zzImg: data.url
      })
    });
  }

  useEffect(() => {
    reload()
  }, []);

  return (
    <>
      <div className={'p-4'}>
        <ConfigProvider>
          <Form
            divider
            initialValues={FormData}
            labelPosition="left"
            onFinish={(values) => submitSucceed(values)}
            onFinishFailed={(errors) => submitFailed(errors)}
            footer={
              FormData.status != 1 && FormData.status != 0 && (
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'center',
                    width: '100%'
                  }}
                >
                  <Button nativeType="submit" block type={'info'}
                          disabled={FormData.status != 2 && FormData.status != undefined}>
                    {submitText}
                  </Button>
                </div>
              )
            }
          >
            <Form.Item
              label="类型"
              name="type"
              initialValue={FormData.type}
              required
            >
              <Radio.Group value={FormData?.type} direction="horizontal"
                           disabled={FormData.status != 2 && FormData.status != undefined}
                           onChange={(value) => setFormData({...FormData, type: value})}>
                <Radio key={0} value={0}>
                  个人
                </Radio>
                {/*<Radio key={1} value={1}>*/}
                {/*  企业*/}
                {/*</Radio>*/}
              </Radio.Group>
            </Form.Item>
            {
              // 个人类型
              FormData.type == 0 && (
                <>
                  <Form.Item
                    label={'真实姓名'}
                    name="realName"
                    required
                    initialValue={FormData.realName}
                    rules={[{message: '请输入真实姓名'}]}
                  >
                    <Input
                      placeholder={'请输入真实姓名'}
                      type="text"
                      disabled={FormData.status != 2 && FormData.status != undefined}
                      value={FormData?.realName}
                      onChange={(value) => setFormData({...FormData, realName: value})}
                    />
                  </Form.Item>
                  <Form.Item
                    label={'身份证号码'}
                    name="idCard"
                    required
                    initialValue={FormData.idCard}
                    rules={[{message: '请输入身份证号码'}]}
                  >
                    <Input
                      placeholder="请输入身份证号码"
                      type="text"
                      value={FormData?.idCard}
                      disabled={FormData.status != 2 && FormData.status != undefined}
                      maxLength={18}
                      onChange={(value) => setFormData({...FormData, idCard: value})}
                    />
                  </Form.Item>
                  <Form.Item
                    label={'上传证件'}
                    name="image"
                    required
                    rules={[{message: '请上传身份证正反面'}]}
                  >
                    <div className={'flex gap-2'}>
                      <div onClick={uploadSfz1}>
                        <Image src={FormData.sfz1} lazyLoad={false}
                               radius="10%" width="80" height="80"/>
                      </div>
                      <div onClick={uploadSfz2}>
                        <Image src={FormData.sfz2} mode={'scaleToFill'} lazyLoad={false}
                               radius="10%" width="80" height="80"/>
                      </div>
                    </div>
                  </Form.Item>
                </>
              )
            }
            {
              // 企业类型
              FormData.type == 1 && (
                <>
                  <Form.Item
                    label={'主体名称'}
                    name="name"
                    required
                    initialValue={FormData.name}
                    rules={[{message: '请输入公司名称或单位名称'}]}
                  >
                    <Input
                      placeholder={'请输入主体名称'}
                      type="text"
                      value={FormData?.name}
                      onChange={(value) => setFormData({...FormData, name: value})}
                    />
                  </Form.Item>
                  <Form.Item
                    label={'营业执照号码'}
                    name="zzCode"
                    required
                    initialValue={FormData.zzCode}
                    rules={[{message: '请输入营业执照号码'}]}
                  >
                    <Input
                      placeholder="请输入营业执照号码"
                      type="text"
                      value={FormData?.zzCode}
                      maxLength={18}
                      onChange={(value) => setFormData({...FormData, zzCode: value})}
                    />
                  </Form.Item>
                  <Form.Item
                    label={'上传营业执照'}
                    name="zzImg"
                    required
                    rules={[{message: '请上传营业执照'}
                    ]}
                  >
                    <div onClick={uploadZzImg}>
                      <Image src={FormData.zzImg} mode={'scaleToFill'} lazyLoad={false}
                             radius="10%" width="80" height="80"/>
                    </div>
                  </Form.Item>
                </>
              )
            }
            {
              FormData.status != undefined && (
                <Form.Item
                  label={'审核状态'}
                  name="status"
                >
                  <span className={'text-gray-500'}>{FormData.statusText}</span>
                </Form.Item>
              )
            }

            {FormData.status == 2 && (
              <Form.Item
                label={'驳回原因'}
                name="comments"
              >
                <div className={'flex text-orange-500'}>
                  {FormData.comments}
                </div>
              </Form.Item>
            )}

          </Form>
        </ConfigProvider>
      </div>
    </>
  )
}

export default Index
