import React, { useRef, useMemo } from "react";
import { Modal, Input, Form, message, TreeSelect } from "antd";
import { SaveDataModel, GetCanUseTableList } from "@/api";
import { TableType } from "@/enum";
import { ProjectInfo, TableItemType } from "@/type";
import { DEFAULT_SETTING } from "@/constants";
import CustomColorPicker from "@/components/CustomColorPicker";
import { useRequest, useModel } from "umi";
import { pick } from "lodash-es";

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

  const {
    data,
    loading: loadingOptions,
    run,
  } = useRequest(GetCanUseTableList, {
    manual: true,
  });

  // 可引入表列表
  const treeData = useMemo(() => {
    const tableMap: Record<string, any> = {};
    data?.result
      ?.filter(
        (item: any) =>
          // 过滤当前数据表类型及存在相同schemaName、aliasName的表
          item?.type == project?.type
      )
      ?.forEach((item: any) => {
        const option = {
          key: item.id,
          title: `${item?.schemaName}(${item.name})`,
          value: item?.id,
          selectable: !item.parentBusinessTableId,
        };
        // 子表
        if (item.parentBusinessTableId) {
          if (tableMap[item.parentBusinessTableId]) {
            tableMap[item.parentBusinessTableId].children.push(option);
          } else {
            tableMap[item.parentBusinessTableId] = {
              children: [option],
            };
          }
        } else {
          // 主表
          if (tableMap[item.id]) {
            tableMap[item.id] = {
              ...tableMap[item.id],
              ...option,
            };
          } else {
            tableMap[item.id] = {
              ...option,
              children: [],
            };
          }
        }
        return;
      });
    return Object.keys(tableMap).map((key) => tableMap[key]);
  }, [data]);

  const handleSubmit = () => {
    form.validateFields().then(async (values) => {
      if (editInfo.current) {
        const erDataModel = {
          ...editInfo.current,
          ...values,
          table: undefined
        }

        const params = {
          erDataModel
        };
        // 编辑
        await SaveDataModel(params);
        message.success("编辑成功");
        props.onChange?.(erDataModel);
        setOpen(false);
      } else {
        // 新增
        const erDataModel = {
          ...values,
          directory: folderRef.current,
          type: type.current,
          setting: JSON.stringify(DEFAULT_SETTING),
          table: undefined,
        }
        const businessTables =
          data?.result
            ?.filter((item: any) => values?.table?.includes(item.id))
            ?.map((item: any) => {
              return pick(item, [
                "aliasName",
                "schemaName",
                "id",
                "parentBusinessTableId",
              ]);
            }) || [];
        const res = await SaveDataModel({
          erDataModel,
          importFromBusinessTablesDto: {
            businessTables,
            color,
          }
        });
        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>
        {!editInfo.current && (
          <>
            <Form.Item label="选择表" name="table">
              <TreeSelect
                multiple
                treeCheckable
                allowClear
                placeholder="请选择"
                loading={loadingOptions}
                treeData={treeData}
              />
            </Form.Item>
            <Form.Item label="颜色" name="color">
              <CustomColorPicker onChange={setColor}>
                {color ? (
                  <div
                    className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none cursor-pointer shadow-inner"
                    style={{ background: color || "#eee" }}
                  ></div>
                ) : (
                  <span className="bg-#eee px-5px py-3px rounded-4px cursor-pointer text-12px text-#666">
                    随机生成,点击可选择颜色
                  </span>
                )}
              </CustomColorPicker>
            </Form.Item>
          </>
        )}
      </Form>
    </Modal>
  );
});
