import React, { useEffect } from "react";
import { EditableProTable, ProColumns } from "@ant-design/pro-components";
import type { ColumnItem } from "@/type";
import { createColumn } from "@/utils";
import { DataType } from "@/enum";
import { DATA_TYPE_OPTIONS } from "@/constants";
import {
  Button,
  Input,
  InputNumber,
  message,
  Switch,
  Tooltip,
  Upload,
  UploadFile,
} from "antd";
import LangInput from "./LangInput";
import { validateColumnCode } from "@/utils/validator";
import VariableModal from "./VariableModal";
import ColumnVariableModal from "./ColumnVariableModal";
import { FormInstance } from "antd/lib";
import {
  DownloadOutlined,
  InfoCircleOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { parseExcel } from "@/utils/parseExcel";
import ImportResultModal from "./ImportResultModal";
export default function TableEdit(props: {
  tableId?: string;
  data: any[];
  modelId?: string;
  onChange?: (data: readonly ColumnItem[]) => void;
}) {
  const [editableKeys, setEditableRowKeys] = React.useState<React.Key[]>([]);
  const [dataSource, setDataSource] = React.useState<readonly ColumnItem[]>(
    props.data
  );
  const boxRef = React.useRef<HTMLDivElement>(null);
  const importResultRef = React.useRef<{
    open: (data: any[], columns: readonly ColumnItem[]) => void;
  }>();

  useEffect(() => {
    props.onChange?.(dataSource);
  }, [dataSource]);

  // useEffect(() => {
  //   setDataSource(props.data);
  // }, [props.data]);
  const DefaultValueComp = ({
    value,
    onChange,
  }: {
    value?: string;
    onChange?: (value: string) => void;
  }) => {
    return (
      <div className="flex gap-2px">
        <Input
          placeholder="默认值"
          value={value}
          onChange={(e) => {
            onChange?.(e.target.value);
          }}
        />
        <div>
          <VariableModal
            trigger={
              <Button
                size="small"
                style={{ width: 40, fontSize: 12 }}
                type="text"
              >
                +变量
              </Button>
            }
            onOk={(val) => onChange?.(val)}
          />
          <ColumnVariableModal
            trigger={
              <Button
                size="small"
                style={{ width: 40, fontSize: 12 }}
                type="text"
              >
                +字段
              </Button>
            }
            onOk={(val) => onChange?.(val)}
          />
        </div>
      </div>
    );
  };

  const LengthComp = ({
    value,
    onChange,
    model,
    form,
    rowKey,
  }: {
    value?: string;
    onChange?: (value: string) => void;
    model: ColumnItem;
    form: FormInstance;
    rowKey?: React.Key | React.Key[];
  }) => {
    return (
      <span className="flex gap-2px">
        <InputNumber
          min={0}
          placeholder="总长度"
          defaultValue={model.precision}
          onChange={(value) =>
            form.setFieldValue([rowKey || "", "precision"], value)
          }
        />
        <InputNumber
          min={0}
          placeholder="小数位数"
          defaultValue={model.scale}
          onChange={(value) =>
            form.setFieldValue([rowKey || "", "scale"], value)
          }
        />
      </span>
    );
  };

  const columns: ProColumns[] = [
    {
      title: "操作",
      valueType: "option",
      width: 130,
      render: (_text, record, _, action) =>
        record.isPreDefined
          ? []
          : [
              <a
                key="editable"
                onClick={() => {
                  action?.startEditable?.(record.id);
                }}
              >
                编辑
              </a>,
              <a
                key="delete"
                onClick={() => {
                  setDataSource(
                    dataSource.filter((item) => item.id !== record.id)
                  );
                }}
              >
                删除
              </a>,
            ],
    },
    {
      title: "字段代码",
      dataIndex: "schemaName",
      valueType: "text",
      width: 150,
      formItemProps: {
        rules: [
          {
            required: true,
            message: "请输入字段名称",
          },
          {
            max: 50,
            message: "字段名称不能超过50个字符",
          },
          validateColumnCode,
        ],
      },
    },
    {
      title: "字段名称",
      dataIndex: "langName",
      valueType: "text",
      width: 150,
      render: (_dom, entity) => {
        return (
          entity.langNameList?.find(
            (item: Record<string, string>) => item.name === "zh-CN"
          )?.value || "-"
        );
      },
      renderFormItem: (_schema, config, form) => {
        const model = config.record;
        const rowKey = config.recordKey;
        return (
          <span>
            <LangInput
              style={{ width: 150 }}
              value={model.langNameList}
              onChange={(langValue, key) => {
                form.setFieldValue([rowKey || "", "langNameList"], langValue);
                form.setFieldValue([rowKey || "", "langName"], "");
              }}
            />
          </span>
        );
      },
    },
    {
      title: "类型",
      dataIndex: "type",
      valueType: "select",
      width: 90,
      fieldProps: (form, { rowKey }) => {
        return {
          options: DATA_TYPE_OPTIONS,
          onChange: () => {
            form.setFieldValue([rowKey || "", "maxLength"], undefined);
            form.setFieldValue([rowKey || "", "scale"], undefined);
            form.setFieldValue([rowKey || "", "precision"], undefined);
          },
        };
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: "请选择类型",
          },
        ],
      },
    },
    {
      title: "长度",
      dataIndex: "maxLength",
      valueType: "digit",
      width: 90,
      fieldProps: {
        precision: 0,
      },
      render: (text, record) => {
        return record.type === DataType.Decimal
          ? `${record.precision}${record.scale ? `,${record.scale}` : ""}`
          : text;
      },
      renderFormItem: (_schema, config, form) => {
        const model = config.record;
        const rowKey = config.recordKey;
        return model.type === DataType.Nvarchar ? (
          <InputNumber min={0} max={4000} placeholder="字符长度" />
        ) : model.type === DataType.Decimal ? (
          <LengthComp model={model} form={form} rowKey={rowKey} />
        ) : (
          "-"
        );
      },
    },
    {
      title: "必填",
      dataIndex: "isRequired",
      valueType: "switch",
      render: (text, record) => {
        return <Switch disabled checked={record.isRequired} />;
      },
      width: 80,
    },
    {
      title: "唯一",
      dataIndex: "isUnique",
      valueType: "switch",
      render: (text, record) => {
        return <Switch disabled checked={record.isUnique} />;
      },
      width: 80,
    },
    {
      title: "默认值",
      dataIndex: "defaultValue",
      valueType: "text",
      width: 150,
      renderFormItem() {
        return <DefaultValueComp />;
      },
    },
    {
      title: "字符集",
      dataIndex: "chartset",
      valueType: "text",
      width: 120,
      renderFormItem: (_schema, config) => {
        return config.record.type === DataType.Nvarchar ? (
          <Input placeholder="字符集" />
        ) : null;
      },
    },
    {
      title: "内容",
      dataIndex: "whereInputContent",
      valueType: "text",
      width: 120,
      renderFormItem: (_schema, config) => {
        return config.record.type === DataType.Nvarchar ? (
          <Input.TextArea placeholder="内容..." />
        ) : null;
      },
    },
    {
      title: "描述",
      dataIndex: "memo",
      valueType: "textarea",
      width: 150,
      renderFormItem: () => {
        return <Input.TextArea placeholder="描述..." />;
      },
    },
    {
      title: "预定义字段",
      dataIndex: "isPreDefined",
      valueType: "switch",
      readonly: true,
      render: (text, record) => {
        return record.isPreDefined ? "是" : "否";
      },
      renderFormItem: (schema, config) => {
        return config.record.isPreDefined ? "是" : "否";
      },
    },
  ];

  const handleAdd = () => {
    return createColumn(props?.tableId, dataSource.length + 1);
  };

  // 上传字段模版文件
  const handleUpload = (file: UploadFile) => {
    message.loading("正在解析文件...", 0);
    parseExcel<any>(file)
      .then((res) => {
        console.log("加载数据：", res);
        const list = res?.["表单字段"];
        message.destroy();
        if (!list || !list.length) {
          message.warning("当前文件无字段数据,请检查");
        } else {
          importResultRef.current?.open(list, dataSource);
        }
      })
      .catch((err) => {
        console.error("加载数据失败：", err);
        message.error("文件解析失败");
        message.destroy();
      });
  };

  // 解析粘贴板数据
  // 解析出每一行的数据
  const parseClipBoard = (text: string) => {
    const arr = text.split("\r\n");
    return arr.map((item) => item.split("\t"));
  };

  const regex = /^[a-z][a-z0-9_]*$/;

  const handlePaste = () => {
    // 获取粘贴板数据
    navigator.clipboard.readText().then((text) => {
      console.log("粘贴板数据：", text);
      // 无文本，或格式不对
      if (!text || !text.includes("\t")) {
        message.warning("粘贴数据格式不正确，请检查");
        return;
      }

      const parseList = parseClipBoard(text);
      // 过滤无效数据
      const list = parseList
        .filter((item) => item.length >= 3 && regex.test(item?.[0]))
        .map((item) => ({
          字段名: item[0],
          类型: item[1],
          长度: item[2],
          中文名: item[3],
          英文名: item[4],
          是否必填: item[5],
          描述: item[6],
          默认值: item[7],
        }));
      if (!list.length) {
        message.warning("粘贴板无有效数据，请检查");
        return;
      }

      importResultRef.current?.open(list, dataSource);
    });
  };

  useEffect(() => {
    // 监听ctrl+v 粘贴表格数据
    document.addEventListener("paste", handlePaste);
    return () => {
      document.removeEventListener("paste", handlePaste);
    };
  }, []);

  const handleChangeColumn = (list: ColumnItem[]) => {
    setDataSource(list);
  };

  return (
    <div className="w-full h-full overflow-auto" ref={boxRef}>
      <ImportResultModal
        ref={importResultRef}
        tableId={props?.tableId}
        onChange={handleChangeColumn}
      />
      <EditableProTable
        columns={columns}
        rowKey="id"
        size="small"
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={{
          record: handleAdd,
        }}
        editable={{
          type: "multiple",
          editableKeys,
          onChange: setEditableRowKeys,
        }}
        toolBarRender={() => [
          <span key="paste" className="text-gray-500">可使用粘贴导入</span>,
          <Tooltip
            key="info"
            title={
              <div>
                <p>填写规范:</p>
                <p>
                  1、字段名第一位必须为大写字母，之后的对象可以字母大小写，数字或下划线；
                </p>
                <p>2、Nvarchar类型长度最大不可以超过4000；</p>
                <p>
                  3、Decimal类型精度的填写方式：总精度,有效小数位，eg: 18,6；
                </p>
                <p>4、Int、Datetime等类型长度需填写为0；</p>
              </div>
            }
          >
            <InfoCircleOutlined />
          </Tooltip>,
          <Button key="download" icon={<DownloadOutlined />}>
            <a
              download={"BusinessTableColumnsImportTemplate.xlsx"}
              href="/Content/Template/BusinessTableColumnsImportTemplate.xlsx"
            >
              下载模版
            </a>
          </Button>,
          <Upload
            key="upload"
            accept=".xlsx"
            showUploadList={false}
            beforeUpload={(file) => handleUpload(file)}
          >
            <Button
              type="primary"
              icon={<UploadOutlined />}
              onClick={() => {
                handleAdd();
              }}
            >
              导入字段
            </Button>
          </Upload>,
        ]}
      />
    </div>
  );
}
