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";
import { DataType } from "@/enum";

export default forwardRef(function ImportResultModal(
  props: { tableId?: string; onChange: (list: ColumnItem[]) => void },
  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[], origin: ColumnItem[]) => {
        originData.current = origin;
        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";
    }

    if (["id", ""].includes(val)) {
      msg += "编码不能是预定义字段!";
    }

    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!";
      }
    }
    if (type !== "Decimal" && val.toString().includes(",")) {
      msg = "非Decimal类型不能包含逗号!";
    }
    if (!/^\d+(,\d+)?$/.test(val.toString())) {
      msg = "长度必须是数字逗号组成!";
    }
    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 list = [...originData.current];
        dataSource.forEach((item, i) => {
          const data = {
            schemaName: item["字段名"],
            type: DataType[item["类型"]] as unknown as DataType,
            langNameList: [
              { name: "en", value: item["英文名"] },
              { name: "zh-CN", value: item["中文名"] },
            ],
            isRequired: item["是否必填"] === "是",
            defaultValue: item["默认值"],
            memo: item["描述"],
            maxLength: 0,
            precision: 0,
            scale: 0,
          };
          if (item["类型"] === "Nvarchar") {
            data.maxLength = item["长度"];
          }
          if (item["类型"] === "Decimal") {
            const arr = item["长度"].toString().split(",");
            data.precision = arr?.[0];
            data.scale = item.arr?.[1];
          }
          const index = list.findIndex(
            (obj) => obj.schemaName === item?.["字段名"]
          );
          if (index >= 0) {
            list[index] = {
              ...list[index],
              ...data,
            };
          } else {
            const newColumn = createColumn(
              props?.tableId,
              list.length + i + 1
            );
            list.push({
              ...newColumn,
              ...data,
            });
          }
        });

        props.onChange(list);
        setOpen(false);
      },
      onCancel: () => {
        setOpen(false);
      },
    });
  };

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

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