import React, { useMemo, useState } from "react";
import { Modal, Tag } from "antd";
import { ProTable } from "@ant-design/pro-components";
import { GetWfBusinessTableAndColumns } from "@/api";
import { useRequest, useParams } from "umi";

export type TableListItem = {
  c_DisplayOrder: number;
  c_Id: string;
  c_IsRequired: boolean;
  c_MaxLength: number;
  c_Name: string;
  c_SchemaName: string;
  c_Type: number;
  description: string;
  displayOrder: number;
  id: string;
  langDescription: string;
  langName: string;
  name: string;
  schemaName: string;
  type: number;
};

// 数据库数据类型
export enum DataType {
  Int = 1,
  Nvarchar = 2,
  Real = 3,
  Bit = 4,
  Decimal = 5,
  DateTime = 6,
}

export const TypeMap = {
  1: "Int",
  2: "Nvarchar",
  3: "Real",
  4: "Bit",
  5: "Decimal",
  6: "DateTime",
};

export default function ColumnModal(props: {
  trigger: React.ReactNode;
  onChange?: (data: TableListItem[]) => void;
  api?: (data: any) => Promise<any>;
  defaultParams?: any[];
  defaultOpen?: boolean;
  onClose?: () => void;
}) {
  const [open, setOpen] = useState(props?.defaultOpen ?? false);
  const [data, setData] = useState<TableListItem[]>([]);
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  const params = useParams();

  const { run, loading } = useRequest(
    props?.api || GetWfBusinessTableAndColumns,
    {
      manual: true,
      cacheKey: `columns_${params.id}`,
      cacheTime: 1000 * 60 * 10,
      staleTime: 1000 * 60 * 10,
      onSuccess: (res) => {
        console.log("res:", res);
        setData(res?.result || []);
      },
    }
  );

  // 计算出表格数据
  const tableDataSource = useMemo(() => {
    const tableMap: Record<string, any> = {};
    data.forEach((item) => {
      if (tableMap[item.schemaName]) return;

      tableMap[item.schemaName] = {
        key: item.schemaName,
        schemaName: item.schemaName,
        name: item.name,
        type: item.type,
        description: item.description,
        displayOrder: item.displayOrder,
      };
    });

    return Object.values(tableMap).sort(
      (a, b) => a.displayOrder - b.displayOrder
    );
  }, [data]);

  const expandedRowRender = (record: TableListItem) => {
    const dataSource = data
      .filter((item) => item.schemaName === record.schemaName)
      .sort((a, b) => a.c_DisplayOrder - b.c_DisplayOrder);
    return (
      <ProTable
        columns={[
          { title: "字段代码", dataIndex: "c_SchemaName", key: "c_SchemaName" },
          { title: "字段名称", dataIndex: "c_Name", key: "c_Name" },
          {
            title: "字段类型",
            dataIndex: "c_Type",
            key: "c_Type",
            renderText: (text: keyof typeof TypeMap) => TypeMap[text],
          },
          { title: "字段长度", dataIndex: "c_MaxLength", key: "c_MaxLength" },
          {
            title: "必填",
            dataIndex: "c_IsRequired",
            key: "c_IsRequired",
            renderText: (text) => (text ? "是" : "否"),
          },
          { title: "需求描述", dataIndex: "c_Memo", key: "c_Memo" },
        ]}
        rowSelection={{
          type: "radio",
          selectedRowKeys: selectedRows.map((item) => item.c_Id),
          onChange(selectedRowKeys, selectedRows) {
            setSelectedRows(selectedRows);
            console.log("selectedRowKeys: ", selectedRowKeys, selectedRows);
          },
        }}
        rowKey="c_Id"
        headerTitle={false}
        search={false}
        options={false}
        dataSource={dataSource}
        pagination={false}
        toolBarRender={false}
        tableAlertRender={false}
      />
    );
  };

  // 打开弹窗
  const handleOpen = () => {
    setOpen(true);
    params?.id && run(params.id);
  };

  const handleOk = () => {
    props?.onChange?.(selectedRows);
    setOpen(false);
    setSelectedRows([]);
  };

  const handleCancel = () => {
    setOpen(false);
    setSelectedRows([]);
    props.onClose?.();
  };

  return (
    <>
      {/* 触发器 */}
      <span onClick={handleOpen}>{props.trigger}</span>

      <Modal
        title="请选择"
        open={open}
        width={880}
        styles={{
          body: {
            maxHeight: "80%",
            overflowY: "auto",
          },
        }}
        onOk={handleOk}
        onCancel={handleCancel}
        closable={false}
        destroyOnHidden
      >
        {!!selectedRows.length && (
          <div className="bg-gray-100 p-4 mb-4 text-gray-500">
            <div className="text-gray-800">
              当前已选择: {selectedRows.length}项
            </div>
            {selectedRows.map((item) => (
              <Tag key={item.c_Id}>
                {`<%${item.schemaName}.${item.c_SchemaName}%>`}
              </Tag>
            ))}
          </div>
        )}

        <ProTable<TableListItem>
          loading={loading}
          columns={[
            { title: "表代码", dataIndex: "schemaName" },
            { title: "表名称", dataIndex: "name" },
            {
              title: "类型",
              dataIndex: "type",
              renderText: (text) => (
                <>
                {text == 1 && <span key="1">系统表</span>}
                {text == 2 && <span key="2">流程表</span>}
                {text == 3 && <span key="3">业务表</span>}
                </>
              ),
            },
          ]}
          scroll={{
            y: 300,
          }}
          dataSource={tableDataSource}
          request={(params, sorter, filter) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            return Promise.resolve({
              data: tableDataSource.filter(
                (item) =>
                  item.schemaName?.includes(params?.schemaName || "") &&
                  item.name?.includes(params?.name || "")
              ),
              success: true,
            });
          }}
          rowKey="key"
          pagination={false}
          expandable={{ expandedRowRender }}
          dateFormatter="string"
          options={false}
        />
      </Modal>
    </>
  );
}
