import { Form, Input, Modal } from 'antd'
import { FC, useEffect } from 'react'
import { D3StaffOversiderType } from '../../types'

export interface OutsiderModalProps {
  visible: boolean
  item: D3StaffOversiderType | null
  setVisible: (v: boolean) => void
  onOk: (item: D3StaffOversiderType) => void
  onCancel?: () => void
}

export const OutsiderModal: FC<OutsiderModalProps> = ({
  visible,
  item,
  setVisible,
  onOk,
  onCancel
}) => {
  const [form] = Form.useForm()

  const handleCancel = () => {
    setVisible(false)
    form.resetFields()
    onCancel?.()
  }

  const handleSubmit = async () => {
    if (!(await form.validateFields())) return

    onOk(form.getFieldsValue())
    handleCancel()
  }

  // const validateIdCard = (_: any, value: string) => {
  //   if (!value) return Promise.resolve()

  //   // 身份证简单正则
  //   const reg = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/
  //   if (!reg.test(value)) {
  //     return Promise.reject('请输入正确的身份证号')
  //   }

  //   // 校验位验证（18位身份证）
  //   if (value.length === 18) {
  //     const weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] // 加权因子
  //     const validate = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'] // 校验码

  //     let sum = 0
  //     for (let i = 0; i < 17; i++) {
  //       sum += parseInt(value.charAt(i)) * weight[i]
  //     }

  //     const mod = sum % 11
  //     if (value.charAt(17).toUpperCase() !== validate[mod]) {
  //       return Promise.reject('请输入正确的身份证号')
  //     }
  //   }

  //   return Promise.resolve()
  // }

  const validatePhone = (_: any, value: string) => {
    const reg = /^1[3-9]\d{9}$/
    if (value && !reg.test(value)) {
      return Promise.reject('请输入正确的手机号')
    }
    return Promise.resolve()
  }

  useEffect(() => {
    if (!item) return
    form.setFieldsValue(item)
  }, [item, form])

  return (
    <Modal title='外部人员' open={visible} onCancel={handleCancel} onOk={handleSubmit}>
      <Form form={form} labelCol={{ span: 5 }}>
        <Form.Item label='姓名' required rules={[{ required: true }]} name='name'>
          <Input maxLength={30} placeholder='请输入' />
        </Form.Item>
        <Form.Item label='联系方式' name='phone' rules={[{ validator: validatePhone }]}>
          <Input maxLength={30} placeholder='请输入' />
        </Form.Item>
        {/* <Form.Item label='身份证号' name='papers' rules={[{ validator: validateIdCard }]}>
          <Input maxLength={30} placeholder='请输入' />
        </Form.Item> */}
        <Form.Item label='所在单位' name='remark'>
          <Input maxLength={30} placeholder='请输入' />
        </Form.Item>
      </Form>
    </Modal>
  )
}
