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 } 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 } from '@/utils/domShow'
import dayjs from 'dayjs'
import htmlToPdf2 from '@/utils/htmlToPdf2'
import { MessageFu } from '@/utils/message'
import ZinfoPop from '@/components/ZinfoPop'
import history from '@/utils/history'

type FormType = {
  name: string
  phone: string
  ID: string
  num1: null | number
  num2: null | null
  jigou: string
  miaoshu: string
}

function A5order() {
  useEffect(() => {
    FormBoxRef.current?.setFieldsValue({
      name: '王大锤',
      phone: '18702025091',
      ID: '421083199504071212',
      num1: 3,
      num2: null,
      jigou: '机构机构',
      miaoshu: ''
    })
  }, [])

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

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

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

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

  //  通过校验点击确定
  const onFinish = useCallback(async (values: FormType) => {
    setTitPop('succ')

    console.log(123, values)
    // domShowFu('#AsyncSpinLoding', true)

    // setText({
    //   1: values.jigou.replaceAll(/(\n|\r|\r\n)/g, '<br />'),
    //   2: values.miaoshu.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 = '预约申请单'

    //     htmlToPdf2(dom, name, () => {
    //       // 打开预约成功的弹窗
    //       // setTime('')
    //       // domShowFu('#AsyncSpinLoding', false)
    //     })
    //   } else {
    //     MessageFu.warning('找不到元素!')
    //     setTime('')
    //     domShowFu('#AsyncSpinLoding', false)
    //   }
    // }, 500)
  }, [])

  const [fileUrl, setFileUrl] = useState({
    src: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    name: ''
  })

  return (
    <div className={styles.A5order}>
      <TopCom txt='填写信息' />
      <div className={classNames('A5main')}>
        <div className='A5list'>
          <div className='A5listMain'>
            {/* 顶部 */}
            <div className='A5lTop'>
              <p>
                <span>预约日期：</span>11月21日上午
              </p>
              <p>
                <span>预约课程：</span>英语课程英语课程英语
              </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
              >
                {/* 第一个卡片 */}
                <div className='A5lKa'>
                  <div className='A5tit'>负责人信息</div>

                  <Form.Item
                    label='负责人姓名'
                    name='name'
                    rules={[{ required: true, message: '请输入负责人姓名!' }]}
                    getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
                  >
                    <Input placeholder='请输入内容，不超过6个字' maxLength={6} />
                  </Form.Item>

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

                  <Form.Item
                    label='身份证号'
                    name='ID'
                    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='请输入18位证件编码' maxLength={18} />
                  </Form.Item>
                </div>

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

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

                  <Form.Item className='A5llmove' label='随堂老师人数' name='num2'>
                    <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='jigou'
                        rules={[{ required: true, message: '请输入所属机构!' }]}
                        getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
                      >
                        <TextArea autoSize placeholder='请输入内容，不超过20个字' maxLength={20} />
                      </Form.Item>

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

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

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

                {time ? null : (
                  <div className='A5LA1'>
                    预约单模板
                    <a className='A5LA1btn' href='xxx' download='预约单模板'>
                      下载
                    </a>
                  </div>
                )}

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

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

                        <MyPopconfirm
                          txtK='删除'
                          onConfirm={() => setFileUrl({ src: '', name: '' })}
                          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
