import React, { useMemo, useRef, useState } from "react";
import { Collapse, Modal, Table } from "antd";
import { useRequest, useModel } from "umi";
import { ColumnItem } from "@/type";
export default function VariableModal(props: {
  /**
   * 触发节点
   */
  trigger: JSX.Element;
  /**
   * 确认
   */
  onOk: (code: string) => void;
}) {
  const [open, setOpen] = React.useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = React.useState<React.Key[]>([]);
  const { project } = useModel("erModel");
  const [variable, setVariable] = useState('');

  const triggerDom = React.cloneElement(props.trigger, {
    ...props.trigger.props,
    onClick: () => {
      setSelectedRowKeys([]);
      setVariable('');
      setOpen(true);
    },
  });
  const handleSelected = (tableAliasName: string, keys: React.Key[], rows: any[]) => {
    console.log(rows, rows?.[0]?.schemaName)
    setSelectedRowKeys(keys);
    setVariable(rows?.[0]?.schemaName ? `<%${tableAliasName}.${rows?.[0]?.schemaName}%>` : '');
  };

  const handleOk = () => {
    props.onOk(variable);
    setOpen(false);
  };

  return (
    <>
      <Modal
        width={880}
        open={open}
        title="请选择"
        onCancel={() => setOpen(false)}
        onOk={handleOk}
        okButtonProps={{
          disabled: !variable
        }}
      >
        <div>当前选择：<span>{variable}</span></div>
        <Collapse
          items={project.tables.map((item) => {
            const { table, tableColumnList } = item;
            const name = table.langNameList?.find(
              (item) => item.name === "zh-CN"
            )?.value;
            return {
              key: table.id,
              label: `${table.aliasName}${name ? `(${name})` : ""}`,
              children: (
                <Table
                  rowKey={"id"}
                  pagination={false}
                  dataSource={tableColumnList}
                  rowSelection={{
                    type: "radio",
                    selectedRowKeys,
                    onChange: (keys, selectedRows) => {
                      handleSelected(table.aliasName, keys, selectedRows);
                    },
                  }}
                  columns={[
                    { title: "字段代码", dataIndex: "name" },
                    { title: "字段名称", dataIndex: "type" },
                    { title: "字段类型", dataIndex: "type" },
                    { title: "字段长度", dataIndex: "type" },
                    { title: "是否必填", dataIndex: "type" },
                    { title: "需求描述", dataIndex: "type" },
                  ]}
                />
              ),
            };
          })}
        ></Collapse>
      </Modal>
      {triggerDom}
    </>
  );
}
