import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterReqType } from '~/api/interface';
import { insertSystemMessage } from '~/api/interface/resourceManageType';
import RichText from '~/components/richText';
import { ResourceManageAPI } from '~/api';

// 请求的表单类型
type ReqType = InterReqType<insertSystemMessage>;

const AddEditModalView: React.FC<ModalProps & { data?: any; onCancel: () => void }> = (props) => {
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 点击确认
  const handleOk = async () => {
    form
      .validateFields()
      .then(async (values) => {
        // console.log('确认事件 --->', values);
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: ReqType) => {
    const res = await ResourceManageAPI[
      props.data?.id ? 'updateSystemMessage' : 'insertSystemMessage'
    ]({
      ...props.data,
      ...values,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleClose();
    }
  };
  // 关闭弹窗
  const handleClose = () => {
    form.resetFields();
    props.onCancel?.();
  };
  // 组件挂载
  useEffect(() => {
    if (!props.data) return;
    form.setFieldsValue(props.data);
  }, [props.data]);
  return (
    <Modal {...props} width={680} onOk={handleOk} onCancel={handleClose}>
      <Form
        name='Form'
        form={form}
        labelAlign='right'
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item label='标题' name='subject' rules={[{ required: true, message: '请输入标题' }]}>
          <Input placeholder={'请输入标题'} maxLength={35} allowClear />
        </Form.Item>
        <Form.Item
          label='内容'
          name='content'
          rules={[{ required: false, message: '请输入内容' }]}
          wrapperCol={{ span: 22 }}
        >
          <RichText
            richTextContent={form.getFieldValue('content') || props?.data?.content}
            onChange={(e) => form.setFieldValue('content', e)}
            height={250}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModalView;
