<template>
  <div>
    <!-- Tree Start -->
    <a-spin
        :delay="delayTime"
        :spinning="treeLoading">
      <a-list v-show="isEmpty" :data-source="[]"/>
      <ul id="leftTree" class="ztree"></ul>
    </a-spin>
    <!-- Tree End -->
  </div>
</template>
<script>

import {fuzzySearch} from './fuzzysearch';

export default {
  name: "LeftTree",
  components: {},
  props: {
    versionDiffCloseFlag: {
      type: Boolean,
      default: false
    },
    versionLibraryDiffCloseFlag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      setting: {
        data: {
          key: {
            title: "title"
          }
        },
        view: {
          showIcon: false,
          fontCss: {color: '#c84d3c'}
        },
        callback: {
          onClick: this.leftTreeClick,
        }
      },
      /** tree数据 */
      treeData: [],
      /** tree加载中状态 */
      treeLoading: false,
      /** 延迟显示加载效果的时间（防止闪烁）*/
      delayTime: 300,
      /** 是否显示空状态 */
      isEmpty: true,
    };
  },
  watch: {
    // 监听差异处理弹框标志
    versionDiffCloseFlag(v) {
      if (v) {
        this.initLeftTree();
      }
    },
    // 监听知识库差异处理弹框标志
    versionLibraryDiffCloseFlag(v) {
      if (v) {
        this.initLeftTree();
      }
    }
  },
  mounted() {
    this.initLeftTree();
  },
  methods: {
    /**
     * 初始化左侧树
     */
    initLeftTree() {
      let _that = this;
      _that.treeLoading = true;
      _that.$api.getRiskChain({
        fmeaId: _that.$store.getters.rfmeaId
      }).then((res) => {
        if (res.flag) {
          _that.treeData = res.data;
          _that.isEmpty = !_that.treeData;
          if (!_that.treeData || _that.treeData.length === 0) return;
          let loop = (nodes) => {
            for (let i = 0, len = nodes.length; i < len; i++) {
              // 追加title
              nodes[i]['title'] = nodes[i].name;
              // 追加前缀
              if (nodes[i].prefix) nodes[i].name = nodes[i].prefix + '\xa0' + nodes[i].name;
              if (nodes[i].children && nodes[i].children.length > 0) {
                loop(nodes[i].children);
              }
            }
          }
          // 递归处理
          loop(_that.treeData);
          // 初始化
          $.fn.zTree.init($("#leftTree"), _that.setting, _that.treeData);
          // 默认选中第一个
          _that.defaultSelectFirstNode(_that.treeData[0].id);
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.treeLoading = false;
      });
    },
    /**
     * 默认选中第一个
     * @param id 节点ID
     */
    defaultSelectFirstNode(id) {
      let zTree = $.fn.zTree.getZTreeObj('leftTree');
      let node = zTree.getNodeByParam("id", id, null);
      zTree.selectNode(node);
      this.initRightRiskNet();
    },
    /**
     * 左侧树点击事件
     * @param event
     * @param treeId
     * @param treeNode
     */
    leftTreeClick(event, treeId, treeNode) {
      this.initRightRiskNet();
    },
    /**
     * 初始化右侧风险网
     */
    initRightRiskNet() {
      this.$emit('initRightRiskNet');
    },
    /**
     * 清空右侧风险网数据
     */
    cleanRightRiskNetData() {
      this.$emit('cleanRightRiskNetData');
    },
    /**
     * 过滤节点
     * @param sVal S值
     * @param symbolValue 符号
     * @param keywords 关键词
     */
    filterNode(sVal, symbolValue, keywords) {
      const flag = this.filterKeyWord(keywords);
      /**
       * flag返回true，代表没有数据，不执行下面方法
       * flag返回undefined 或者 false 代表有数据通过执行
       */
      if (!flag) {
        let zTreeObj = $.fn.zTree.getZTreeObj('leftTree');
        if (zTreeObj === null) {
          return;
        } else {
          this.filterSValNode(zTreeObj, sVal, symbolValue);

          let nodes = zTreeObj.getNodes();
          let firstNode = this.getFirstNode(nodes);
          // 由默认从左树第一个节点开始检索改为从选中节点进行检索
          let checkedNode = zTreeObj.getSelectedNodes(true);
          if (!firstNode) {
              this.isEmpty = true;
              this.cleanRightRiskNetData();
          } else {
              this.isEmpty = false;
              // 当选中节点不满足检索条件时，默认选中符合检索条件的第一个节点 否则就按选中节点检索
              if (checkedNode.length === 0) {
                this.defaultSelectFirstNode(firstNode.id);
              } else {
                this.defaultSelectFirstNode(checkedNode.id);
              }

          }
        }
      }
    },
    /**
     * 过滤S值
     * @param zTreeObj 树对象
     * @param sVal S值
     * @param symbolValue 符号
     */
    filterSValNode(zTreeObj, sVal, symbolValue) {
      let nodes = zTreeObj.getNodes();
      for (let i = 0, len = nodes.length; i < len; i++) {
        if (!sVal) {
          zTreeObj.showNode(nodes[i]);
          continue;
        }
        if (nodes[i].prefix) {
          let nodeSVal = nodes[i].prefix.split('S=')[1];
          switch (symbolValue) {
            case '=':
              if (sVal !== nodeSVal) zTreeObj.hideNode(nodes[i]);
              break;
            case '>':
              if (Number(sVal) >= Number(nodeSVal)) {
                zTreeObj.hideNode(nodes[i]);
              }
              break;
            case '<':
              if (Number(sVal) <= Number(nodeSVal)) zTreeObj.hideNode(nodes[i]);
              break;
          }
        } else {
          zTreeObj.hideNode(nodes[i]);
        }
      }
    },
    /**
     * 获取第一个节点
     * @param nodes 节点数组
     */
    getFirstNode(nodes) {
      for (let i = 0, len = nodes.length; i < len; i++) {
        if (!nodes[i].isHidden) return nodes[i];
      }
    },
    /**
     * 过滤关键词
     * @param keyWord 关键词
     */
    filterKeyWord(keyWord) {
      fuzzySearch('leftTree', keyWord, true, true);
    }
  },
};
</script>

<style lang="less" scoped>

/deep/ .ztree li span.button {
  background-image: url("data:image/png;base64, ");
}

/deep/ .ztree li > a {
  width: 100%;
  height: 24px;
  border-radius: 2px;

  span {
    margin-left: 5px;
    font-size: 14px;
  }
}

/deep/ .ztree li > a:hover {
  text-decoration: none;
  background-color: #e6fffc;
}

/deep/ .ztree li a.curSelectedNode {
  background-color: #9bf2eb;
  opacity: 1;
}

/deep/ .ztree li span.button.switch {
  height: 25px;
}

/deep/ .ztree li > a {
  max-width: 95%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
}
</style>
