import { FC, useEffect } from 'react';
import { Form, Input, message, Modal } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { industryCaseAddCase, industryCaseListCasePage } from '~/api/interface/resourceManageType';
import { ResourceManageAPI } from '~/api';
import RichText from '~/components/richText';

// 列表的类型
type TableType = InterListType<industryCaseListCasePage>;
// 请求的表单类型
type ReqType = InterReqType<industryCaseAddCase>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}

const AddEditModal: FC<propType> = (props) => {
  AddEditModal.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 as ReqType & { file: any[] });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType) => {
    const res = await ResourceManageAPI[
      data?.id ? 'industryCaseUpdateCase' : 'industryCaseAddCase'
    ]({
      ...values,
      id: data?.id ? Number(data?.id) : undefined,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue({
      caseTitle: data.caseTitle,
      origin: data.origin,
      caseContents: data.caseContents || undefined,
    });
  }, [open, data]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      width={768}
    >
      <Form
        name='Form'
        form={form}
        labelAlign='right'
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 20 }}
      >
        <Form.Item
          label='文章标题'
          name='caseTitle'
          rules={[{ required: true, message: '请输入文章标题' }]}
        >
          <Input placeholder={'请输入文章标题'} maxLength={50} allowClear />
        </Form.Item>
        <Form.Item
          label='文章来源'
          name='origin'
          rules={[{ required: true, message: '请输入文章来源' }]}
        >
          <Input placeholder={'请输入文章来源'} maxLength={50} allowClear />
        </Form.Item>
        <Form.Item label='文章详情' name='caseContents'>
          <RichText
            richTextContent={data?.caseContents || ''}
            onChange={(e) => form.setFieldValue('caseContents', e)}
            height={250}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModal;
