/**
 * @author: clay
 * @data: 2021/5/14 23:20
 * @email: clay@hchyun.com
 * @description: node er图点击事件
 */

let vm = null;

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

export default {
  sendThis,
  name: "click-er-edge",
  options: {
    getEvents() {
      return {
        "edge:click": "onEdgeClick",
        "edge:contextmenu": "onEdgeRightClick"
      };
    },
    /**
     * 点击连线
     * @param event
     */
    onEdgeClick(event) {
      let clickEdge = event.item;
      clickEdge.setState("selected", !clickEdge.hasState("selected"));
      vm.currentFocus = "edge";

      this.updateVmData(event);
    },
    /**
     *
     * @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);
      }
    },
    updateVmData(event) {

      // 更新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 }
        };

      }
    },
  }
};
