import utils from '../utils'

/**
 * @author: clay
 * @data: 2021/5/14 23:20
 * @email: clay@hchyun.com
 * @description: node
 */
const isInBBox = (point, bbox) => {
  const {
    x,
    y
  } = point;
  const {
    minX,
    minY,
    maxX,
    maxY
  } = bbox;

  return x < maxX && x > minX && y > minY && y < maxY;
};

let vm = null;

const sendThis = (_this) => {
  vm = _this;
};

export default {
  sendThis,
  name: 'dice-er-node',
  options: {
    getDefaultCfg() {
      return {
        multiple: true,
        start:0,
      };
    },
    getEvents() {
      return {
        itemHeight: 50,
        wheel: "scroll",
        "node:click": "onNodeClick",
        "edge:click": "onEdgeClick",
        "node:contextmenu": "onNodeRightClick",
        "edge:contextmenu": "onEdgeRightClick",
        "canvas:click": "onCanvasClick",
      };
    },
    scroll(e) {
      e.preventDefault()
      const {
        graph
      } = this;
      const nodes = graph.getNodes().filter((n) => {
        const bbox = n.getBBox();

        return isInBBox(graph.getPointByClient(e.clientX, e.clientY), bbox);
      });
      if (nodes) {
        nodes.forEach((node) => {
          const model = node.getModel();
          if (model.column.length < 9 ) {
            return;
          }
          const idx = model.startIndex || 0;
          this.start=idx
          let startX = model.startX || 0.5;
          let startIndex = idx + e.deltaY * 0.02;
          if ((model.column.length-idx)<10 && startIndex > idx){
            return;
          }
          startX -= e.deltaX;
          if (startIndex < 0) {
            startIndex = 0;
          }
          if (startX > 0) {
            startX = 0;
          }
          if (startIndex > model.column.length - 1) {
            startIndex = model.column.length - 1;
          }
          graph.update(node, {
            startIndex,
            startX,
          });
        });
      }


    },
    onNodeClick(event) {
      this.shrinkage(event)
      vm.currentFocus = "node";
      vm.rightMenuShow = false;
      this.updateVmData(event);
    },
    /**
     * 点击连线
     * @param event
     */
    onEdgeClick(event) {
      let clickEdge = event.item;
      clickEdge.setState("selected", !clickEdge.hasState("selected"));
      vm.currentFocus = "edge";

      this.updateVmData(event);
    },
    onNodeRightClick(event) {
      let graph = vm.graph;
      let clickNode = event.item;
      let clickNodeModel = clickNode.getModel();
      let selectedNodes = graph.findAllByState("node", "selected");
      let selectedNodeIds = selectedNodes.map(item => {
        return item.getModel().id;
      });
      vm.selectedNode = clickNode;
      // 如果当前点击节点是之前选中的某个节点，就进行下面的处理
      if (selectedNodes.length > 1 && selectedNodeIds.indexOf(clickNodeModel.id) > -1) {
        vm.rightMenuShow = true;
        let rightMenu = vm.$refs.rightMenu;
        rightMenu.style.left = event.clientX + "px";
        rightMenu.style.top = event.clientY + "px";
      } else {
        // 隐藏右键菜单
        vm.rightMenuShow = false;
        // 先取消所有节点的选中状态
        selectedNodes.forEach(node => {
          node.setState("selected", false);
        });
        // 再添加该节点的选中状态
        clickNode.setState("selected", true);
        vm.currentFocus = "node";
        this.updateVmData(event);
      }
      graph.paint();
    },
    /**
     *
     * @param event
     */
    onEdgeRightClick(event) {
      let graph = vm.graph;
      let clickEdge = event.item;
      let clickEdgeModel = clickEdge.getModel();
      let selectedEdges = graph.findAllByState("edge", "selected");
      // 如果当前点击节点不是之前选中的单个节点，才进行下面的处理
      if (!(selectedEdges.length === 1 && clickEdgeModel.id === selectedEdges[0].getModel().id)) {
        // 先取消所有节点的选中状态
        graph.findAllByState("edge", "selected").forEach(edge => {
          edge.setState("selected", false);
        });
        // 再添加该节点的选中状态
        clickEdge.setState("selected", true);
        vm.currentFocus = "edge";
        this.updateVmData(event);
      }
      let point = { x: event.x, y: event.y };
    },
    onCanvasClick() {
      vm.currentFocus = "canvas";
      vm.rightMenuShow = false;
    },
    updateVmData(event) {
      if (event.item._cfg.type === "node") {
        let clickNode = event.item;
        if (clickNode.hasState("selected")) {
          let clickNodeModel = clickNode.getModel();
          vm.selectedNode = clickNode;
          let nodeAppConfig = { ...vm.nodeAppConfig };
          Object.keys(nodeAppConfig).forEach(function(key) {
            nodeAppConfig[key] = "";
          });
          vm.selectedNodeParams = {
            label: clickNodeModel.label || "",
            columns:clickNodeModel.columns,
            appConfig: { ...nodeAppConfig, ...clickNodeModel.appConfig }
          };
        }
      } else if (event.item._cfg.type === "edge") {
        // 更新vm的data: selectedEdge 和 selectedEdgeParams
        let clickEdge = event.item;
        if (clickEdge.hasState("selected")) {
          let clickEdgeModel = clickEdge.getModel();
          vm.selectedEdge = clickEdge;
          let edgeAppConfig = { ...vm.edgeAppConfig };
          Object.keys(edgeAppConfig).forEach(function(key) {
            edgeAppConfig[key] = "";
          });
          vm.selectedEdgeParams = {
            label: clickEdgeModel.label || "",
            relationalItem: clickEdgeModel.relationalItem,
            sourceColumn:clickEdgeModel.sourceColumn,
            targetColumn:clickEdgeModel.targetColumn,
            appConfig: { ...edgeAppConfig, ...clickEdgeModel.appConfig }
          };
        }
      }
    },
    shrinkage(e){
      const {
        graph
      } = this;
      const item = e.item;
      const shape = e.shape;
      if (!item) {
        return;
      }
      if (shape.get("name") === "collapse") {
        graph.updateItem(item, {
          collapsed: true,
          size: [300, 50],
          height:44,
        });
        setTimeout(() => graph.layout(), 100);
      } else if (shape.get("name") === "expand") {
        let updateGraph = graph.updateItem(item, {
          collapsed: false,
          size: [300, 500],
          height:316,
        });
        // utils.anchor.update({height:100,}, graph)
        setTimeout(() => graph.layout(), 100);
      }else {
        // eslint-disable-next-line no-unused-vars
        const model = item.getModel();
        // console.log(JSON.stringify(model));
        // console.log(model.style.default.fill = '#4eb922');
        // console.log(model.style.selected.shadowColor = '#4eb922');
      }
    },
    moves(e) {
      const name = e.shape.get("name");
      const item = e.item;
      if (!name.startsWith("marker")){
        if (name && name.startsWith("item")) {
          this.graph.updateItem(item, {
            selectedIndex: Number(name.split("-")[1]),
          });
        } else {
          this.graph.updateItem(item, {
            selectedIndex: NaN,
          });
        }
      }
    },
  }
}
