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?: (id: string) => void },
  ref
) {
  const [open, setOpen] = React.useState(false);
  const [form] = Form.useForm();
  const type = React.useRef<TableType>();
  const isAdd = useRef(true);
  React.useImperativeHandle(ref, () => {
    return {
      open: (tableType: TableType) => {
        isAdd.current = true;
        type.current = tableType;
        setOpen(true);
        form.resetFields();
      },
      edit: (info: ProjectInfo) => {
        isAdd.current = false;
        form.setFieldsValue(info);
        setOpen(true);
      },
    };
  });

  const handleSubmit = () => {
    form.validateFields().then(async (values) => {
      console.log(values, message);
      if (isAdd.current) {
        const res = await SaveDataModel({
          ...values,
          type: type.current,
          setting: JSON.stringify(DEFAULT_SETTING),
        });
        message.success("创建成功");
        props.onChange?.(res?.result);
        setOpen(false);
      } else {
        const res = await SaveDataModel({
          ...values,
          type: type.current,
        });
        message.success("创建成功");
        props.onChange?.(res?.result);
        setOpen(false);
      }
    });
  };

  return (
    <Modal
      open={open}
      width={440}
      title="创建模型"
      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>
  );
});
