import React, { useEffect } from 'react';
import { Form, Input, message, Modal, Select } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { insertModuleInfo, listModuleInfoPage } from '~/api/interface/commonType';
import { CommonAPI } from '~/api';

// 列表的类型
type TableType = InterListType<listModuleInfoPage>;
// 请求的表单类型
type ReqType = InterReqType<insertModuleInfo>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}
// 所属产品
const moduleType = [
  { label: '云享飞', value: 0 },
  { label: '云飞手', value: 1 },
  { label: '云仓', value: 2 },
  { label: '无人机城', value: 3 },
];

const AddModuleModal: React.FC<propType> = (props) => {
  AddModuleModal.defaultProps = {
    data: undefined,
  };
  // 参数
  const { title, open, closed, data } = props;
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType) => {
    const res = await CommonAPI.insertModuleInfo(values);
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
    // console.log('提交事件 --->', values);
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue(data);
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label='模块名称'
          name='moduleName'
          rules={[{ required: true, message: '请输入模块名称' }]}
        >
          <Input placeholder={'请输入模块名称'} maxLength={20} allowClear />
        </Form.Item>
        <Form.Item
          label='所属产品'
          name='moduleType'
          rules={[{ required: true, message: '请选择所属产品' }]}
        >
          <Select placeholder={'请选择所属产品'} options={moduleType} allowClear />
        </Form.Item>
        <Form.Item
          label='模块代码'
          name='moduleCode'
          rules={[{ required: true, message: '请输入模块代码' }]}
        >
          <Input placeholder={'请输入模块代码'} maxLength={20} allowClear />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddModuleModal;
