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, InputNumber, Select } 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'
import ZselectCity from '@/components/ZselectCity'
import TextArea from 'antd/es/input/TextArea'
import { papersSelArr } from './data'

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

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

  // 路由参数key，1:个人/2:团体
  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 >= 5) return MessageFu.warning('最多5位!')
    setFormArr([...formArr, { id: formArrNumRef.current + 1 }])
    formArrNumRef.current += 1
  }, [formArr])

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

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

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

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

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      if (values.teamPcs && values.teamPcs > 20) return MessageFu.warning('参团人数最多20人!')

      const cityArr = selectCityRef.current.getValue()
      if (cityArr.length < 2) return MessageFu.warning('请选择地区!')

      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}`],
          papers: values[`papers${v.id}`],
          province: cityArr[0],
          city: cityArr[1]
        })
      })

      const obj = {
        info: arr,
        teamDesc: values.teamDesc,
        teamPcs: values.teamPcs,
        type: urlObjTemp.key === '1' ? 'person' : 'team'
      }

      // if (1 + 1 === 2) {
      //   console.log(123, obj)

      //   return
      // }

      const res = await B4_APIsave(obj)
      if (res.code === 0) setTitPop('succ')
    },
    [formArr, urlObj.bookDate, urlObj.bookId, urlObj.time, urlObjTemp.key]
  )

  return (
    <div className={styles.B4form}>
      <div className='B4main'>
        <div className='B4top'>
          <p>
            <span>预约日期：</span>
            {urlObj.bookDate}
          </p>
          <p>
            <span>入馆时间：</span>
            {urlObj.time}
          </p>
          <p>
            <span>预约类型：</span>
            {urlObjTemp.key === '1' ? '个人预约' : '团队预约'}
          </p>
        </div>

        {/* 按钮 */}
        {/* 个人预约才有 */}
        {urlObjTemp.key === '1' ? (
          <div
            className={classNames('B4addBtn', formArr.length >= 5 ? 'myBtnNo' : '')}
            onClick={addFormFu}
          >
            新增参观人（最多5位）
          </div>
        ) : null}

        {/* 地区选择 */}
        <div className='B4KaBox0'>
          <div className='B4KaBoxll'>
            <span>* </span>来自地区
          </div>
          <div className='B4KaBoxrr'>
            <ZselectCity ref={selectCityRef} />
          </div>
        </div>

        <div className='B4KaBox'>
          <Form
            ref={FormBoxRef}
            name='basic'
            // labelCol={{ span: 3 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete='off'
            scrollToFirstError
            initialValues={{ papers1: '内地身份证' }}
          >
            {/* 卡片 */}
            {formArr.map((item, index) => (
              <div className='B4Ka' key={item.id}>
                <div className='B4tit'>
                  <div className='B4titTxt'>
                    {urlObjTemp.key === '1' ? `参观人信息${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.trim()}
                >
                  <Input placeholder='请输入内容' 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='请输入联系方式' maxLength={30} />
                </Form.Item>

                <Form.Item
                  label='证件类型'
                  name={`papers${item.id}`}
                  rules={[{ required: true, message: '请选择证件类型!' }]}
                >
                  <Select placeholder='请选择证件类型' options={papersSelArr} />
                </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='请输入证件号码' maxLength={30} />
                </Form.Item>
              </div>
            ))}

            {/* 团体才有的，团队信息 */}
            {urlObjTemp.key === '2' ? (
              <div className='B4Ka'>
                <div className='B4tit'>
                  <div className='B4titTxt'>团队信息</div>
                </div>

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

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

            {/* 底部按钮 */}
            <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
