import React, { useEffect, useState } from 'react';
import { InterListType, InterReqType } from '~/api/interface';
import { listCompanyAdd, listCompanyPage } from '~/api/interface/systemManageType';
import { Cascader, Form, Input, message, Modal } from 'antd';
import { SystemManageAPI } from '~/api';
import DistrictData from '~/assets/json/district.json';

// 列表的类型
type TableType = InterListType<listCompanyPage>;
// 请求的表单类型
type ReqType = InterReqType<listCompanyAdd>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}
const AddEditModal: React.FC<propType> = (props) => {
  // 参数
  const { title, open, closed, data } = props;
  /// 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 地区
  const [localList, setLocalList] = useState<
    {
      childInfo: any[];
      id: number;
      name: string;
    }[]
  >();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit({
          ...values,
          province: values?.area?.at(0),
          city: values?.area?.at(1),
          district: values?.area?.at(2),
          companyType: data?.id === 1 ? 0 : 1,
        });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType) => {
    const res = await SystemManageAPI[data?.id ? 'listCompanyUpdate' : 'listCompanyAdd']({
      ...values,
      id: Number(data?.id),
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // 获取地区信息
  const getSecondDistrictInfo = async () => {
    setLocalList(DistrictData || []);
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    getSecondDistrictInfo().then();
    if (!data) return;
    form.setFieldsValue({
      ...data,
      area: [data?.province, data?.city, data?.district],
    });
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      width={450}
    >
      <Form name='addForm' form={form} labelAlign='right' labelCol={{ span: 4 }}>
        <Form.Item
          label='单位名称'
          rules={[{ required: true, message: '请输入单位名称' }]}
          name='companyName'
        >
          <Input placeholder={'请输入单位名称'} maxLength={25} allowClear />
        </Form.Item>
        <Form.Item
          label='单位全称'
          rules={[{ required: false, message: '请输入单位全称' }]}
          name='fullName'
        >
          <Input placeholder={'请输入单位全称'} maxLength={50} allowClear />
        </Form.Item>
        <Form.Item
          label='行政区划'
          name='area'
          rules={[{ required: true, message: '请选择行政区划' }]}
        >
          <Cascader
            options={localList}
            placeholder='请选择行政区划'
            allowClear
            fieldNames={{
              label: 'name',
              value: 'name',
              children: 'childInfo',
            }}
          />
        </Form.Item>
        <Form.Item
          label='详细地址'
          name='address'
          rules={[{ required: true, message: '请输入详细地址' }]}
        >
          <Input.TextArea placeholder='请输入详细地址' maxLength={50} showCount />
        </Form.Item>
        <Form.Item label='联系人' name='companyUserName'>
          <Input placeholder='请输入联系人' maxLength={15} />
        </Form.Item>
        <Form.Item
          label='联系方式'
          name='phoneNum'
          rules={[
            () => ({
              validator(_, value) {
                if (!value || /^1[3-9]\d{9}$/.test(value)) {
                  return Promise.resolve();
                }
                return Promise.reject('请输入正确的手机号');
              },
            }),
          ]}
        >
          <Input placeholder='请输入联系方式' maxLength={11} type={'number'} />
        </Form.Item>
        <Form.Item label='备注' name='remark'>
          <Input.TextArea placeholder='请输入备注' maxLength={50} showCount />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModal;
