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

import {
  Form,
  Button,
  Input,
  Radio,
  Cell,
  SearchBar
} from '@nutui/nutui-react-taro'
import {UserVerify} from "@/api/system/userVerify/model";
import {addUserVerify, myUserVerify, updateUserVerify} from "@/api/system/userVerify";
import {pageOrganizations} from "@/api/system/organization";

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

  const [FormData, setFormData] = useState<UserVerify>({
    userId: undefined,
    type: 0,
    phone: Taro.getStorageSync('Phone'),
    avatar: undefined,
    realName: undefined,
    idCard: undefined,
    birthday: undefined,
    sfz1: undefined,
    sfz2: undefined,
    zzCode: undefined,
    zzImg: undefined,
    organizationId: undefined,
    organizationName: undefined,
    userRoleId: Taro.getStorageSync(''),
    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
        })
      }
    })
    if(Taro.getStorageSync('Phone')){
      setFormData({...FormData, phone: Taro.getStorageSync('Phone')})
    }
  }

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  const searchSiteList = (keywords: string) => {
    pageOrganizations({keywords,limit: 5}).then(res => {
      setSiteList(res?.list || [])
    })
  }

  const onOrganizationChange = (item) => {
    console.log(item);

    setFormData({
      ...FormData,
      organizationId: item.organizationId,
      organizationName: item.organizationName
    })
  }

  // 提交表单
  const submitSucceed = (values: any) => {
    console.log('提交表单...',values)
    if (FormData.status != 2 && FormData.status != undefined) return false;
    if(FormData.organizationId == 0 || !FormData.organizationId){
      Taro.showToast({
        title: '请选择站点',
        icon: 'none'
      });
      return false;
    }
    if(!FormData.realName){
      Taro.showToast({
        title: '请填写真实姓名',
        icon: 'none'
      });
      return false;
    }
    console.log('提交表单', FormData);
    const saveOrUpdate = isUpdate ? updateUserVerify : addUserVerify;
    saveOrUpdate({...FormData, status: 0}).then(() => {
      Taro.showToast({title: `提交成功`, icon: 'success'})
      setTimeout(() => {
        return Taro.navigateBack()
      }, 1000)
    }).catch(() => {
      Taro.showToast({
        title: '提交失败',
        icon: 'error'
      });
    }).finally(() => {
      reload();
    })
  }

  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.status != 1 && (
              <>
                <ConfigProvider
                  theme={{
                    nutuiSearchbarBackground: '#ffffff',
                    nutuiSearchbarContentBackground: '#eee',
                    nutuiSearchbarInputTextAlign: 'right',
                  }}
                >
                  <SearchBar className={'mt-3'} placeholder={'搜索站点'} onChange={(val: string) => searchSiteList(val)} maxLength={10} />
                </ConfigProvider>
                <div className={'p-3'}
                >
                  <Radio.Group defaultValue={FormData.organizationId} direction="horizontal">
                    {siteList.map((item: any,index) => (
                      <Cell className={'px-2'} key={item.organizationId} onClick={() => onOrganizationChange(item)}>
                        <Radio key={index} value={item.organizationId}>{item.organizationName}</Radio>
                      </Cell>
                    ))}
                  </Radio.Group>
                  {/*{siteList.length == 0 && (*/}
                  {/*  <div className={'text-center'}>*/}
                  {/*    <span className={'text-gray-400 text-sm'}>没有搜索结果</span>*/}
                  {/*  </div>*/}
                  {/*)}*/}
                </div>
              </>

            )}

            {
              // 个人类型
              FormData.type == 0 && (
                <>
                  <Form.Item
                    label={'所属站点'}
                    name="organizationId"
                    required
                    initialValue={FormData.organizationName}
                    rules={[{message: '请输入所属站点'}]}
                  >
                    <Input
                      placeholder={'请输入所属站点'}
                      type="text"
                      disabled={FormData.status != 2 && FormData.status != undefined}
                      value={FormData?.organizationName}
                    />
                  </Form.Item>
                  <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="phone"
                    required
                    initialValue={FormData.phone}
                    rules={[{message: '请输入手机号码'}]}
                  >
                    <Input
                      placeholder={'请输入手机号'}
                      type="text"
                      disabled={FormData.status != 2 && FormData.status != undefined}
                      value={FormData?.phone}
                      onChange={(value) => setFormData({...FormData, phone: 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}*/}
                  {/*             radius="10%" width="80" height="80"/>*/}
                  {/*    </div>*/}
                  {/*    <div onClick={uploadSfz2}>*/}
                  {/*      <Image src={FormData.sfz2} mode={'scaleToFill'}*/}
                  {/*             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'}*/}
            {/*                 radius="10%" width="80" height="80"/>*/}
            {/*        </div>*/}
            {/*      </Form.Item>*/}
            {/*    </>*/}
            {/*  )*/}
            {/*}*/}
            {/*<Form.Item*/}
            {/*  label={'真实姓名'}*/}
            {/*  name="realName"*/}
            {/*  required*/}
            {/*  initialValue={FormData.realName}*/}
            {/*  rules={[{message: '请输入真实姓名'}]}*/}
            {/*>*/}
            {/*  <Input*/}
            {/*    placeholder={'请输入真实姓名'}*/}
            {/*    type="text"*/}
            {/*    value={FormData?.realName}*/}
            {/*    onChange={(value) => setFormData({...FormData, realName: value})}*/}
            {/*  />*/}
            {/*</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
