<template>
  <div class="leftTree" ref="leftTree">
    <div>
      <!-- zTree Start -->
      <ul id="leftTree" class="ztree"/>
      <!-- zTree End -->

      <!-- 模态框 Start -->
      <DragModal
          :visible="modalVisible"
          :title="title"
          :width="1000"
          :destroyOnClose="true"
          :maskClosable="false"
          @cancel="modalVisible = false"
          :footer="null">
        <!-- 添加结构 -->
        <AddStructure
            ref='addStruModel'
            :addType='addType'
            v-if="actionName === 'addStructure'"
            :struTypeCode='struTypeCode'
            :checkedNode='checkedNode'
            @closeModal='closeModal'
            @initLeftTree='initLeftTree'
            @initRightX6='initRightX6'
            @addRightX6Node="addRightX6Node"/>
        <!-- 添加评审意见 -->
        <AddReviewComments
            ref='addReviewComments'
            v-if="actionName === 'addReviewComments'"
            :checkedNode='checkedNode'
            @closeModal='closeModal'
            @initLeftTree='initLeftTree'/>
        <!-- 结构属性 -->
        <PropertyStructure
            v-if="actionName === 'propertyStructure'"
            :checkedNode='checkedNode'
            :tabKey='tabKey'
            @closeModal='closeModal'
            @initLeftTree='initLeftTree'
            @initRightX6='initRightX6'
            @updateRightX6Node='updateRightX6Node'
        />
      </DragModal>
      <!-- 模态框 End -->
    </div>
  </div>
</template>
<script>

import DragModal from "@/components/DragModal";
import AddStructure from '../AddModal/AddStructurel';
import AddReviewComments from "../AddModal/AddReviewComments";
import PropertyStructure from '../PropertyModal/PropertyStructure';
import {replaceNullName} from "@/utils/tree";
import {getMoveTargetNode, showMoveDownBtn, showMoveUpBtn, showPasteBtn, showShowBtn} from "@/utils/treeMenuBtn";
import AntSpinDot from "@/components/AntSpinDot/index.vue";
import {getUrlParam} from "@/common/common"

export default {
  name: "LeftTree",
  components: {
    AntSpinDot,
    DragModal,
    AddStructure,
    AddReviewComments,
    PropertyStructure,
  },
  props: {},
  data() {
    return {
      /** 初始数据 */
      initData: [],
      /** 模态框状态 */
      modalVisible: false,
      /** 模态框唯一Key */
      actionName: "",
      /** 模态框标题 */
      title: "",
      /** 模态框，选项卡Key */
      tabKey: "",
      /** 添加类型 */
      addType: '',
      /** 节点类型CODE */
      struTypeCode: "",
      /** 选中节点 */
      checkedNode: "",
      /** 加载对象 */
      loader: undefined,
      /** 上下移动节点标识，防止快速移动 */
      moveNodeFlag: true,
      /** zTree 配置项 */
      setting: {
        data: {
          key: {
            title: "description"
          },
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
          }
        },
        view: {
          /** 显示 / 不显示 连线 */
          showLine: true,
          /** 显示 / 隐藏 提示信息 */
          showTitle: false,
          /** 支持 / 不支持 HTML 脚本 */
          nameIsHTML: true,
          /** 显示 / 隐藏 图标 */
          showIcon: false,
          /** 双击节点 切换 / 不切换 展开状态 */
          dblClickExpand: false,
          /** 是否允许同时选中多个节点 */
          selectedMulti: false,
          /** 是否允许可以选择 zTree DOM 内的文本 */
          txtSelectedEnable: true,
          /** 显示动画效果 */
          expandSpeed: "fast"
        },
        edit: {
          enable: true,
          drag: {
            isCopy: false,
            isMove: false,
            prev: false,
            next: false,
            inner: false
          },
          editNameSelectAll: true,
          showRenameBtn: false,
          showRemoveBtn: false,
        },
        async: {
          enable: true,
          url: "/DFMEA/mfmeaBoundaryMap/Rb04263G3/func",
          dataType: "json",
          type: "post",
          dataFilter: this.handleDataFilter
        },
        callback: {
          beforeClick: this.handleBeforeClick,
          beforeRightClick: this.handleBeforeRightClick,
          beforeAsync: this.handleBeforeAsync,
          onAsyncSuccess: this.handleOnAsyncSuccess,
          onDblClick: this.handleOnDblClick,
          onRename: this.handleOnRename,
          onCollapse: this.treeNodeCollapse,
          onExpand: this.treeNodeExpand,
        }
      },
      // 刷新后选择的节点id
      onAsyncSuccessSelectId: "",
      // 折叠节点ids
      foldNodeIds: [],
    };
  },
  watch: {
    modalVisible(v) {
      this.keyListenerChange(v);
    },
  },
  created() {
  },
  mounted() {
    this.forbidRightClick();
    this.initLeftTree();
  },
  methods: {
    /******************************************* zTree Start **************************************************/
    /**
     * 初始化左侧树
     */
    initLeftTree(zNodes = []) {
      let _that = this;
      let settings = $.extend({}, _that.setting);
      settings.view.fontCss = _that.setNodeFontCss;
      settings.view.showTitle = true; // 设置鼠标移入显示
      settings.async.contentType = "application/json";
      settings.async.otherParam = {
        fmeaId: _that.$store.getters.rfmeaId,
      };
      // 初始化ztree
      $.fn.zTree.init($("#leftTree"), settings, zNodes);
    },
    /**
     * 用于对 Ajax 返回数据进行预处理的函数
     * @param treeId
     * @param parentNode
     * @param responseData
     */
    handleDataFilter(treeId, parentNode, responseData) {
      let _that = this;
      let childNodes = responseData.data.mfmeaStruTreeModels;
      _that.initData = responseData.data.mfmeaStruTreeModels;
      for (let i = 0, l = childNodes.length; i < l; i++) {
        let node = childNodes[i];
        // 设置【description】为节点的title
        node['description'] = replaceNullName(node);
        node.name = _that.getNodeName(node);
      }
      // 获取左侧zTree
      this.$nextTick(() => {
        let treeObj = $.fn.zTree.getZTreeObj("leftTree");
        // 循环所有折叠状态节点将其折叠
        for (let i = 0; i < _that.foldNodeIds.length; i++) {
          treeObj.expandNode(treeObj.getNodeByParam("id", _that.foldNodeIds[i]), false, true, false);
        }
      })
      return childNodes;
    },
    /**
     * 用于捕获单击节点之前的事件回调函数，并且根据返回值确定是否允许单击操作
     * @param treeId
     * @param treeNode
     * @param clickFlag
     */
    handleBeforeClick(treeId, treeNode, clickFlag) {
      // 存储当前节点信息
      this.setCheckedNode(treeNode);
    },
    /**
     * 用于捕获 zTree 上鼠标右键点击之前的事件回调函数，并且根据返回值确定触发 onRightClick 事件回调函数
     * @param treeId
     * @param treeNode
     */
    handleBeforeRightClick(treeId, treeNode) {
      // 右键非节点时，忽略
      if (!treeNode) return;
      // 存储当前节点信息
      this.setCheckedNode(treeNode);
      // 获取右键菜单项
      let bthMenuBtn = this.getMenuBtn();
      // 处理右键菜单
      this.handleContextMenu(treeNode, bthMenuBtn);
    },
    /**
     * 用于捕获异步加载之前的事件回调函数，zTree 根据返回值确定是否允许进行异步加载
     * @param treeId
     * @param treeNode
     */
    handleBeforeAsync(treeId, treeNode) {
      // 开启加载...
      this.handleShowHideLoading(true);
    },
    /**
     * 用于捕获异步加载正常结束的事件回调函数
     * 如果设置了 setting.callback.beforeAsync 方法，且返回 false，
     * 将无法触发 onAsyncSuccess / onAsyncError 事件回调函数。
     */
    handleOnAsyncSuccess(event, treeId, treeNode, msg) {
      let _that = this;
      // 处理选中ZTree节点
      let nodes = [_that.$store.getters.checkedLeftNode];
      _that.setCheckedNode(nodes[0]);
      // 重置防止上下移动按钮点击过快标识的状态
      _that.moveNodeFlag = true;
      // 恢复高亮复制节点
      _that.restoreHighLightCopyNode();
      // 关闭加载...
      _that.handleShowHideLoading(false);
      // 设置节点选中
      _that.selectNode(treeId)
    },
    /**
     * 用于捕获 zTree 上鼠标双击之后的事件回调函数
     * @param event
     * @param treeId
     * @param treeNode
     */
    handleOnDblClick(event, treeId, treeNode) {
      // 进入编制状态若为查看，禁用双击重命名
      if (getUrlParam("enterState")) return false;
      // 防止，双击展开折叠时报错
      if (treeNode) {
        let treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeNode.name = treeNode.description;
        treeObj.editName(treeNode);
        // 禁用快捷键
        this.keyListenerChange(true)
      }
    },
    /**
     * 用于捕获节点编辑名称结束之后的事件回调函数。
     * @param event
     * @param treeId
     * @param treeNode
     * @param isCancel
     */
    handleOnRename(event, treeId, treeNode, isCancel) {
      let _that = this;
      let treeObj = $.fn.zTree.getZTreeObj(treeId);
      // 非空
      if (!treeNode.name) {
        treeNode.name = treeNode.description;
      }
      // 未更改
      if (treeNode.name === treeNode.description) {
        console.log('未更改' + treeNode.name);
      } else {
        if (treeNode.name.length < 500) {
          // 调接口
          _that.$api.updateNodeName({
            fmeaId: _that.$store.getters.rfmeaId,
            struId: treeNode.id,
            struName: treeNode.name,
          }).then((res) => {
            if (res.flag) {
              _that.$message.success(res.message, 1);
            } else {
              _that.$message.error(res.message, 1);
            }
          }).catch((error) => {
            _that.$message.error(error.response.data.message);
          }).finally(() => {
            _that.updateRightX6Node(treeNode);
          });
        } else {
          _that.$message.warn(_that.$t('global-message.warn.node-name-length'));
          treeNode.name = treeNode.description;
        }
      }
      treeNode.description = treeNode.name;
      treeNode.name = this.getNodeName(treeNode);
      treeObj.updateNode(treeNode);
      // 启用快捷键
      this.keyListenerChange(false)
    },
    /**
     * 取得节点名称
     * @param node
     * @returns {string}
     */
    getNodeName(node) {
      let nodeName = '&nbsp;';
      // 节点图标
      let nodeIcon = this.getNodeIcon(node);
      if (nodeIcon) {
        nodeName += nodeIcon + '&nbsp;';
      }
      // 附件标识 0：无，1：有
      if (node.annexFlag === '1') {
        nodeName += "<i class='iconfont iconshuxing1' onclick='handleAnnexLIconClick(\"" + node.id + "\")'></i>" + "&nbsp;";
      }
      // 评审意见
      if (node.hasStruComment) {
        nodeName += `<i class="iconfont iconxiaoxi_right"></i>` + '&nbsp;';
      }
      nodeName += node.description;
      return nodeName;
    },
    /**
     * 根据节点类型不同,展示不同的Icon
     * @param node 节点
     */
    getNodeIcon(node) {
      let iconClass = "iconfont ";
      switch (node.struTypeCode) {
        case '01': // 结构
          iconClass += this.$store.getters.treeIcons.structuralAnalysis01;
          break;
        case '99': // 接口
          iconClass += this.$store.getters.treeIcons.structuralAnalysis99;
          break;
      }
      return `<i class="${iconClass}"></i>`;
    },
    /**
     * 设置功能、失效、要求和产品特征字体着色
     * @param treeId
     * @param treeNode
     * @returns {*}
     */
    setNodeFontCss(treeId, treeNode) {
      return this.$store.getters.nodeTypeDict.zTreeLNodeColor['chartFlag' + (treeNode.deep > 1 ? treeNode.chartFlag : '1')];
    },
    /**
     * 单级折叠/展开（顶部按钮）
     */
    collapseExpand() {
      let _that = this;
      let checkedNode = _that.$store.getters.lastCheckedNode;
      let treeObj = $.fn.zTree.getZTreeObj('leftTree');
      treeObj.expandNode(checkedNode, !checkedNode?.open, true, true);
      _that.saveFoldNodeIds(checkedNode)
      document.getElementById("leftTree").style.paddingLeft = "15px";
    },
    /**
     * 全部折叠/展开（顶部按钮）
     */
    collapseExpandAll() {
      let _that = this;
      let checkedNode = _that.$store.getters.lastCheckedNode;
      let treeObj = $.fn.zTree.getZTreeObj('leftTree');
      let nodes = treeObj.getNodesByParam("level", checkedNode.level, null);
      let expandFlag = checkedNode?.open;
      for (let i = 0, len = nodes.length; i < len; i++) {
        // 聚焦当前选中节点
        treeObj.expandNode(nodes[i], !expandFlag, true, checkedNode.id === nodes[i].id);
        _that.saveFoldNodeIds(nodes[i])
      }
      document.getElementById("leftTree").style.paddingLeft = "15px";
    },
    /**
     * 树节点折叠
     */
    treeNodeCollapse(event, treeId, treeNode) {
      this.saveFoldNodeIds(treeNode);
    },
    /**
     * 树节点展开
     */
    treeNodeExpand(event, treeId, treeNode) {
      this.saveFoldNodeIds(treeNode);
    },
    /**
     * 保存节点展开折叠状态
     */
    saveFoldNodeIds(checkedNode) {
      let _that = this;
      // open：f为折叠 t为展开
      if (!checkedNode?.open) {
        // 存储折叠节点ID
        _that.foldNodeIds.push(checkedNode.id)
      } else {
        // 清除节点折叠状态
        _that.foldNodeIds = _that.foldNodeIds.filter(item => item !== checkedNode.id);
      }
    },
    /**
     * 显示、隐藏 -- 加载Loading
     * @param flag
     */
    handleShowHideLoading(flag) {
      if (flag) {
        if (this.loader) this.loader.hide();
        this.loader = this.$loading.show({
          container: this.$refs.leftTree,
          color: '#1890FF',
        }, {
          // 自定义加载动画组件
          default: this.$createElement('ant-spin-dot'),
        });
      } else {
        this.loader.hide();
      }
    },
    /******************************************* zTree End **************************************************/

    /******************************************* 右键菜单 Start **************************************************/
    /**
     * 取得当前节点的右键菜单项
     * @param checkNode 选中节点
     */
    getCurrentNodeMenus(checkNode) {
      let nodeTypeDict = Object.values(this.$store.getters.nodeTypeDict.structureAnalysis).filter((item) => {
        return item.key === checkNode.struTypeCode;
      })[0];
      // 1：只读，2：编制
      let readOnly = this.$api.isLook;
      // 只读
      if (readOnly === '1') {
        return nodeTypeDict.leftMenuReadOnly;
      } else {
        return nodeTypeDict.leftMenu;
      }
    },
    /**
     * 获取右键菜单项
     */
    getMenuBtn() {
      // 选中节点
      let checkedNode = this.$store.getters.lastCheckedNode;
      if (!checkedNode) return;
      // 复制剪切的节点
      let lastCopyOrCutNode = this.$store.getters.lastCopyOrCutNode;
      // 复制剪切的标识位：copy、cut
      let lastCopyOrCut = this.$store.getters.lastCopyOrCut;
      // 取得当前节点的右键菜单项
      let cNodeMenus = this.getCurrentNodeMenus(checkedNode);
      let menuBtn = {};
      this.$store.getters.struLeftTreeMenus.forEach((item) => {
        if (cNodeMenus.indexOf(item.key) !== -1) {
          switch (item.key) {
            case "cut": // 剪切
              // 根节点不能剪切
              if (checkedNode.deep === 1) return false;
              break;
            case "paste": // 粘贴
              if (!lastCopyOrCut) return false; // 没有复制或剪切，不允许粘贴
              // 剪切的节点不能粘贴在它的子节点下(包含自己)
              if (showPasteBtn('leftTree', this.$store.getters.nodeTypeDict.paste,
                  lastCopyOrCutNode, checkedNode, lastCopyOrCut) === 1) return false;
              break;
            case "delete": // 删除
              if (checkedNode.deep === 1) return false;  // 非根节点删除
              break;
            case "addParent": // 添加上级
              if (checkedNode.deep !== 1) return false; // 根节点可以添加
              break;
            case "moveUp": // 上移
              if (checkedNode.deep === 1) return false; // 根节点不能移动
              else if (!showMoveUpBtn('leftTree', checkedNode)) return false;
              break;
            case "moveDown": // 下移
              if (checkedNode.deep === 1) return false;  // 根节点不能移动
              else if (!showMoveDownBtn('leftTree', checkedNode)) return false;
              break;
            case "addBoundary": // 添加边界图
              if (checkedNode.deep === 1) return false; // 根节点不能显示
              if (checkedNode.chartFlag === 1) return false; // chartFlag 0:隐藏 1:显示
              if (!showShowBtn('leftTree', checkedNode)) return false; // 父节点已经隐藏，当前节点不允许显示
              break;
            case "addAllBoundary": // 添加全部到边界图
              if (checkedNode.deep != 1 && !showShowBtn('leftTree', checkedNode)) return false; // 父节点已经隐藏，当前节点不允许显示
              break;
            case "property": // 属性
              if (checkedNode.connectId) return false;  // 连线结构没有属性
              break;
            default:
              break;
          }
          // 追加菜单项
          let menuObj = {name: this.$t('' + item.label + ''), icon: "fas iconfont " + item.icon};
          let children = {};
          if (item.children && item.children.length > 0) {
            for (let i = 0, len = item.children.length; i < len; i++) {
              children['' + item.children[i].key + ''] = {name: this.$t('' + item.children[i].label + '')};
            }
            menuObj['items'] = children;
          }
          menuBtn['' + item.key + ''] = menuObj;
        }
      });
      // 处理右键菜单的分割线
      menuBtn = this.handleContextMenuSep(menuBtn);
      return menuBtn;
    },
    /**
     * 处理右键菜单的分割线
     * @param menuBtn
     */
    handleContextMenuSep(menuBtn) {
      let afterFilter = Object.keys(menuBtn);
      let operationTypes = this.$store.getters.nodeTypeDict.operationType;
      let sepIndex = 1;
      for (let i = 0; i < operationTypes.length; i++) {
        let innerJoinArray = afterFilter.filter((v) => operationTypes[i].includes(v));
        if (innerJoinArray && innerJoinArray.length > 0) {
          let index = afterFilter.findIndex(val => val === innerJoinArray[innerJoinArray.length - 1]);
          // 最后一组分割线不显示
          if (i < operationTypes.length - 1 && afterFilter.length > 1) {
            afterFilter.splice(index + 1, 0, 'sep' + sepIndex++);
          }
        }
      }
      let newMenuBtn = {};
      for (let i = 0; i < afterFilter.length; i++) {
        for (let j in menuBtn) {
          if (afterFilter[i] === j) {
            newMenuBtn['' + afterFilter[i] + ''] = menuBtn[j];
            break;
          } else {
            newMenuBtn['' + afterFilter[i] + ''] = "---------";
          }
        }
      }
      return newMenuBtn;
    },
    /**
     * 处理右键菜单
     * @param node 节点
     * @param items 菜单项
     */
    handleContextMenu(node, items) {
      let _that = this;
      // 隐藏上次菜单
      let selector = '#' + node.tId + '_a'
      jQuery.contextMenu('destroy', selector);
      jQuery.contextMenu({
        selector: selector,
        autoHide: true,
        zIndex: 10,
        items: items,
        callback: function (itemKey, opt) {
          let arr = itemKey.split("_");
          let key, label;
          key = arr[0];
          if (arr.length > 1 && key === 'convert') {
            label = arr[1];
          }
          let actionInfo = {key: key, label: label};
          _that.menuAction(actionInfo);
        },
      });
    },
    /**
     * 右键菜单事件
     * @param actionInfo 菜单项信息
     */
    menuAction(actionInfo) {
      let checkedNode = this.$store.getters.lastCheckedNode;
      this.checkedNode = checkedNode;
      this.actionName = actionInfo.key;
      switch (actionInfo.key) {
        case "addStructure": // 结构
          this.addType = 'struTree';
          this.clearHighLightCopyCutNode();
          // checkedNode.chartFlag = 0;
          this.handleAddModal(checkedNode, actionInfo.key);
          this.modalVisible = true;
          break;
        case "copy": // 复制
          this.setHighLightCopyCutNode("copy");
          // 顶部按钮状态刷新
          this.refreshTopTreeBtnStatus();
          break;
        case "cut": // 剪切
          this.setHighLightCopyCutNode("cut");
          // 顶部按钮状态刷新
          this.refreshTopTreeBtnStatus();
          break;
        case "paste": // 粘贴
          this.paste();
          break;
        case "delete": // 删除
          this.clearHighLightCopyCutNode();
          this.deleteNode(checkedNode);
          break;
        case "moveUp": // 上移
          this.clearHighLightCopyCutNode();
          this.moveNode(checkedNode, -1);
          break;
        case "moveDown": // 下移
          this.clearHighLightCopyCutNode();
          this.moveNode(checkedNode, 1);
          break;
        case "addParent": // 添加上级
          this.clearHighLightCopyCutNode();
          this.addParent(checkedNode);
          break;
        case "property": // 属性
          this.clearHighLightCopyCutNode();
          this.handlePropertyModal(checkedNode);
          this.modalVisible = true;
          break;
        case "addReviewComments": // 添加评审意见
          this.clearHighLightCopyCutNode();
          this.handleReviewCommentsModal(checkedNode);
          this.modalVisible = true;
          break;
        case 'convert': // 转换
          this.handleConvert();
          break;
        case 'addBoundary': // 添加边界图
          this.addRightX6Node(checkedNode);
          break;
        case 'addAllBoundary': // 添加全部到边界图
          this.addAllRightX6Node(checkedNode);
          break;
      }
    },
    /**
     * 处理转换
     */
    handleConvert() {
      let _that = this;
      _that.$api.structPartConversion({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.$store.getters.lastCheckedNode.id
      }).then((res) => {
        if (res.flag) {
          _that.initLeftTree();
          _that.initRightX6();
        } else {
          _that.$message.error(res.message, 1);
        }
      });
    },
    /**
     * 处理添加
     * @param node 节点
     * @param menuKey 菜单标识
     */
    handleAddModal(node, menuKey) {
      let name = node.description;
      let adds = this.$store.getters.nodeTypeDict.addModals;
      for (let i = 0, len = adds.length; i < len; i++) {
        if (adds[i].menuKey === menuKey) {
          this.title = this.$t('' + adds[i].title + '') + name;
          this.struTypeCode = adds[i].struTypeCode;
          this.tab = this.$t('' + adds[i].label + '');
          return;
        }
      }
    },
    /**
     * 处理合并Modal逻辑
     * @param node 节点
     */
    handleMergeModal(node) {
      let struTypeCode = node.struTypeCode;
      let merges = this.$store.getters.nodeTypeDict.mergeModals;
      for (let i = 0; i < merges.length; i++) {
        if (merges[i].key === struTypeCode) {
          this.actionName = merges[i].action;
          this.title = this.$t('' + merges[i].title + '');
          return;
        }
      }
    },
    /**
     * 处理属性Modal逻辑
     * @param node 节点
     * @param tabKey 选项卡Key
     */
    handlePropertyModal(node, tabKey = "") {
      let name = "14,07".indexOf(node.struTypeCode) !== -1 ? "" : node.description;
      let merges = this.$store.getters.nodeTypeDict.propertyModals;
      let merge = {};
      for (let i = 0; i < merges.length; i++) {
        if ("09,10".indexOf(node.struTypeCode) !== -1
            && merges[i].key === node.curOptTypeCode) {
          merge = merges[i];
          break;
        }
        if (merges[i].key === node.struTypeCode) {
          merge = merges[i];
          break;
        }
      }
      this.actionName = merge.action;
      this.title = this.$t('' + merge.title + '') + name;
      this.tabKey = tabKey;
    },
    /**
     * 处理评审意见Modal逻辑
     * @param node 节点
     */
    handleReviewCommentsModal(node) {
      let name = "14,07".indexOf(node.struTypeCode) !== -1 ? "" : node.description;
      let reviewComments = this.$store.getters.nodeTypeDict.reviewCommentsModals;
      for (let i = 0, len = reviewComments.length; i < len; i++) {
        if ("09,10".indexOf(node.struTypeCode) !== -1
            && reviewComments[i].key === node.curOptTypeCode) {
          this.title = this.$t('' + reviewComments[i].title + '') + name;
          return;
        }
        if (reviewComments[i].key === node.struTypeCode) {
          this.title = this.$t('' + reviewComments[i].title + '') + name;
          return;
        }
      }
    },
    /******************************************* 右键菜单 End **************************************************/

    /******************************************* 父组件方法 Start **************************************************/
    /**
     * 监听快捷键
     * @param flag true、false
     */
    keyListenerChange(flag) {
      this.$emit("keyListenerChange", flag);
    },
    /**
     * 初始化边界图
     */
    initRightX6() {
      this.$emit('initRightX6');
    },
    /**
     * 存储当前节点信息
     */
    setCheckedNode(node) {
      this.$emit("setCheckedNode", node, "leftTree");
    },
    /**
     * 设置：复制/剪切时，节点高亮
     */
    setHighLightCopyCutNode(copyCut) {
      this.$emit("setHighLightCopyCutNode", copyCut, "leftTree");
    },
    /**
     * 顶部按钮状态刷新
     */
    refreshTopTreeBtnStatus() {
      this.$emit("refreshTopTreeBtnStatus");
    },
    /**
     * 清除：复制/剪切时，节点高亮
     */
    clearHighLightCopyCutNode() {
      this.$emit("clearHighLightCopyCutNode", "leftTree");
    },
    /**
     * 恢复高亮复制节点,目的：允许一次复制多次粘贴
     */
    restoreHighLightCopyNode() {
      this.$emit("restoreHighLightCopyNode", "leftTree");
    },
    /**
     * 删除节点
     */
    deleteNode(node) {
      this.$emit("deleteNode", node);
    },
    /**
     * 更新右侧X6节点
     */
    updateRightX6Node(node) {
      this.$emit("updateRightX6Node", node);
    },
    /**
     * 添加右侧X6节点
     */
    addRightX6Node(node) {
      this.$emit("addRightX6Node", node);
    },
    /**
     * 添加全部节点到右侧X6节点
     */
    addAllRightX6Node(node) {
      this.$emit("addAllRightX6Node", node);
    },
    /**
     * 显示、隐藏主界面 -- 加载Loading
     */
    showHideLoading(flag) {
      this.$emit("showHideLoading", flag);
    },
    /******************************************* 父组件方法 End **************************************************/

    /******************************************* 子组件方法 Start **************************************************/
    /**
     * 关闭模态框
     */
    closeModal() {
      this.modalVisible = false;
    },
    /******************************************* 子组件方法 End **************************************************/

    /**
     * 粘贴节点
     */
    paste() {
      let _that = this;
      // 粘贴是否携带上级功能网、失效网关系变量 0：不携带；1：携带
      var pastePormpt = 0;
      if (_that.$store.getters.lastCopyOrCut === 'copy'
          && (_that.$store.getters.lastCopyOrCutNode.struTypeCode === '01'
              || _that.$store.getters.lastCopyOrCutNode.struTypeCode === '99')) {
        _that.$confirm({
          title: this.$t('global-message.remind'),
          content: this.$t('global-message.paste.prompt'),
          icon: "aaoopqa", //图标，不想用就随便写一个
          okText: this.$t('global-btn.yes'),
          cancelText: this.$t('global-btn.no'),
          onCancel() {
            pastePormpt = 0;
            _that.pasteJump(pastePormpt);
          },
          onOk() {
            pastePormpt = 1;
            _that.pasteJump(pastePormpt);
          },
        });
      } else {
        _that.pasteJump(pastePormpt);
      }
    },
    /**
     * 粘贴跳转
     */
    pasteJump(pastePormpt) {
      let _that = this;
      // 判断是复制还是剪切，并调用接口
      _that.$api.pasteNode({
        optType: _that.$store.getters.lastCopyOrCut === 'copy' ? 1 : 2, // 1:表示复制，2:表示剪切
        srcStruId: _that.$store.getters.lastCopyOrCutNode.id, // 需移动的结构id
        struId: _that.$store.getters.lastCheckedNode.id, // 目标结构id（复制剪切操作时不需要）
        fmeaId: _that.$store.getters.rfmeaId,
        chartFlag: _that.$store.getters.lastCheckedNode.chartFlag,
        pastePormpt: pastePormpt // 是否携带上级功能网、失效网关系 1：携带；0：不携带
      }).then((res) => {
        if (res.flag) {
          _that.onAsyncSuccessSelectId = res.data.pasteStruId;
          _that.initLeftTree();
          _that.initRightX6();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        // 清除：复制/剪切时，节点高亮
        _that.clearHighLightCopyCutNode();
      });
    },
    /**
     * 上移/下移
     * @param node
     * @param optType 1上移，2下移
     */
    async moveNode(node, optType) {
      let _that = this;
      if (!_that.moveNodeFlag) return;
      _that.moveNodeFlag = false;
      let targetNode = getMoveTargetNode('leftTree', node, optType);
      if (targetNode) {
        _that.treeLoading = true;
        await _that.$api.moveNode({
          fmeaId: _that.$store.getters.rfmeaId,
          optType: optType,
          struId: node.id,
          targetStruId: targetNode.id
        }).then((res) => {
          if (res.flag) {
            this.$message.success(res.message, 1);
            _that.initLeftTree();
            // _that.initRightX6();
          } else {
            _that.$message.error(res.message, 1);
          }
        });
      }
    },
    /**
     * 添加上级
     */
    addParent() {
      let _that = this;
      _that.$confirm({
        title: _that.$t('global-message.warn'),
        content: _that.$t('global-message.warn.add-parent'),
        icon: 'aaoopqa', //图标，不想用就随便写一个
        okText: _that.$t('global-btn.ok'),
        cancelText: _that.$t('global-btn.cancel'),
        onOk() {
          _that.$api.addParent({
            fmeaId: _that.$store.getters.rfmeaId,
            struId: _that.$store.getters.lastCheckedNode.id
          }).then((res) => {
            if (res.flag) {
              _that.initLeftTree();
              _that.initRightX6();
            } else {
              _that.$message.error(res.message, 1);
            }
          });
        },
        onCancel() {
        }
      });
    },
    /**
     * 在区域禁用浏览器右键菜单
     */
    forbidRightClick() {
      document.getElementById("leftTree").oncontextmenu = function (e) {
        return false;
      };
    },
    // 设置节点选中
    selectNode(treeId) {
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      var node = treeObj.getNodeByParam("id", this.onAsyncSuccessSelectId);
      if (node) {
        // 设置节点选中
        treeObj.selectNode(node);
        this.handleBeforeClick(treeId, node, 1);
        this.onAsyncSuccessSelectId = "";
      }
    },
  },
};
</script>
<style lang="less" scoped>

@import "~@/styles/zTree";

</style>
