import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { message, Modal, Table, Tooltip } from "antd";
import { ColumnItem } from "@/type";
import { TableProps } from "antd/lib";
import { createColumn } from "@/utils";

export default forwardRef(function ImportResultModal(props: { tableId?: string}, ref) {
  const [open, setOpen] = useState(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const originData = useRef<ColumnItem[]>([]);
  const [modal, contextHolder] = Modal.useModal();
  useImperativeHandle(ref, () => {
    return {
      open: (data: any[], columnList: ColumnItem[]) => {
        originData.current = columnList;
        setDataSource(data);
        setOpen(true);
      },
    };
  });

  // 校验字段名
  const validateSchemaName = (val: string) => {
    const regex = /^[a-z][a-z0-9_]*$/;
    let msg = "";
    if (!val) {
      msg = "编码不能为空!";
    }
    if (!regex.test(val)) {
      msg = "编码只能包含字母和数字, 必须小写字母开头！";
    }
    if (val?.length > 50) {
      msg += "!编码长度不能超过50";
    }

    return msg;
  };

  // 校验类型值
  const validateTypeValue = (val: string) => {
    return !["Int", "Nvarchar", "Real", "Bit", "Decimal", "DateTime"].includes(
      val
    )
      ? "类型值错误!"
      : "";
  };

  // 长度校验
  const validateLength = (val: string | number, type: string) => {
    let msg = "";
    if (type === "Int" || type === "DateTime") {
      if (parseInt(val + "") > 0) {
        msg = "Int和DateTime类型长度为0!";
      }
    }
    if (type === "Nvarchar") {
      if (typeof val === "string" && val.length > 4000) {
        msg = "长度不能超过4000!";
      }
    }
    return msg;
  };

  const handleSubmit = () => {
    let valid = true;
    dataSource.forEach((item) => {
      if (
        validateSchemaName(item["字段名"]) ||
        validateTypeValue(item["类型"]) ||
        validateLength(item["长度"], item["类型"])
      ) {
        valid = false;
      }
    });
    if(!valid) {
      message.error("数据校验失败,请检查数据修改后重新导入!");
      return;
    }

    modal.confirm({
      title: "确认导入",
      content: "导入会覆盖原有的内容, 是否继续?",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        const addList = dataSource.map((item, i) => {
          const old = originData.current.find((obj) => obj.schemaName === item?.['字段名']);
          const newColumn = createColumn(props?.tableId, old?.displayOrder || originData.current.length + i + 1);
          return newColumn;
        });
        setOpen(false);
      },
      onCancel: () => {
        setOpen(false);
      },
    });
  };

  const columns: TableProps["columns"] = [
    {
      title: "字段名",
      dataIndex: "字段名",
      render: (text) => {
        const msg = validateSchemaName(text);
        return (
          <Tooltip title={msg}>
            <span style={{ color: msg ? "red" : "black" }}>
              {text || "字段名为空"}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: "类型",
      dataIndex: "类型",
      render: (text) => {
        const msg = validateTypeValue(text);
        return (
          <Tooltip title={msg}>
            <span style={{ color: msg ? "red" : "black" }}>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: "长度",
      dataIndex: "长度",
      render: (text, record) => {
        const msg = validateLength(text, record?.["类型"]);
        return (
          <Tooltip title={msg}>
            <span style={{ color: msg ? "red" : "black" }}>{text}</span>
          </Tooltip>
        );
      },
    },
    { title: "中文名", dataIndex: "中文名" },
    { title: "英文名", dataIndex: "英文名" },
    { title: "是否必填", dataIndex: "是否必填" },
    { title: "描述", dataIndex: "描述" },
    { title: "默认值", dataIndex: "默认值" },
  ];

  return (
    <Modal
      title="导入结果"
      open={open}
      width="80%"
      okText="导入"
      onOk={handleSubmit}
      onCancel={() => setOpen(false)}
    >
      {contextHolder}
      <Table
        key={"字段名"}
        scroll={{ y: 400 }}
        columns={columns}
        dataSource={dataSource}
      />
    </Modal>
  );
});
