import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterItemType, InterReqType } from '~/api/interface';
import { listByInspectionIdType, industryUpdateType } from '~/api/interface/categoryManage';
import { CategoryManageAPI } from '~/api';

// 表格类型
type TableType = InterItemType<listByInspectionIdType>;
// 表单参数
type ReqType = InterReqType<industryUpdateType>;
// 参数类型
interface selfProps {
  id: number;
  data?: TableType[0];
  onCancel: () => void;
}

const AddEditTagModalView: React.FC<ModalProps & selfProps> = ({
  id,
  open,
  title,
  onCancel,
  data,
}) => {
  // 表格数据类型
  const [form] = Form.useForm<ReqType>();
  // 关闭事件
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };
  // 确定事件
  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 CategoryManageAPI[data?.id ? 'inspectionTagUpdate' : 'inspectionTagInsert']({
      ...values,
      inspectionId: id,
      id: data?.id || undefined,
    });
    if (res && res.code === '200') {
      message.success('操作成功').then();
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue(data);
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal title={title} open={open} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form form={form} labelAlign='right' labelCol={{ span: 4 }} wrapperCol={{ span: 10 }}>
        <Form.Item
          label='标签名称'
          name='tagName'
          rules={[{ required: true, message: '请输入标签名称' }]}
        >
          <Input placeholder='请输入标签名称' maxLength={15} allowClear />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditTagModalView;
