import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import TopCom from '@/components/TopCom'
import classNames from 'classnames'
import { Button, Form, FormInstance, Input, InputNumber, Select } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { EyeOutlined, CloseOutlined } from '@ant-design/icons'
import MyPopconfirm from '@/components/MyPopconfirm'
import { ImageViewer } from 'antd-mobile'
import { domShowFu, fileDomInitialFu } from '@/utils/domShow'
import dayjs from 'dayjs'
import htmlToPdf2 from '@/utils/htmlToPdf2'
import { MessageFu } from '@/utils/message'
import ZinfoPop from '@/components/ZinfoPop'
import history, { wxDownFu } from '@/utils/history'
import { useParams } from 'react-router-dom'

import {
  A5_APIgetInfo,
  A5_APIgetTemplateUrl,
  A5_APIsave,
  API_upFile,
  upFileFu
} from '@/store/action/all'
import { FileType } from '@/types'
import { baseURL } from '@/utils/http'
import ZselectCity from '@/components/ZselectCity'
import { papersSelArr } from '../B4form/data'
import useWxXcx from '@/components/AownUse/useWxXcx'

type FormType = {
  name: string
  phone: string
  ID: string
  pcsStudent: null | number
  pcsTeacher: null | null
  unit: string
  remark: string
}

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

  // 获取路由参数
  const [urlObj, setUrlObj] = useState({
    id: 0,
    bookDate: '',
    bookTime: '',
    name: '',
    subjectBookTimeId: ''
  })

  // useEffect(() => {
  //   // console.log('获取参数', urlObj)
  // }, [urlObj])

  const urlObjTemp: any = useParams()

  const getInfo = useCallback(async () => {
    const res = await A5_APIgetInfo(Number(urlObjTemp.id))
    if (res.code === 0) {
      setUrlObj({
        id: Number(urlObjTemp.id),
        bookDate: urlObjTemp.bookDate,
        bookTime: urlObjTemp.bookTime,
        name: res.data.name,
        subjectBookTimeId: urlObjTemp.subjectBookTimeId
      })
    }
  }, [urlObjTemp])

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

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

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

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

  // useEffect(() => {
  //   FormBoxRef.current?.setFieldsValue({
  //     name: '王大锤',
  //     phone: '18702025091',
  //     identity: '421083199504071212',
  //     pcsStudent: 3,
  //     pcsTeacher: null,
  //     unit: '机构机构',
  //     remark: ''
  //   })
  // }, [])

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

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

  // 点击提交的页面元素显示和隐藏
  const [time, setTime] = useState('')
  // 导出pdf文本域换行问题
  const [tetx, setText] = useState({
    1: '',
    2: ''
  })

  // 附件图片信息
  const [fileObj, setFileObj] = useState({} as FileType)

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

  // 选择地区的ref
  const selectCityRef = useRef<any>(null)

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: FormType) => {
      const cityArr = selectCityRef.current.getValue()
      if (cityArr.length < 2) return MessageFu.warning('请选择地区!')

      domShowFu('#AsyncSpinLoding', true)

      setText({
        1: (values.unit || '').replaceAll(/(\n|\r|\r\n)/g, '<br />'),
        2: (values.remark || '').replaceAll(/(\n|\r|\r\n)/g, '<br />')
      })

      const time = dayjs(new Date()).format('YYYY-MM-DD HH:mm')
      setTime(time)
      window.setTimeout(() => {
        const dom = document.querySelector('.A5listMain') as HTMLDivElement
        if (dom) {
          const name = '预约申请单.pdf'

          // 成功之后的回调
          htmlToPdf2(dom, name, async myfile => {
            domShowFu('#AsyncSpinLoding', false)
            // 创建FormData对象
            const fd = new FormData()
            fd.append('type', 'doc')
            fd.append('dirCode', 'orderDoc')
            fd.append('moduleName', 'apply')
            fd.append('isDb', 'true')
            fd.append('file', myfile)

            // for (var [a, b] of fd.entries()) {
            //   console.log(a, b)
            // }

            try {
              const res = await API_upFile(fd, 'wx/upload')
              if (res.code === 0) {
                const obj = {
                  ...values,
                  bookDate: urlObj.bookDate,
                  bookTime: urlObj.bookTime,
                  subjectName: urlObj.name,
                  fileIds: res.data.id + '',
                  pcsTeacher: values.pcsTeacher === null ? 0 : values.pcsTeacher,
                  subjectBookTimeId: Number(urlObj.subjectBookTimeId),

                  province: cityArr[0],
                  city: cityArr[1]
                }

                if (fileObj.id) obj.fileIds += `,${fileObj.id}`

                const res2 = await A5_APIsave(obj)
                if (res2.code === 0) {
                  // 打开预约成功的弹窗
                  setTitPop('succ')
                } else setTime('')
              }
              fileDomInitialFu()
            } catch (error) {
              setTime('')
              fileDomInitialFu()
            }
          })
        } else {
          MessageFu.warning('找不到元素!')
          setTime('')
          domShowFu('#AsyncSpinLoding', false)
        }
      }, 500)
    },
    [fileObj.id, urlObj]
  )

  const myInput = useRef<HTMLInputElement>(null)

  // 上传图片
  const handeUpPhoto = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    upFileFu(
      e,
      'wx/upload',
      5,
      ['image/jpeg', 'image/png'],
      '.jpg,.png',
      data => setFileObj(data),
      { type: 'img', dirCode: 'orderImg', moduleName: 'apply', isDb: 'true' }
    )
  }, [])

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

      <TopCom txt='填写信息' />
      <div className={classNames('A5main')}>
        <div className='A5list'>
          <div className='A5listMain'>
            {/* 顶部 */}
            <div className='A5lTop'>
              <p>
                <span>预约时间：</span>
                {urlObj.bookDate} {urlObj.bookTime}
              </p>
              <p>
                <span>预约课程：</span>
                {urlObj.name}
              </p>
              {time ? (
                <p>
                  <span>申请时间：</span>
                  {time}
                </p>
              ) : null}
            </div>
            <div className='A5lKaBox'>
              <Form
                ref={FormBoxRef}
                name='basic'
                // labelCol={{ span: 3 }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete='off'
                scrollToFirstError
                initialValues={{ papers: '内地身份证' }}
              >
                {/* 第一个卡片 */}
                <div className='A5lKa'>
                  <div className='A5tit'>负责人信息</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
                    label='证件类型'
                    name='papers'
                    rules={[{ required: true, message: '请选择证件类型!' }]}
                  >
                    <Select placeholder='请选择证件类型' options={papersSelArr} />
                  </Form.Item>

                  <Form.Item
                    label='证件号码'
                    name='identity'
                    rules={[
                      { required: true, message: '请输入证件号码!' }
                      // {
                      //   pattern:
                      //     /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                      //   message: '请输入正确格式的证件号码!'
                      // }
                    ]}
                  >
                    <Input placeholder='请输入证件号码' maxLength={30} />
                  </Form.Item>
                </div>

                {/* 第二个卡片 */}
                <div className='A5lKa'>
                  <div className='A5tit'>团队信息</div>

                  <Form.Item
                    label='参观学生人数'
                    name='pcsStudent'
                    rules={[{ required: true, message: '请输入参观学生人数!' }]}
                  >
                    <InputNumber min={0} max={999} precision={0} placeholder='请输入数字' />
                  </Form.Item>

                  <Form.Item className='A5llmove' label='随堂老师人数' name='pcsTeacher'>
                    <InputNumber
                      min={0}
                      max={999}
                      precision={0}
                      placeholder={time ? ' - ' : '请输入数字'}
                    />
                  </Form.Item>

                  {/* 文本域不换行问题 */}
                  {time ? (
                    <>
                      <div className='A5TextPdf'>
                        <div>
                          <span>*</span>所属机构
                        </div>
                        <div dangerouslySetInnerHTML={{ __html: tetx[1] || ' - ' }}></div>
                      </div>
                      <div className='A5TextPdf'>
                        <div>
                          <span style={{ opacity: 0 }}>*</span>团队描述
                        </div>
                        <div dangerouslySetInnerHTML={{ __html: tetx[2] || ' - ' }}></div>
                      </div>
                    </>
                  ) : (
                    <>
                      <Form.Item
                        className='A5Text20'
                        label='所属机构'
                        name='unit'
                        rules={[{ required: true, message: '请输入所属机构!' }]}
                        getValueFromEvent={e => e.target.value.trim()}
                      >
                        <TextArea autoSize placeholder='请输入内容，不超过20个字' maxLength={20} />
                      </Form.Item>

                      <Form.Item label='团队描述' name='remark' className='A5Text'>
                        <TextArea
                          autoSize
                          maxLength={200}
                          placeholder='请输入内容，不超过200个字'
                        />
                      </Form.Item>
                    </>
                  )}

                  {/* 地区选择 */}
                  <div className='A5lKaRow'>
                    <div className='A5lKaRowll'>
                      <span>* </span>来自地区
                    </div>
                    <div className='A5lKaRowrr'>
                      <ZselectCity ref={selectCityRef} />
                    </div>
                  </div>
                </div>

                {time ? null : (
                  <Button className='A5btn' type='primary' htmlType='submit'>
                    提交
                  </Button>
                )}
              </Form>

              {/* 第三个卡片 */}
              <div className='A5lKa' hidden={!!time && !fileObj.filePath}>
                <div className='A5tit'>健康生活教育课程预约单</div>

                {time ? null : (
                  <div className='A5LA1'>
                    预约单模板
                    {templateUrl ? (
                      isWXxcx ? (
                        <div className='A5LA1btn' onClick={() => wxDownFu(templateUrl)}>
                          下载
                        </div>
                      ) : (
                        <a className='A5LA1btn' href={baseURL + templateUrl} download='预约单模板'>
                          下载
                        </a>
                      )
                    ) : (
                      <div className='A5LA1btn A5LA1btnNo'>暂无文件</div>
                    )}
                  </div>
                )}

                {time ? null : (
                  <div className='A5LA1'>
                    <div className='A5LA1ll'>
                      <p>上传填写结果</p>
                      <span>仅限jpg，png格式；大小不超过5M；最多1个文件</span>
                    </div>
                    <div
                      className='A5LA1btn A5LA1btn2'
                      onClick={() => myInput.current?.click()}
                      hidden={!!fileObj.filePath}
                    >
                      上传
                    </div>
                  </div>
                )}

                {fileObj.filePath ? (
                  <div className='A5file'>
                    <img src={baseURL + fileObj.filePath} alt='' />
                    {time ? null : (
                      <div className='A5file2'>
                        <EyeOutlined
                          onClick={() => ImageViewer.show({ image: baseURL + fileObj.filePath })}
                        />

                        <MyPopconfirm
                          txtK='删除'
                          onConfirm={() => setFileObj({} as FileType)}
                          Dom={<CloseOutlined className='clearCover' />}
                        />
                      </div>
                    )}
                  </div>
                ) : null}
                {time ? null : (
                  <div className='A5LAkuang'>
                    <div>
                      <p>1.下载模板</p>
                      <p>2.填写模板 </p>
                      <p>3.将填写结果导出PNG或JPG图片格式</p>
                      <p>4.上传填写结果</p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 预约成功的弹窗 */}
      {titPop ? <ZinfoPop type={titPop as 'succ'} callFu={() => history.push('/my')} /> : null}
    </div>
  )
}

const MemoA5order = React.memo(A5order)

export default MemoA5order
