import React, { useEffect, useState } from "react";
import { Button, Modal, Input } from "antd";
import { 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";
export default function TablePanel() {
  const { project, 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);

  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[],
      });
    }
  };

  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 />} />
        <Button type="primary" onClick={() => addTable()}>
          添加表
        </Button>
        <Button type="primary">导入表</Button>
      </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}
        onCancel={() => {
          setOpen(false);
          setTableData(undefined);
        }}
      >
        <TableEdit
          tableId={tableData?.table?.id}
          data={tableData?.tableColumnList || []}
          modelId={project.id}
          onChange={handleChangeTableColumns}
        />
      </Modal>
    </div>
  );
}
