<template>
  <div class="dfmea-page-tree-content" id="mainContainer">
    <!-- 顶部按钮 -->
    <div class="top-button-bar">
      <a v-for='(item, index) in topBtns' :class="(item.active ? 'active ' : '') + (item?.float ? 'fr ' : '')"
        :key=index href='javascript:void(0);' @click='topBtnClick(item)'>
        <a-tooltip :title="$t('' + item.label + '')" :placement="item.float ? 'topRight' : 'topLeft'" arrowPointAtCenter
          v-if="!item.children">
          <i :class="'iconfont ' + item.icon"></i>
          <colorPicker :hidden=colorPickerHidden v-if="item.key === 'backgroundColor'" v-model='backgroundColor'
            :disabled='!item.active' :style="{ zIndex: '1000' }" v-on:change='handleBackgroundColorChange'>
          </colorPicker>
          <colorPicker :hidden=colorPickerHidden v-if="item.key === 'lineColor'" v-model='lineColor'
            :disabled='!item.active' :style="{ zIndex: '1000' }" v-on:change='handleLineColorChange'>
          </colorPicker>
          <!-- 右侧分割线 -->
          <a-divider v-if="item.sepR" type="vertical" />
        </a-tooltip>
        <!-- children top Start -->
        <a-tooltip :title="$t('' + item.label + '')" :placement="item.float ? 'topRight' : 'topLeft'" arrowPointAtCenter
          v-if="item.children && item.children.length > 0">
          <a-dropdown :trigger="[item.active ? 'click' : '']">
            <i :class="'iconfont ' + item.icon" />
            <a-menu slot="overlay">
              <template v-for="(item, index) in item.children">
                <a-menu-divider v-if="item.key === 'divider'" />
                <a-menu-item v-else :key="index" @click="dropDownClick(item)">
                  <i :class="'iconfont ' + item.icon"></i>
                </a-menu-item>
              </template>
            </a-menu>
          </a-dropdown>
          <!-- 右侧分割线 -->
          <a-divider v-if="item.sepR" type="vertical" />
        </a-tooltip>
        <!-- children top End -->
      </a>
    </div>
    <!-- 底部操作 -->
    <div class="structure-analysis-content">
      <SplitPane :default-percent='28' :min-percent='15' split='vertical'>
        <!-- 左侧树 -->
        <template slot='paneL'>
          <div class='leftTree' style="background-color:#fff">
            <LeftTree ref='leftTree' @initRightX6="initRightX6" @deleteNode="deleteNode"
              @deleteRootNode="deleteRootNode" @setCheckedNode="setCheckedNode"
              @setHighLightCopyCutNode="setHighLightCopyCutNode" @clearHighLightCopyCutNode="clearHighLightCopyCutNode"
              @addRightX6Node="addRightX6Node" @updateRightX6Node="updateRightX6Node" @showHideLoading="showHideLoading"
              @keyListenerChange='keyListenerChange' @addAllRightX6Node="addAllRightX6Node"
              @refreshTopTreeBtnStatus="refreshTopTreeBtnStatus"/>
          </div>
        </template>
        <!-- 右侧过程图 -->
        <template slot='paneR'>
          <div class='rightX6'>
            <RightX6 ref='rightX6' @initLeftTree="initLeftTree" @deleteNode="deleteNode"
              @setCheckedNode="setCheckedNode" @showHideLoading="showHideLoading"
              @refreshLineShowHide="refreshLineShowHide" @changePickerHiddenFlag="changePickerHiddenFlag" />
          </div>
        </template>
      </SplitPane>
    </div>
    <!-- P图 Start -->
    <Parameter ref="parameter" @keyListenerChange="keyListenerChange" />
    <!-- P图 End -->
    <HistoryChart ref="historyChart" />
    <!-- 配置 Start -->
    <Configuration ref="configuration" @setCheckedNode="setCheckedNode" />
    <!-- 配置 End -->
  </div>
</template>

<script>

import "@/styles/fmea.scss";
import SplitPane from 'vue-splitpane';
import LeftTree from "./components/LeftTree/index.vue";
import RightX6 from "./components/RightX6/index.vue";
import Configuration from "./components/TopBtnModal/Configuration/index.vue";
import Parameter from "./components/TopBtnModal/Parameter/index.vue";
import HistoryChart from "./components/TopBtnModal/HistoryChart/index.vue";
import AntSpinDot from "@/components/AntSpinDot/index.vue";
import {showMoveDownBtn, showMoveUpBtn, showPasteBtn} from "@/utils/treeMenuBtn";
import {addClass, removeClass} from "@/utils";
import {getNextX6NodePosition, getX6Node} from "@/views/structure/assets/topology";

export default {
  name: 'index',
  components: {
    LeftTree,
    RightX6,
    Configuration,
    Parameter,
    HistoryChart,
    SplitPane,
    AntSpinDot,
  },
  created() {
  },
  data() {
    return {
      /** 顶部按钮 */
      topBtns: JSON.parse(JSON.stringify(this.$store.getters.topologyTopBtns)),
      /** 删除弹出框 */
      deleteModal: undefined,
      /** 显示设置 */
      displaySettingsVisible: false,
      /** 下载 */
      downloadFlowChartVisible: false,
      /** 配置 */
      configurationVisible: false,
      /** 背景颜色 */
      backgroundColor: '',
      /** 线条颜色 */
      lineColor: '',
      /** 加载对象 */
      loader: undefined,
      colorPickerHidden: false
    }
  },
  watch: {
    '$store.getters.lastCheckedNode'() {
      this.refreshTopTreeBtnStatus()
    },
    '$store.getters.lastCheckedX6Node'() {
      this.refreshTopX6BtnStatus()
    },
  },
  mounted() {
    window.addEventListener('keydown', this.keyCodeForEvent);
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('keydown', this.keyCodeForEvent)
    });
  },
  methods: {
    /**
     * 监听键盘，快捷键
     * @param v
     */
    keyListenerChange(v) {
      if (v) {
        window.removeEventListener('keydown', this.keyCodeForEvent)
      } else {
        window.addEventListener('keydown', this.keyCodeForEvent)
      }
    },
    /**
     * 监听键盘，触发事件
     */
    keyCodeForEvent(e) {
      // 选中节点
      let checkedNode = this.$store.getters.lastCheckedNode;
      if (!checkedNode) return;
      // 复制剪切的节点
      let lastCopyOrCutNode = this.$store.getters.lastCopyOrCutNode
      // 复制剪切的标识位：copy、cut
      let lastCopyOrCut = this.$store.getters.lastCopyOrCut
      // 取得左侧菜单信息
      let leftTreeMenus = this.$store.getters.leftTreeMenus
      // 当前节点菜单项
      let cNodeMenus = this.$refs.leftTree.getCurrentNodeMenus(checkedNode);
      // X6菜单项
      let actionInfo
      switch (e.keyCode) {
        case 65: // 结构(Ctrl+A)
          if (!e.ctrlKey) return false
          if (checkedNode.connectId) return false
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'addStructure')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 46: // Delete
          if (checkedNode.deep === 1) return false // 根节点不能删除
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'delete')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 88: // 剪切(Ctrl+X)
          if (!e.ctrlKey) return false
          if (checkedNode.connectId) return false
          if (checkedNode.struTypeCode === '99') return false
          if (checkedNode.deep === 1) return false // 根节点不能剪切
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'cut')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 67: // 复制(Ctrl+C)
          if (!e.ctrlKey) return false
          if (checkedNode.connectId) return false
          if (checkedNode.struTypeCode === '99') return false
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'copy')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 86: // 粘贴(Ctrl+V)
          if (!e.ctrlKey) return false
          if (checkedNode.connectId) return false
          if (!lastCopyOrCut) return false // 没有复制或剪切，不允许粘贴

          // 剪切的节点不能粘贴在它的子节点下(包含自己)
          if (showPasteBtn('leftTree', this.$store.getters.nodeTypeDict.paste,
              lastCopyOrCutNode, checkedNode, lastCopyOrCut) === 1) return false
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'paste')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 38: // 同级上移(Ctrl+↑)
          if (!e.ctrlKey) return false
          if (checkedNode.deep === 1) return false  // 根节点不能移动
          else if (!showMoveUpBtn('leftTree', checkedNode)) return false;
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'moveUp')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 40: // 同级下移(Ctrl+↓)
          if (!e.ctrlKey) return false
          if (checkedNode.deep === 1) return false  // 根节点不能移动
          else if (!showMoveDownBtn('leftTree', checkedNode)) return false
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'moveDown')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
        case 78: // 添加评审意见(Shift+N)
          if (!e.shiftKey) return false
          actionInfo = this.getNodeActionInfo(leftTreeMenus, cNodeMenus, 'addReviewComments')
          if (actionInfo) this.$refs.leftTree.menuAction(actionInfo)
          break
          /*case 81: // 属性(Ctrl+Q)
            if (!e.ctrlKey) return false
            if (!x6NodeMenus) {
              return false
            }
            actionInfo = this.getNodeActionInfo(rightX6Menus, x6NodeMenus, 'property')
            if (actionInfo) {
              this.$refs.rightX6.modalVisible = true
              this.$refs.rightX6.handlePropertyModal(x6CheckedNode);
            }
            break*/
        default:
          break
      }
    },
    /**
     * 取得节点对应的菜单信息
     * @param lrTreeMenus 左右树总菜单
     * @param nodeMens 该节点菜单
     * @param menuKey 菜单标识
     */
    getNodeActionInfo(lrTreeMenus, nodeMens, menuKey) {
      let actionInfo
      if (nodeMens && nodeMens.indexOf(menuKey) === -1) {
        return
      }
      lrTreeMenus.forEach((item) => {
        if (item.key === menuKey) actionInfo = item
      })
      return actionInfo
    },
    /**
     * 下拉选中
     * @param item
     */
    dropDownClick(item) {
      if (!item.active) return; // 置灰按钮，点击无效
      switch (item.pKey) {
        case 'line': // 线条
          this.handleLineStyleChange(item.key);
          break;
        case 'connectLine': // 连线
          this.handleLineWayChange(item.key);
          break;
        default:
          break;
      }
    },
    /**
     * 刷新顶部zTree按钮状态
     */
    refreshTopTreeBtnStatus() {
      let _that = this;
      let topBtns = this.topBtns;
      let checkedNode = _that.$store.getters.lastCheckedNode;
      // 取消顶部按钮状态
      if (!checkedNode) {
        topBtns.forEach(btn => {
          if (_that.$store.getters.topologyTopZTreeBtns.indexOf(btn.key) !== -1) {
            btn.active = false;
          }
        })
        return;
      }
      // 复制剪切的节点
      let lastCopyOrCutNode = _that.$store.getters.lastCopyOrCutNode;
      // 复制剪切的标识位：copy、cut
      let lastCopyOrCut = _that.$store.getters.lastCopyOrCut;
      // 选中节点的右键菜单
      let cNodeMenus = _that.$refs.leftTree.getCurrentNodeMenus(checkedNode);
      // 选中节点过滤掉外部结构后的的子节点
      let checkedNodeChildren = [];
      if (checkedNode.children && checkedNode.children.length > 0) {
        checkedNodeChildren = checkedNode.children.filter(item => {
          return item.struTypeCode !== '99';
        })
      }
      // 1：只读，2：编制
      let readOnlyTopBtns = _that.$api.isLook === '1' ? _that.$store.getters.topologyReadOnlyTopBtns : [];
      // x6选中
      for (let i = 0, len = topBtns.length; i < len; i++) {
        let btn = topBtns[i];
        if (readOnlyTopBtns && readOnlyTopBtns.length > 0
            && readOnlyTopBtns.indexOf(btn.key) === -1) continue;
        switch (btn.key) {
          case 'copy': // 复制
            btn.active = cNodeMenus.indexOf(btn.key) !== -1;
            break;
          case 'cut': // 剪切 「根节点不能剪切」
            btn.active = (cNodeMenus.indexOf(btn.key) !== -1 && checkedNode.deep !== 1);
            break;
          case 'paste': // 粘贴
            btn.active = cNodeMenus.indexOf(btn.key) !== -1;
            if (!lastCopyOrCut) btn.active = false; // 没有复制或剪切，不允许粘贴
            // 剪切的节点不能粘贴在它的子节点下(包含自己)
            if (showPasteBtn('leftTree', _that.$store.getters.nodeTypeDict.paste,
                lastCopyOrCutNode, checkedNode, lastCopyOrCut) === 1) {
              btn.active = false;
            }
            break;
          case 'delete': // 删除「非根节点或根节点下孩子节点中struTypeCode为01的节点数为1」
            btn.active = (cNodeMenus.indexOf(btn.key) !== -1 && checkedNode.deep === 1 &&
                    checkedNodeChildren && checkedNodeChildren.length === 1)
                || (cNodeMenus.indexOf(btn.key) !== -1 && checkedNode.deep !== 1);
            break;
          case 'moveUp': // 上移
            btn.active = (cNodeMenus.indexOf(btn.key) !== -1 && showMoveUpBtn('leftTree', checkedNode));
            break;
          case 'moveDown': // 下移
            btn.active = (cNodeMenus.indexOf(btn.key) !== -1 && showMoveDownBtn('leftTree', checkedNode));
            break;
          case 'collapseExpand': // 单级折叠/展开
            btn.active = true;
            break;
          case 'collapseExpandAll': // 同级折叠/展开
            btn.active = true;
            break;
          default:
            break;
        }
      }
    },
    /**
     * 刷新顶部x6按钮状态
     */
    refreshTopX6BtnStatus() {
      let _that = this;
      let topBtns = this.topBtns;
      let checkedNode = _that.$store.getters.lastCheckedX6Node;
      // 取消顶部按钮状态
      if (!checkedNode) {
        topBtns.forEach(btn => {
          if (_that.$store.getters.topologyTopX6Btns.indexOf(btn.key) !== -1) {
            btn.active = false;
          }
        });
        return;
      }
      // 1：只读，2：编制
      let readOnlyTopBtns = _that.$api.isLook === '1' ? _that.$store.getters.topologyReadOnlyTopBtns : [];
      // x6选中
      let selectCells = _that.$refs.rightX6.rightX6Graph.getSelectedCells();
      for (let i = 0, len = topBtns.length; i < len; i++) {
        let btn = topBtns[i];
        if (readOnlyTopBtns && readOnlyTopBtns.length > 0
            && readOnlyTopBtns.indexOf(btn.key) === -1) continue;
        switch (btn.key) {
          case 'backgroundColor': // 背景颜色
            let nodes = selectCells.filter(cell => cell.isNode());
            btn.active = checkedNode && nodes.length > 0;
            break;
          case 'lineColor': // 线条颜色
            btn.active = checkedNode && checkedNode.shape === 'edge';
            break;
          case 'line': // 线条
            btn.active = checkedNode && checkedNode.shape === 'edge';
            break;
          case 'connectLine': // 连线
            btn.active = checkedNode && checkedNode.shape === 'edge';
            break;
          default:
            break;
        }
      }
    },
    /**
     * 顶部按钮
     */
    topBtnClick(item) {
      if (!item.active) return; // 置灰按钮，点击无效
      // 选中节点
      let checkedNode = this.$store.getters.lastCheckedNode;
      switch (item.key) {
        case 'copy': // 复制
          this.$refs.leftTree.setHighLightCopyCutNode('copy');
          // 刷新顶部树按钮状态
          this.refreshTopTreeBtnStatus();
          break;
        case 'cut': // 剪切
          this.$refs.leftTree.setHighLightCopyCutNode('cut');
          // 刷新顶部树按钮状态
          this.refreshTopTreeBtnStatus();
          break;
        case 'paste': // 粘贴
          this.$refs.leftTree.paste();
          break;
        case 'delete': // 删除
          if (checkedNode.deep === 1) {
            // 根节点删除
            this.deleteRootNode(checkedNode);
          } else {
            // 节点删除
            this.deleteNode(checkedNode);
          }
          break;
        case 'moveUp': // 上移
          this.$refs.leftTree.clearHighLightCopyCutNode();
          this.$refs.leftTree.moveNode(checkedNode, -1);
          break;
        case 'moveDown': // 下移
          this.$refs.leftTree.clearHighLightCopyCutNode();
          this.$refs.leftTree.moveNode(checkedNode, 1);
          break;
        case 'collapseExpand': // 单级折叠/展开
          this.$refs.leftTree.clearHighLightCopyCutNode();
          this.$refs.leftTree.collapseExpand();
          break;
        case 'collapseExpandAll': // 同级折叠/展开
          this.$refs.leftTree.clearHighLightCopyCutNode();
          this.$refs.leftTree.collapseExpandAll();
          break;
        case 'overallCenter': // 全屏
          this.$refs.rightX6.rightX6Graph.zoomToFit();
          break;
        case 'exportImages': // 导出图片
          // 图片导出时暂时禁用背景颜色弹窗 避免导出图片时背景颜色弹窗弹出
          this.colorPickerHidden = true;
          this.$refs.rightX6.exportImages();
          break;
        case 'parameter': // P图
          this.$refs.parameter.parameterVisible = true;
          break;
        case 'historyChart': // 历史边界图
          this.$refs.historyChart.visible = true;
          break;
        case 'configuration': // 配置
          this.$refs.configuration.visible = true;
          break;
        default:
          break;
      }
    },
    /**
     * 导出图片以后恢复背景颜色弹窗
     */
    changePickerHiddenFlag() {
      this.colorPickerHidden = false;
    },
    /**
     * 初始化左侧树
     */
    initLeftTree() {
      this.$refs.leftTree.initLeftTree();
    },
    /**
     * 初始化右侧X6
     */
    initRightX6() {
      this.$refs.rightX6.initRightX6();
    },
    /**
     * 刷新连线显示隐藏
     */
    refreshLineShowHide() {
      this.$refs.configuration.refreshLineShowHide();
    },
    /**
     * 处理背景颜色
     * @param color
     */
    handleBackgroundColorChange(color) {
      let _that = this;
      let cells = _that.$refs.rightX6.rightX6Graph.getSelectedCells();
      if (cells && cells.length > 0) {
        cells.forEach(cell => {
          if (cell.isNode()) {
            let node = this.$refs.rightX6.rightX6Graph.getCellById(cell.id);
            node.setAttrs({
              body: {
                fill: color
              }
            });
            _that.$refs.rightX6.updateNode(node);
          }
        })
      }
    },
    /**
     * 处理线条颜色
     * @param color
     */
    handleLineColorChange(color) {
      let _that = this;
      let checkedNode = _that.$store.getters.lastCheckedX6Node;
      if (!checkedNode) return;
      if (checkedNode.shape === 'edge') {
        let edge = this.$refs.rightX6.rightX6Graph.getCellById(checkedNode.id);
        // 修改颜色
        edge.setAttrs({
          line: {
            color: color, // 连线颜色
            stroke: color, // 连线颜色
          }
        })
        _that.$refs.rightX6.updateEdge(edge);
      }
    },
    /**
     * 处理线条样式
     * @param lineStyle
     */
    handleLineStyleChange(lineStyle) {
      let _that = this;
      let checkedNode = _that.$store.getters.lastCheckedX6Node;
      if (!checkedNode) return;
      if (checkedNode.shape === 'edge') {
        let edge = this.$refs.rightX6.rightX6Graph.getCellById(checkedNode.id);
        // 修改颜色
        edge.setAttrs({
          line: {
            color: edge.store.data.attrs.line.color, // 连线颜色
            stroke: edge.store.data.attrs.line.color, // 连线颜色
            strokeDasharray: lineStyle === 'solid' ? '' : lineStyle === 'dashed' ? 5 : 2, // 线条样式「实线、虚线、点」
          }
        })
        _that.$refs.rightX6.updateEdge(edge);
      }
    },
    /**
     * 处理线条方式
     * @param lineWay
     */
    handleLineWayChange(lineWay) {
      let _that = this;
      let checkedNode = _that.$store.getters.lastCheckedX6Node;
      if (!checkedNode) return;
      if (checkedNode.shape === 'edge') {
        let edge = this.$refs.rightX6.rightX6Graph.getCellById(checkedNode.id);
        switch (lineWay) {
          case 'taxi':
            edge.router = {
              name: 'er',
              args: {
                offset: 'center',
              },
            };
            edge.connector = undefined;
            break;
          case 'unbundled-bezier':
            edge.router = undefined;
            edge.connector = {name: 'smooth'}
            break;
          case 'straight':
            edge.router = undefined;
            edge.connector = {name: 'normal'}
            break;
          default:
            break;
        }
        // 修改颜色
        edge.setAttrs({
          line: {
            color: edge.store.data.attrs.line.color, // 连线颜色
            stroke: edge.store.data.attrs.line.color, // 连线颜色
          }
        })
        _that.$refs.rightX6.updateEdge(edge);
      }
    },
    /**
     * 添加右侧树节点
     * @param node
     */
    addRightX6Node(node) {
      let _that = this;
      let id = node.id;
      let pid = node.pid;
      let name = node.description;
      let struTypeCode = node.struTypeCode;
      let zIndex = node.deep;
      let position = getNextX6NodePosition(pid, struTypeCode);
      let x = position.x;
      let y = position.y;
      let x6Node = getX6Node(id, pid, x, y, name, struTypeCode, zIndex);
      _that.$api.addBoundary({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: id,
        chartFlag: 1,
        options: JSON.stringify(x6Node),
      }).then((res) => {
        if (res.flag) {
          _that.$refs.leftTree.initLeftTree()
          _that.$refs.rightX6.addNode(x6Node);
        } else {
          _that.$message.error(res.message, 1)
        }
      }).finally(() => {
        this.$refs.rightX6.rightX6Graph.zoomToFit();
      });
    },
    /**
     * 添加全部到右侧树节点
     * @param node
     */
    addAllRightX6Node(node) {
      let _that = this;
      let id = node.id;
      let pid = node.pid;
      let name = node.description;
      let struTypeCode = node.struTypeCode;
      let zIndex = node.deep;
      let position = getNextX6NodePosition(pid, struTypeCode);
      let x = position.x;
      let y = position.y;
      let x6Node = getX6Node(id, pid, x, y, name, struTypeCode, zIndex);
      _that.$api.addAllBoundary({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: id,
        chartFlag: 1,
        options: JSON.stringify(x6Node),
      }).then((res) => {
        if (res.flag) {
          _that.$refs.leftTree.initLeftTree()
          _that.$refs.rightX6.initRightX6Data();
        } else {
          _that.$message.error(res.message, 1)
        }
      }).finally(() => {
        this.$refs.rightX6.rightX6Graph.zoomToFit();
      });
    },
    /**
     * 修改右侧树节点
     * @param node
     */
    updateRightX6Node(node) {
      let cell = this.$refs.rightX6.rightX6Graph.getCellById(node.id);
      if (cell) {
        cell.setAttrs({
          text: {
            text: node.description
          },
          label: {
            title: node.description
          }
        });
        // 同步修改流程图根节点名称
        if (node.deep === 1) {
          this.$refs.rightX6.rootNodeName = node.description;
        }
        this.$refs.rightX6.updateNode(cell);
      }
    },
    /**
     * 删除节点
     */
    deleteNode(node) {
      let _that = this;
      // 确保唯一
      if (_that.deleteModal) {
        // 销毁
        _that.deleteModal.destroy();
      }
      let deleteContent = undefined;
      let deleteNumber = undefined;
      let data = {
        rfmeaId: _that.$store.getters.rfmeaId,
        struId: node.id
      };
      // 发送请求，统计删除的节点数量
      _that.$api.getDeleteNodeNumber(data).then(res => {
        if (res.flag) {
          deleteNumber = res.data;
          // 设置删除提示语
          if (node.struTypeCode == '01') { // 非根节点结构/边界图中方块结构
            deleteContent = _that.$t('global-message.warn.structural.analysis.node.delete', [deleteNumber]);
          } else if (node.struTypeCode == '99') { // 外部结构/界图中椭圆接口
            deleteContent = _that.$t('global-message.warn.exterior.elliptical.interface.delete', [deleteNumber]);
          }
          _that.deleteModal = _that.$confirm({
            title: _that.$t('global-message.warn'),
            content: deleteContent,
            okText: _that.$t('global-btn.ok'),
            cancelText: _that.$t('global-btn.cancel'),
            onOk() {
              // 开启加载...
              _that.showHideLoading(true);
              _that.$api.deleteNode({
                fmeaId: _that.$store.getters.rfmeaId,
                struId: node.id,
                connectId: node.lineType ? node.id : null,
                delFlag: 1
              }).then((res) => {
                if (res.flag) {
                  _that.initLeftTree();
                  _that.initRightX6();
                } else {
                  _that.$message.error(res.message, 1);
                }
              }).finally(() => {
                // 关闭加载...
                _that.showHideLoading(false);
              });
            },
            onCancel() {
            }
          });
        }
      });
    },
    /**
     * 删除根节点
     * @param node 节点
     */
     deleteRootNode(node) {
      let _that = this;
      let deleteContent = undefined;
      let deleteNumber = undefined;
      let data = {
        rfmeaId: _that.$store.getters.rfmeaId,
        struId: node.id
      };
      _that.$api.getDeleteNodeNumber(data).then(res => {
        if (res.flag) {
          deleteNumber = res.data;
          deleteContent = _that.$t('global-message.warn.nodo.radice.delete', [deleteNumber]);
          _that.$confirm({
            title: _that.$t('global-message.warn'),
            content: deleteContent,
            okText: _that.$t('global-btn.ok'),
            cancelText: _that.$t('global-btn.cancel'),
            onOk() {
              // 开启加载
              _that.showHideLoading(true);
              _that.$api.deleteRootNode({
                fmeaId: _that.$store.getters.rfmeaId,
                struId: node.id
              }).then((res) => {
                if (res.flag) {
                  _that.$message.success(res.message, 1);
                  _that.initLeftTree();
                  _that.initRightX6();
                } else {
                  _that.$message.error(res.message, 1);
                }
              }).finally(() => {
                // 关闭加载...
                _that.showHideLoading(false);
              })
            },
            onCancel() {
            }
          });
        }
      });
    },
    /**
     * 显示、隐藏主界面 -- 加载Loading
     * @param flag
     */
    showHideLoading(flag) {
      if (flag) {
        if (this.loader) this.loader.hide();
        this.loader = this.$loading.show({
          container: document.getElementById('mainContainer'),
          color: '#1890FF',
        }, {
          // 自定义加载动画组件
          default: this.$createElement('ant-spin-dot'),
        });
      } else {
        this.loader.hide();
      }
    },
    /**
     * 选中节点时，存储当前节点信息
     * @param node
     * @param treeFlag 区分选中标识
     */
    setCheckedNode(node, treeFlag) {
      if (node) {
        this.setCheckedLeftTree(node);
        this.setCheckedRightX6(node);
      } else {
        this.cleanCheckedLeftTree();
        this.cleanCheckedRightX6();
      }
    },
    /**
     * 选中左侧ztree
     * @param node
     */
    setCheckedLeftTree(node) {
      // ztree选中
      let treeObj = $.fn.zTree.getZTreeObj('leftTree');
      let treeNode = treeObj.getNodeByParam("id", node.id, null);
      if (!treeNode) this.cleanCheckedLeftTree();
      treeObj.selectNode(treeNode);
      // 缓存
      this.$store.dispatch('fmeaTree/set', {
        key: 'checkedLeftNode',
        value: treeNode
      });
      this.$store.dispatch('fmeaTree/set', {
        key: 'lastCheckedNode',
        value: treeNode
      });
    },
    /**
     * 选中右侧X6
     * @param node
     */
    setCheckedRightX6(node) {
      // 清空选中
      this.$refs.rightX6.rightX6Graph.cleanSelection();
      // 清除所有放大缩小框
      this.$refs.rightX6.rightX6Graph.clearTransformWidgets();
      // 清除所有连线选中
      this.cleanSelectedEdges();
      // cell选中
      let cell = this.$refs.rightX6.rightX6Graph.getCellById(node.id);
      if (!cell) return;
      // 根节点不允许选中
      if (cell.store.data.parent !== '00000000000000000000000000000000') {
        // x6选中
        if (cell && cell.isNode()) {
          this.backgroundColor = cell.attrs.body.fill;
          this.$refs.rightX6.rightX6Graph.resetSelection(cell);
        }
        // 颜色选中
        if (cell && cell.isEdge()) {
          let attrs = cell.getAttrs();
          this.lineColor = (attrs.line.color ? attrs.line.color : attrs.line.stroke);
          cell.attr('line/stroke', 'orange');
          // 增加连线线段
          // if (this.$api.isLook !== '1') {
          //   cell.addTools(
          //       [
          //         {
          //           name: 'segments',
          //           args: {
          //             stopPropagation: false,
          //           }
          //         }
          //       ]
          //   );
          // }
        }
        // 放大缩小框选中
        let nodes = this.$refs.rightX6.rightX6Graph.getNodes();
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === node.id) {
            this.$refs.rightX6.rightX6Graph.createTransformWidget(nodes[i]);
          }
        }
      }
      // 缓存
      this.$store.dispatch('fmeaTree/set', {
        key: 'checkedRightNode',
        value: node
      });
      this.$store.dispatch('fmeaTree/set', {
        key: 'lastCheckedX6Node',
        value: node
      });
    },
    /**
     * 清除左侧ztree
     */
    cleanCheckedLeftTree() {
      // ztree取消
      let treeObj = $.fn.zTree.getZTreeObj('leftTree');
      let selectedNodes = treeObj.getSelectedNodes();
      selectedNodes.forEach(node => {
        treeObj.cancelSelectedNode(node);
      });
      // 缓存
      this.$store.dispatch('fmeaTree/set', {
        key: 'checkedLeftNode',
        value: undefined
      });
      this.$store.dispatch('fmeaTree/set', {
        key: 'lastCheckedNode',
        value: undefined
      });
    },
    /**
     * 清除右侧X6
     */
    cleanCheckedRightX6() {
      // 清空选中
      this.$refs.rightX6.rightX6Graph.cleanSelection();
      // 清除所有放大缩小框
      this.$refs.rightX6.rightX6Graph.clearTransformWidgets();
      // 清除所有连线选中
      this.cleanSelectedEdges();
      // 缓存
      this.$store.dispatch('fmeaTree/set', {
        key: 'checkedRightNode',
        value: undefined
      });
      this.$store.dispatch('fmeaTree/set', {
        key: 'lastCheckedX6Node',
        value: undefined
      });
    },
    /**
     * 设置：复制/剪切时，节点高亮
     */
    setHighLightCopyCutNode(cutCopy) {
      let lastCheckedNode = this.$store.getters.lastCheckedNode;
      if (!lastCheckedNode) return;
      this.clearHighLightCopyCutNode();
      addClass(document.getElementById(lastCheckedNode.tId + '_a'), "curCopyCutNode");
      this.$store.dispatch("fmeaTree/set", {
        key: "lastCopyOrCutNode",
        value: lastCheckedNode
      });
      // 存储操作类型标识位：复制=copy or 剪切=cut
      this.$store.dispatch("fmeaTree/set", {
        key: "lastCopyOrCut",
        value: cutCopy
      });
    },
    /**
     * 清除：复制/剪切时，节点高亮
     */
    clearHighLightCopyCutNode() {
      let lastCopyOrCutNode = this.$store.getters.lastCopyOrCutNode;
      let treeId = lastCopyOrCutNode?.tId.split('_')[0];
      if (lastCopyOrCutNode && treeId) {
        let treeObj = $.fn.zTree.getZTreeObj(treeId);
        let node = treeObj.getNodeByParam("id", lastCopyOrCutNode?.id, null);
        if (node) {
          removeClass(document.getElementById(node.tId + '_a'), "curCopyCutNode");
        }
        this.$store.dispatch("fmeaTree/clearCopyOrCut");
      }
    },
    /**
     * 清除所有选中连线
     */
    cleanSelectedEdges() {
      let edges = this.$refs.rightX6.rightX6Graph.getEdges();
      edges.forEach(edge => {
        let attrs = edge.getAttrs();
        let color = attrs.line.color ? attrs.line.color : attrs.line.stroke;
        edge.attr('line/stroke', color);
        edge.attr('line/color', color);
        // 移除线段
        // if (edge.hasTool('segments')) {
        //   edge.removeTool('segments');
        // }
      });
    },
  },
  // 销毁
  destroyed() {
    window.rightX6Graph = undefined;
    $.contextMenu('destroy'); // 销毁所有菜单。
    this.$store.dispatch("fmeaTree/clear");
  }
}
</script>

<style lang='scss' scoped>


</style>
