import { Graph } from "@antv/x6";
import { useRef, useState } from "react";
import { Dnd } from "@antv/x6-plugin-dnd";
import { Transform } from "@antv/x6-plugin-transform";
import { Snapline } from "@antv/x6-plugin-snapline";
import { Clipboard } from "@antv/x6-plugin-clipboard";
import { Selection } from "@antv/x6-plugin-selection";
import { History } from "@antv/x6-plugin-history";
import { Scroller } from "@antv/x6-plugin-scroller";
import { Keyboard } from "@antv/x6-plugin-keyboard";
import { Export } from "@antv/x6-plugin-export";

export default function flowModel() {
  const graphRef = useRef<Graph>();
  const [graph, setGraph] = useState<Graph>();
  const init = (container: HTMLDivElement) => {
    graphRef.current?.dispose();
    const instance = new Graph({
      container,
      width: container.clientWidth,
      height: container.clientHeight,
      autoResize: true,
      // 鼠标滚轮缩放
      mousewheel: {
        enabled: true,
        zoomAtMousePosition: true,
        modifiers: "ctrl",
        minScale: 0.2,
        maxScale: 2,
      },
      background: {
        color: "#fbfcfe",
      },
      grid: {
        size: 20,
        type: "dot",
        visible: true,
        args: { background: true },
      },
      // 节点连线交互
      interacting: {
        edgeLabelMovable: false,
        edgeMovable: true,
        nodeMovable: (view) => {
          // 节点上锁状态无法移动
          const data = view.cell.getData<{ lock: boolean }>();
          return !data || !data?.lock;
        },
        arrowheadMovable: true,
        vertexMovable: true,
        vertexAddable: true,
        vertexDeletable: true,
        useEdgeTools: true,
        magnetConnectable: true,
        stopDelegateOnDragging: true,
        toolsAddable: true,
      },
      // 连线配置
      connecting: {
        snap: true,
        allowLoop: true,
        allowPort: false,
        allowNode: false,
        allowMulti: false,
      }
    });

    // instance.use(new Transform({
    //   resizing: {
    //     enabled: true,
    //   }
    // }));
    instance.use(new Snapline({
      enabled: true
    }));
    instance.use(
      new Selection({
        enabled: true,
        multiple: false,
        rubberband: false,
        movable: true,
        showNodeSelectionBox: false,
        // showEdgeSelectionBox: true,
        pointerEvents: "none",
        strict: true
      })
    );
    instance.use(new History());
    instance.use(
      new Scroller({
        enabled: true,
        autoResize: true,
        pannable: true,
      })
    );

    setGraph(instance);
    graphRef.current = instance;

    graph?.bindKey("del", () => {
      graph?.removeCells(graph?.getSelectedCells());
    });
  };

  return {
    init,
    graph,
  };
}
