import React, { useRef } from "react";
import { Modal, Input, Form, message } from "antd";
import { SaveDataModel } from "@/api";
import { TableType } from "@/enum";
import { ProjectInfo } from "@/type";
import { DEFAULT_SETTING } from "@/constants";

export default React.forwardRef(function AddModel(
  props: { onChange?: (val: string | ProjectInfo) => void },
  ref
) {
  const [open, setOpen] = React.useState(false);
  const [form] = Form.useForm();
  const type = React.useRef<TableType>();
  const editInfo = useRef<ProjectInfo>();
  const folderRef = useRef<string>();
  React.useImperativeHandle(ref, () => {
    return {
      open: (tableType: TableType, folder?: string) => {
        folderRef.current = folder;
        editInfo.current = undefined;
        type.current = tableType;
        setOpen(true);
        form.resetFields();
      },
      edit: (info: ProjectInfo) => {
        editInfo.current = info;
        form.setFieldsValue(info);
        setOpen(true);
      },
    };
  });

  const handleSubmit = () => {
    form.validateFields().then(async (values) => {
      if (editInfo.current) {
        const params = {
          ...editInfo.current,
          ...values,
        };
        // 编辑
        await SaveDataModel(params);
        message.success("编辑成功");
        props.onChange?.(params);
        setOpen(false);
      } else {
        // 新增
        const res = await SaveDataModel({
          ...values,
          directory: folderRef.current,
          type: type.current,
          setting: JSON.stringify(DEFAULT_SETTING),
        });
        message.success("创建成功");
        props.onChange?.(res?.result);
        setOpen(false);
      }
    });
  };

  return (
    <Modal
      open={open}
      width={440}
      title={editInfo.current ? "编辑模型" : "创建模型"}
      onCancel={() => setOpen(false)}
      onOk={handleSubmit}
    >
      <Form<{ name: string; description: string }>
        layout="vertical"
        form={form}
      >
        <Form.Item
          label="模型名称"
          name="name"
          rules={[
            { required: true, message: "请输入模型名称,长度50以内！", max: 50 },
          ]}
        >
          <Input placeholder="请输入模型名称" />
        </Form.Item>
        <Form.Item name="description" label="模型描述">
          <Input.TextArea placeholder="请输入模型描述" />
        </Form.Item>
      </Form>
    </Modal>
  );
});
