import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import TopCom from '@/components/TopCom'
import { Button, Form, FormInstance, Input } from 'antd'
import ZinfoPop from '@/components/ZinfoPop'
import history, { wxDownFu } from '@/utils/history'
import TextArea from 'antd/es/input/TextArea'
import { CloudUploadOutlined, EyeOutlined, CloseOutlined } from '@ant-design/icons'
import MyPopconfirm from '@/components/MyPopconfirm'
import { ImageViewer } from 'antd-mobile'
import { MessageFu } from '@/utils/message'
import { A5_APIgetTemplateUrl, A8_APIsave, upFileFu } from '@/store/action/all'
import { FileType } from '@/types'
import { baseURL } from '@/utils/http'
import useWxXcx from '@/components/AownUse/useWxXcx'

function A8proof() {
  // 是否是微信小程序
  const { isWXxcx } = useWxXcx()

  const urlObj: any = useParams()

  const canRef = useRef('')

  useEffect(() => {
    if (urlObj.val) {
      canRef.current = urlObj.val
    }
  }, [urlObj.val])

  // useEffect(() => {
  //   FormBoxRef.current?.setFieldsValue({
  //     name: '王大锤',
  //     phone: '18702025091',
  //     unit: '阿三大苏打'
  //   })
  // }, [])

  // 附件列表
  const [fileArr, setFileArr] = useState<FileType[]>([])

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, [])

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      if (fileArr.length <= 0) return MessageFu.warning('请上传授权或同意文件!')

      let fileIds = ''
      fileIds = fileArr.map(v => v.id).join(',')
      const obj = {
        ...values,
        fileIds,
        type: canRef.current
      }

      const res = await A8_APIsave(obj)
      if (res.code === 0) {
        setTitPop('succ')
      }
    },
    [fileArr]
  )

  // 打开提示弹窗
  const [titPop, setTitPop] = useState('')

  const myInput = useRef<HTMLInputElement>(null)

  // 上传
  const handeUpPhoto = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      upFileFu(
        e,
        'wx/upload',
        5,
        ['image/jpeg', 'image/png', 'application/pdf'],
        '.pdf,.jpg,.png',
        data => setFileArr([...fileArr, data]),
        { type: 'doc', dirCode: 'ProofDoc', moduleName: 'auth', isDb: 'true' }
      )
    },
    [fileArr]
  )

  // 获取模板下载地址
  const [templateUrl, setTemplateUrl] = useState('')

  const getTemplateUrlFu = useCallback(async () => {
    const res = await A5_APIgetTemplateUrl(14)
    if (res.code === 0) {
      const obj = JSON.parse(res.data.rtf)
      setTemplateUrl(obj.filePath)
    }
  }, [])

  useEffect(() => {
    getTemplateUrlFu()
  }, [getTemplateUrlFu])

  return (
    <div className={styles.A8proof}>
      <input
        id='upInput'
        type='file'
        // accept='.pdf,.jpg,.png'
        ref={myInput}
        onChange={e => handeUpPhoto(e)}
      />

      <TopCom txt='团体认证' />
      <div className='A8main'>
        <div className='A8Center'>
          <Form
            ref={FormBoxRef}
            name='basic'
            // labelCol={{ span: 3 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete='off'
            scrollToFirstError
          >
            {/* 第一个卡片 */}
            <div className='A8lKa'>
              <div className='A8tit'>负责人信息</div>

              <Form.Item
                label='负责人姓名'
                name='name'
                rules={[{ required: true, message: '请输入负责人姓名!' }]}
                getValueFromEvent={e => e.target.value.trim()}
              >
                <Input placeholder='请输入内容' maxLength={6} />
              </Form.Item>

              <Form.Item
                label='联系方式'
                name='phone'
                rules={[
                  { required: true, message: '请输入联系方式!' }
                  // {
                  //   pattern: /^1[3-9][0-9]{9}$/,
                  //   message: '请输入正确格式的手机号!'
                  // }
                ]}
              >
                <Input placeholder='请输入联系方式' maxLength={30} />
              </Form.Item>

              <Form.Item
                className='A8Text'
                label='单位名称'
                name='unit'
                rules={[{ required: true, message: '请输入单位名称!' }]}
                // getValueFromEvent={e => e.target.value.trim()}
              >
                <TextArea placeholder='请输入内容，不超过50个字' maxLength={50} />
              </Form.Item>
            </div>

            {/* 中间的模板卡片 */}
            {templateUrl ? (
              <div className='A8lKa A8lKaDown'>
                <div className='A8lKaDown1'>认证模板文件</div>
                {isWXxcx ? (
                  <div className='A8lKaDown2' onClick={() => wxDownFu(templateUrl)}>
                    下载
                  </div>
                ) : (
                  <a className='A8lKaDown2' href={baseURL + templateUrl} download='认证模板'>
                    下载
                  </a>
                )}
              </div>
            ) : null}

            {/* 第二个卡片 */}
            <div className='A8lKa A8lKa2'>
              <div className='A8lKa2Top'>
                <div className='A8K2ll'>
                  <div className='A8K2ll_1'>
                    <span>* </span>上传授权或同意文件
                  </div>
                  <div className='A8K2ll_2'>仅限PDF，jpg，png格式；大小不超过5M；最多3个文件</div>
                </div>
                <div
                  onClick={() => myInput.current?.click()}
                  className='A8K2rr'
                  style={{
                    opacity: fileArr.length >= 3 ? '0' : '1',
                    pointerEvents: fileArr.length >= 3 ? 'none' : 'auto'
                  }}
                >
                  <CloudUploadOutlined />
                  上传
                </div>
              </div>
              {fileArr.length ? (
                <div className='A8lKa2File'>
                  {fileArr.map((item, index) => (
                    <div key={item.id} className='A8Frow'>
                      <div className='A8Frowll'>{item.fileName}</div>
                      <div className='A8Frowrr'>
                        {item.fileName.endsWith('.pdf') || item.fileName.endsWith('.PDF') ? null : (
                          <EyeOutlined
                            onClick={() => ImageViewer.show({ image: baseURL + item.filePath })}
                          />
                        )}

                        <MyPopconfirm
                          txtK='删除'
                          onConfirm={() => setFileArr(fileArr.filter((v, i) => i !== index))}
                          Dom={<CloseOutlined className='clearCover' />}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              ) : null}
            </div>

            <Button className='A8btn' type='primary' htmlType='submit'>
              提交
            </Button>
          </Form>
        </div>
      </div>
      {/* 预约成功的弹窗 */}
      {titPop ? (
        <ZinfoPop txt1='申请成功' type={titPop as 'succ'} callFu={() => history.push('/my?m=1')} />
      ) : null}
    </div>
  )
}

const MemoA8proof = React.memo(A8proof)

export default MemoA8proof
