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 } from "antd";
import LangInput from "./LangInput";
import { validateColumnCode } from "@/utils/validator";
import VariableModal from "./VariableModal";
import { FormInstance } from "antd/lib";
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);

  useEffect(() => {
    props.onChange?.(dataSource);
  }, [dataSource]);
  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)}
          />
          <Button size="small" style={{ width: 40, fontSize: 12 }} type="text">
            +字段
          </Button>
        </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: "字段代码",
      dataIndex: "schemaName",
      valueType: "text",
      width: 150,
      formItemProps: {
        rules: [
          {
            required: true,
            message: "请输入字段名称",
          },
          {
            max: 50,
            message: "字段名称不能超过50个字符",
          },
          validateColumnCode,
        ],
      },
    },
    {
      title: "字段名称",
      dataIndex: "langNameList",
      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 (
          <LangInput
            value={model.langNameList}
            style={{width: 150}}
            onChange={(langValue) =>
              form.setFieldValue([rowKey || "", "langNameList"], langValue)
            }
          />
        );
      },
    },
    {
      title: "类型",
      dataIndex: "type",
      valueType: "select",
      width: 120,
      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: 120,
      fieldProps: {
        precision: 0,
      },
      render: (text, record) => {
        return record.type === DataType.Decimal
          ? `${record.precision},${record.scale}`
          : text;
      },
      renderFormItem: (_schema, config, form) => {
        const model = config.record;
        const rowKey = config.recordKey;
        return model.type === DataType.Nvarchar ? (
          <InputNumber min={0} placeholder="字符长度" />
        ) : model.type === DataType.Decimal ? (
          <LengthComp model={model} form={form} rowKey={rowKey} />
        ) : (
          "-"
        );
      },
    },
    {
      title: "必填",
      dataIndex: "isRequired",
      valueType: "switch",
      width: 80,
    },
    {
      title: "唯一",
      dataIndex: "isUnique",
      valueType: "switch",
      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: 120,
      renderFormItem: () => {
        return <Input.TextArea placeholder="描述..." />;
      },
    },
    {
      title: "操作",
      valueType: "option",
      width: 120,
      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>,
            ],
    },
  ];

  const handleAdd = () => {
    return createColumn(props?.tableId);
  };

  return (
    <div className="w-full h-full overflow-auto" ref={boxRef}>
      <EditableProTable
        columns={columns}
        rowKey="id"
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={{
          record: handleAdd,
        }}
        editable={{
          type: "multiple",
          editableKeys,
          // onSave: async (rowKey, data, row) => {
          //   console.log(rowKey, data, row, dataSource);
          // },
          onChange: setEditableRowKeys,
        }}
      />
    </div>
  );
}
