import React, { useEffect, useState } from "react";
import { Button, Modal, Input, Dropdown } from "antd";
import {
  DownOutlined,
  ImportOutlined,
  PlusOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import TableItem from "./TableItem";
import { useModel } from "umi";
import noData from "@/assets/no-data.png";
import TableEdit from "@/components/TableEdit";
import { ColumnItem, TableItemType } from "@/type";
import AddTable from "@/pages/detail/components/AddTable";
export default function TablePanel() {
  const {
    project,
    setProject,
    updateTable,
    addTable,
    tableActive,
    setTableActive,
    graph,
  } = useModel("erModel");
  const contentRef = React.useRef<HTMLDivElement>(null);
  const [contentStyle, setContentStyle] = React.useState<React.CSSProperties>(
    {}
  );
  const [tableData, setTableData] = React.useState<TableItemType>();
  const [open, setOpen] = useState(false);
  const addTableRef = React.useRef<{ openImportMode: () => void }>(null);

  useEffect(() => {
    graph?.on("node:dblclick", (args) => {
      const data = args.node.getData();
      if (data?.isTable) {
        setOpen(true);
        setTableData(data);
      }
    });
  }, [graph]);

  useEffect(() => {
    // 计算高度
    setContentStyle({
      height: `calc(100vh - ${contentRef.current?.getBoundingClientRect().top}px)`,
    });
  }, []);

  const handleChangeTableColumns = (columnList: readonly ColumnItem[]) => {
    if (tableData) {
      updateTable({
        ...tableData,
        tableColumnList: columnList as ColumnItem[],
      });
    }
  };

  // 引入表
  const handleImport = (tables: TableItemType[]) => {
    setProject({
      ...project,
      tables: [...tables, ...project.tables],
    });
    setTableActive(tables[0].table.id);
    graph?.select(tables[0].table.id);
  };

  return (
    <div
      className="px-12px overflow-y-auto"
      ref={contentRef}
      style={contentStyle}
    >
      <div className="search-box flex gap-4px mb-12px">
        <Input placeholder="输入关键字搜索" suffix={<SearchOutlined />} />
        <Dropdown
          menu={{
            items: [
              {
                key: "add",
                label: "新建表",
                icon: <PlusOutlined />,
                onClick: () => addTable(),
              },
              {
                key: "import",
                label: "引入表",
                icon: <ImportOutlined />,
                onClick: () => addTableRef.current?.openImportMode(),
              },
            ],
          }}
        >
          <Button type="primary">
            添加表
            <DownOutlined />
          </Button>
        </Dropdown>
      </div>
      {project.tables.map((item) => {
        return (
          <TableItem
            data={item}
            onChange={updateTable}
            key={item.table.id}
            active={tableActive}
            setActive={setTableActive}
          />
        );
      })}
      {project.tables.length === 0 && (
        <div className="flex flex-col items-center justify-center h-[300px]">
          <img src={noData} alt="暂无数据" className="w-[200px] h-[200px]" />
          <div className="text-gray-400">暂无数据表，快来创建！</div>
        </div>
      )}
      <Modal
        title="字段详情"
        width={"80%"}
        open={open}
        footer={(_, { CancelBtn }) => {
          return <CancelBtn />;
        }}
        onCancel={() => {
          setOpen(false);
          setTableData(undefined);
        }}
      >
        <TableEdit
          tableId={tableData?.table?.id}
          data={tableData?.tableColumnList || []}
          modelId={project.id}
          onChange={handleChangeTableColumns}
        />
      </Modal>
      <AddTable ref={addTableRef} onChange={handleImport} />
    </div>
  );
}
