import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import ZexhiBtn from '@/components/ZexhiBtn'
import { Button, Form, FormInstance, Input } from 'antd'
import ZinfoPop from '@/components/ZinfoPop'
import history from '@/utils/history'
import classNames from 'classnames'
import { MessageFu } from '@/utils/message'
import delImg from '@/assets/img/exhibit/del.png'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B3_APIgetList, B4_APIsave } from '@/store/action/all'
import { B3ListApiType } from '../B3start/type'

function B4form() {
  // useEffect(() => {
  //   FormBoxRef.current?.setFieldsValue({
  //     name1: '王大锤',
  //     phone1: '18702025091',
  //     identity1: '421083199504071212'
  //   })
  // }, [])

  // 获取路由参数
  const [urlObj, setUrlObj] = useState({
    bookDate: '',
    bookId: 0,
    time: ''
  })

  const urlObjTemp: any = useParams()

  const getInfoFu = useCallback(async () => {
    const res = await B3_APIgetList()
    if (res.code === 0) {
      const list: B3ListApiType[] = res.data
      const index = Number(urlObjTemp.index)

      setUrlObj({
        bookDate: urlObjTemp.bookDate.replaceAll('_', '-'),
        bookId: list[index].id,
        time: list[index].time
      })
    }
  }, [urlObjTemp])

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

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

  const [formArr, setFormArr] = useState([{ id: 1 }])
  const formArrNumRef = useRef(1)

  // 点击新增 参观人
  const addFormFu = useCallback(() => {
    if (formArr.length >= 3) return MessageFu.warning('最多3位!')
    setFormArr([...formArr, { id: formArrNumRef.current + 1 }])
    formArrNumRef.current += 1
  }, [formArr])

  // 点击删除 参观人
  const delFormFu = useCallback(
    (id: number) => {
      setFormArr(formArr.filter(v => v.id !== id))
    },
    [formArr]
  )

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

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

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const arr: any = []

      formArr.forEach(v => {
        arr.push({
          bookDate: urlObj.bookDate,
          bookId: urlObj.bookId,
          time: urlObj.time,
          name: values[`name${v.id}`],
          phone: values[`phone${v.id}`],
          identity: values[`identity${v.id}`]
        })
      })
      const res = await B4_APIsave(arr)
      if (res.code === 0) setTitPop('succ')
    },
    [formArr, urlObj]
  )

  return (
    <div className={styles.B4form}>
      <div className='B4main'>
        <div className='B4top'>
          <p>
            <span>预约日期：</span>
            {urlObj.bookDate}
          </p>
          <p>
            <span>入馆时间：</span>
            {urlObj.time}
          </p>
        </div>

        {/* 按钮 */}
        <div
          className={classNames('B4addBtn', formArr.length >= 3 ? 'myBtnNo' : '')}
          onClick={addFormFu}
        >
          新增参观人（最多3位）
        </div>

        <div className='B4KaBox'>
          <Form
            ref={FormBoxRef}
            name='basic'
            // labelCol={{ span: 3 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete='off'
            scrollToFirstError
          >
            {/* 卡片 */}
            {formArr.map((item, index) => (
              <div className='B4Ka' key={item.id}>
                <div className='B4tit'>
                  <div className='B4titTxt'>参观人信息{index + 1}</div>

                  {formArr.length <= 1 ? (
                    <div></div>
                  ) : (
                    <MyPopconfirm
                      txtK='删除'
                      onConfirm={() => delFormFu(item.id)}
                      Dom={
                        <div className='B4titDel'>
                          <img src={delImg} alt='' /> 删除
                        </div>
                      }
                    />
                  )}
                </div>

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

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

                <Form.Item
                  label='身份证号'
                  name={`identity${item.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>
            ))}

            {/* 底部按钮 */}
            <ZexhiBtn
              nextFu={() => {}}
              FormBtn={
                <Button className='FormBtn' type='primary' htmlType='submit'>
                  提交
                </Button>
              }
            />
          </Form>
        </div>
      </div>

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

const MemoB4form = React.memo(B4form)

export default MemoB4form
