import { useEffect, useMemo, useRef } from "react";
import { Flex, Tabs } from "antd";
import styles from "./index.less";
import "./index.less";
import { Graph, Shape } from "@antv/x6";
import { Scroller } from "@antv/x6-plugin-scroller";
import Libary from "../Libary";
import { useModel } from "umi";
import { getDefaultDataByTheme } from '@/config/data';
import { edgeMenu } from "@/utils/contentMenu";
import StyleConfig from "./StyleConfig";
import HistoryPanel from "@/components/HistoryPanel";
export default function Content() {
  const stageRef = useRef<HTMLDivElement | null>(null);
  const { initGraph, updateKey, setUpdateKey } = useModel("flowchartModel");
  const { onChangePageSettings, leftPanelActiveKey, setLeftPanelActiveKey } = useModel("appModel");
  const { projectInfo } = useModel("projectModel");

  useEffect(() => {
    // 初次绘制当画布的宽高为0时 设置当前宽高
    if(!projectInfo?.graph?.width) {
      if(!stageRef.current) return;

      const { width, height } = stageRef.current?.getBoundingClientRect();
      onChangePageSettings('width', parseInt(width + ''));
      onChangePageSettings('height', parseInt(height + ''));
    }
  }, [projectInfo?.graph?.width]);

  useEffect(() => {
    const graph = new Graph({
      container: document.getElementById("graph-container")!,
      autoResize: true,
      width: 2000,
      height: 2000,
      async: false,
      mousewheel: {
        enabled: true,
        zoomAtMousePosition: true,
        modifiers: "ctrl",
        minScale: 0.2,
        maxScale: 2,
      },
      // panning: {
      //   enabled: true,
      //   modifiers: "ctrl",
      //   // 画面平移
      //   eventTypes: ["rightMouseDown"],
      // },
      // 查找父节点
      embedding: {
        enabled: true,
        findParent({ node }) {
          const bbox = node.getBBox();
          return this.getNodes().filter((node) => {
            const data = node.getData<{ isPage: boolean }>();
            if (data && data.isPage) {
              const targetBBox = node.getBBox();
              return bbox.isIntersectWithRect(targetBBox);
            }
            return false;
          });
        },
      },
      background: {
        color: "#eaecee",
      },
      interacting: {
        edgeLabelMovable: false,
        edgeMovable: true,
        nodeMovable: (view) => {
          const data = view.cell.getData<{ ignoreDrag: boolean, lock: boolean }>();
          return !data || (!data?.ignoreDrag && !data?.lock);
        },
        arrowheadMovable: true,
        vertexMovable: true,
        vertexAddable: true,
        vertexDeletable: true,
        useEdgeTools: true,
        magnetConnectable: true,
        stopDelegateOnDragging: true,
        toolsAddable: true,
      },
      // 连接配置
      connecting: {
        allowEdge: true,
        allowLoop: true,
        allowNode: true,
        allowBlank: true,
        allowPort: true,
        allowMulti: true,
        highlight: false,
        anchor: "center",
        // connectionPoint: "anchor", // mermaid导入可能存在异常
        snap: {
          radius: 20,
        },
        createEdge() {
          return new Shape.Edge({
            ...getDefaultDataByTheme(projectInfo?.graph?.theme).edgeDefaultData,
            tools: [
              {
                name: "contextmenu",
                args: {
                  menu: edgeMenu,
                },
              },
            ],
          });
        },
        validateConnection({ targetMagnet }) {
          return !!targetMagnet;
        },
      },
      // 高亮显示
      highlighting: {
        magnetAdsorbed: {
          name: "stroke",
          args: {
            attrs: {
              fill: "#5F95FF",
              stroke: "#5F95FF",
            },
          },
        },
      },
    });

    graph.use(
      new Scroller({
        enabled: true,
      })
    );
    initGraph(graph);
  }, []);

  return (
    <Flex className="h-full">
      <div className={styles.leftPanel}>
        <Tabs
          className="h-full"
          centered
          activeKey={leftPanelActiveKey}
          onChange={(key) => setLeftPanelActiveKey(key)}
          items={[
            {
              key: "1",
              label: "组件库",
              children: <Libary />,
            },
            {
              key: "2",
              label: "风格",
              children: <StyleConfig/>,
            },
          ]}
        />
        <HistoryPanel graphId={projectInfo?.graph?.id} onRevert={() => setUpdateKey(updateKey + 1)}/>
      </div>
      <div className="w-12px drag-line"></div>
      <div
        className={styles.designLayout}
        ref={stageRef}
        style={{ width: "100%", height: "100%" }}
      >
        <div id="graph-container" style={{cursor: 'default'}}></div>
      </div>
    </Flex>
  );
}
