<template>
  <div>
    <a-modal
        :title="$t('globalComponents.masterFmeaDiff.contrast')"
        :visible='visible'
        width="80%"
        :maskClosable="false"
        @cancel="visible = false"
        :footer="null">
      <a-row class="tr">
        {{ diffTotal }} {{ $t('globalComponents.masterFmeaDiff.a-diff') }}<span
          v-show="diffTotal>0">, {{ $t('globalComponents.masterFmeaDiff.current') + '\xa0' }}
        {{ curPosition }}/{{ diffTotal }}</span>
        <a-button class='ml10' icon="up" size="small" @click="diffPosition(-1)"></a-button>
        <a-button class='ml10' icon="down" size="small" @click="diffPosition(1)"></a-button>
      </a-row>
      <!-- 分割距离 -->
      <a-row class='mb_8'>
        <a-col :span='24'></a-col>
      </a-row>
      <!-- zTree表格 -->
      <div ref="diffTree">
        <ul id="diffTree" class="ztree"/>
      </div>
    </a-modal>
  </div>
</template>

<script>

import AntSpinDot from "@/components/AntSpinDot/index.vue";

export default {
  name: 'MasterFmeaDiff',
  components: {
    AntSpinDot
  },
  data() {
    return {
      /** 弹出框开关 */
      visible: false,
      /** ztree 配置项 */
      setting: {
        view: {
          fontCss: this.setNodeFontCss,
          showIcon: false,
          showLine: true,
          showTitle: true,
          nameIsHTML: true,
          dblClickExpand: false,
          selectedMulti: false,
          txtSelectedEnable: true,
          addDiyDom: this.addDiyDom
        },
        data: {
          key: {
            name: 'masterNodeName'
          },
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
            rootPId: "00000000000000000000000000000000"
          }
        },
        callback: {
          beforeClick: this.handleBeforeClick
        }
      },
      /** 差异总数 */
      diffTotal: 0,
      /** 当前位置 */
      curPosition: 0,
      /** 加载对象 */
      loader: undefined,
      /** masterFmeaId */
      masterFmeaId: undefined,
      /** 当前FmeaId */
      curFmeaId: undefined,
    };
  },
  mounted() {
    window.sync = this.sync;
  },
  methods: {
    /**
     * 初始化zTree
     * @param zTreeNodes
     */
    initTree(zTreeNodes) {
      let _that = this;
      _that.$nextTick(() => {
        zTreeNodes.forEach(item => {
          if ('01,99'.indexOf(item.struTypeCode) !== -1) {
            item['open'] = true;
          }
          if (item.optType !== 0) {
            _that.diffTotal += 1;
          }
        });
        // 初始化树
        $.fn.zTree.init($("#diffTree"), _that.setting, zTreeNodes);
        // 添加表头
        let li_head = ' <li class="head"><a>' +
            '<div class="divTd" style="width:40%">' + this.$t("globalComponents.masterFmeaDiff.master-fmea") + '</div>' +
            '<div class="divTd" style="width:10%">' + this.$t("globalComponents.masterFmeaDiff.operate") + '</div>' +
            '<div class="divTd" style="width:40%">' + this.$t("globalComponents.masterFmeaDiff.current-fmea") + '</div>' +
            '<div class="divTd" style="width:10%">' + this.$t("globalComponents.masterFmeaDiff.status") + '</div>' +
            '</a></li>';
        let rows = $("#diffTree").find('li');
        if (rows.length > 0) {
          rows.eq(0).before(li_head);
        } else {
          $("#diffTree").append(li_head);
          $("#diffTree").append('<li></li>');
        }
      });
    },
    /**
     * 差异定位
     * @param opt -1 上 1下
     */
    diffPosition(opt) {
      let treeObj = $.fn.zTree.getZTreeObj('diffTree');
      let nodes = treeObj.getNodesByFilter(node => {
        return node.optType !== 0;
      });
      if (nodes.length > 0) {
        let len = nodes.length;
        let curPosition = this.curPosition + opt;
        let curIndex = this.curPosition + opt - 1;
        if (curIndex === len) { // 循环到第一个
          curPosition = 1;
          curIndex = 0;
        } else if (curIndex < 0) { // 循环到最后一个
          curPosition = len;
          curIndex = len - 1;
        }
        let nextNode = nodes[curIndex];
        if (nextNode) {
          this.curPosition = curPosition;
          let treeNode = treeObj.getNodeByParam('id', nextNode.id);
          if (treeNode) {
            treeObj.selectNode(treeNode);
            if (curIndex === 0 && treeNode.pid === '00000000000000000000000000000000') {
              $('#diffTree_1').scrollTop(0);
            }
          }
        }
      }
    },
    /**
     * 用于捕获单击节点之前的事件回调函数，并且根据返回值确定是否允许单击操作
     * @param treeId
     * @param treeNode
     * @param clickFlag
     */
    handleBeforeClick(treeId, treeNode, clickFlag) {
      let treeObj = $.fn.zTree.getZTreeObj(treeId);
      let nodes = treeObj.getNodesByFilter(node => {
        return node.optType !== 0;
      });
      if (nodes.length > 0) {
        let curDiffIndex = nodes.findIndex((val) => {
          return val.id === treeNode.id;
        });
        this.curPosition = curDiffIndex + 1;
      }
    },
    /**
     * 自定义Dom
     * @param treeId
     * @param treeNode
     */
    addDiyDom(treeId, treeNode) {
      const spaceWidth = 15;
      const liObj = $("#" + treeNode.tId);
      const aObj = $("#" + treeNode.tId + "_a");
      const switchObj = $("#" + treeNode.tId + "_switch");
      const icoObj = $("#" + treeNode.tId + "_ico");
      const spanObj = $("#" + treeNode.tId + "_span");
      spanObj.attr('title', treeNode.title);
      aObj.append('<div class="divTd swich fnt" style="width:40%"></div>');
      const div = $(liObj).find('div').eq(0);
      switchObj.remove();
      spanObj.remove();
      icoObj.remove();
      div.append(switchObj);
      div.append(spanObj);
      const spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
      switchObj.before(spaceStr);
      let editStr = '';
      // 宽度需要和表头保持一致
      editStr += '<div class="divTd" style="width:10%" title="' + this.$t('globalComponents.masterFmeaDiff.sync') + '">' + this.opt(treeNode) + '</div>';
      editStr += '<div class="divTd" style="' + this.getStyle(treeNode) + '" title="' + treeNode.curNodeName + '">' + treeNode.curNodeName + '</div>';
      editStr += '<div class="divTd" style="width:10%">' + this.status(treeNode) + '</div>';
      aObj.append(editStr);
    },
    /**
     * 获取样式
     * @param treeNode
     * @returns {string}
     */
    getStyle(treeNode) {
      let style = 'width:40%;';
      switch (treeNode.optType) {
        case 1:
          style += 'color:#03B615';
          break;
        case 2:
          style += 'color:#D9001B;text-decoration:line-through;';
          break;
        case 3:
          style += 'color:#2DB7F5';
          break;
        default:
          break;
      }
      return style;
    },
    /**
     * 同步
     * @param id
     */
    sync(id) {
      let _that = this;
      _that.handleTableLoading(true);
      let treeObj = $.fn.zTree.getZTreeObj('diffTree');
      let treeNode = treeObj.getNodeByParam("id", id, null);
      if (!treeNode) return;
      let optType = treeNode.optType === 3 ? 3 : (treeNode.optType === 2 ? 1 : 2);
      _that.$api.nodeSync({
        sourceFmeaId: _that.masterFmeaId,
        targetFmeaId: _that.curFmeaId,
        struId: id,
        optType: optType,
        struTypeCode: treeNode.struTypeCode,
      }).then(res => {
        if (res.flag) {
          if (treeNode) {
            treeNode.optType = 0;
            let el = treeNode.tId + '_a';
            switch (optType) {
              case 1: // 新增
                treeNode.curNodeName = treeNode.masterNodeName;
                treeObj.updateNode(treeNode);
                $('#' + el + ' div.divTd i').remove(); // 操作元素删除
                $('#' + el + ' div.divTd').eq(2)
                    .css({
                      'color': '#000000',
                      'text-decoration': 'none',
                    })
                    .prop("title", treeNode.curNodeName)
                    .text(treeNode.curNodeName); // 当前Fmea
                $('#' + el + ' div.divTd .ant-tag').remove();// 状态元素删除
                break;
              case 2: // 删除
                treeObj.removeNode(treeNode);
                break;
              case 3: // 更新
                treeNode.curNodeName = treeNode.masterNodeName;
                treeObj.updateNode(treeNode);
                $('#' + el + ' div.divTd i').remove(); // 操作元素删除
                $('#' + el + ' div.divTd').eq(2)
                    .css('color', '#000000')
                    .prop("title", treeNode.curNodeName)
                    .text(treeNode.curNodeName); // 当前Fmea
                $('#' + el + ' div.divTd .ant-tag').remove();// 状态元素删除
                break;
            }
            _that.refreshTopStatus();
          }
        }
      }).finally(() => {
        _that.handleTableLoading(false);
      });
    },
    /**
     * 刷新顶部状态
     */
    refreshTopStatus() {
      let _that = this;
      let treeObj = $.fn.zTree.getZTreeObj('diffTree');
      let nodes = treeObj.getNodesByFilter(node => {
        return node.optType !== 0;
      });
      _that.diffTotal = nodes.length;
      _that.curPosition = 0;
    },
    /**
     * 处理表格Loading
     * @param flag
     */
    handleTableLoading(flag) {
      let _that = this;
      if (flag) {
        if (_that.loader) {
          _that.loader.hide();
        }
        _that.loader = _that.$loading.show({
          container: _that.$refs.diffTree,
          color: '#1890FF'
        }, {
          // 自定义加载动画组件
          default: _that.$createElement('ant-spin-dot')
        });
      } else {
        _that.loader.hide();
      }
    },
    /**
     * 操作
     * @param treeNode
     * @returns {string}
     */
    opt(treeNode) {
      let htmlStr = '';
      if (treeNode.optType !== 0) {
        // if (treeNode.children && treeNode.children.length > 0) {
        //   htmlStr += '<i onclick="sync(\'' + treeNode.id + '\')" aria-label="图标: double-right" class="anticon anticon-double-right"><svg viewBox="64 64 896 896" data-icon="double-right" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M533.2 492.3L277.9 166.1c-3-3.9-7.7-6.1-12.6-6.1H188c-6.7 0-10.4 7.7-6.3 12.9L447.1 512 181.7 851.1A7.98 7.98 0 0 0 188 864h77.3c4.9 0 9.6-2.3 12.6-6.1l255.3-326.1c9.1-11.7 9.1-27.9 0-39.5zm304 0L581.9 166.1c-3-3.9-7.7-6.1-12.6-6.1H492c-6.7 0-10.4 7.7-6.3 12.9L751.1 512 485.7 851.1A7.98 7.98 0 0 0 492 864h77.3c4.9 0 9.6-2.3 12.6-6.1l255.3-326.1c9.1-11.7 9.1-27.9 0-39.5z"></path></svg></i>';
        // } else {
        //   htmlStr += '<i onclick="sync(\'' + treeNode.id + '\')" aria-label="图标: right" class="anticon anticon-right"><svg viewBox="64 64 896 896" data-icon="right" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M765.7 486.8L314.9 134.7A7.97 7.97 0 0 0 302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 0 0 0-50.4z"></path></svg></i>';
        // }
        htmlStr += '<i onclick="sync(\'' + treeNode.id + '\')" aria-label="图标: right" class="anticon anticon-right"><svg viewBox="64 64 896 896" data-icon="right" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M765.7 486.8L314.9 134.7A7.97 7.97 0 0 0 302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 0 0 0-50.4z"></path></svg></i>';
      }
      return htmlStr;
    },
    /**
     * 状态
     * @param treeNode
     * @returns {string}
     */
    status(treeNode) {
      let htmlStr = '';
      switch (treeNode.optType) {
        case 1:
          htmlStr += '<span class="ant-tag ant-tag-has-color ck" style="background-color: #03B615;">' + this.$t("global-btn.insert") + '</span>';
          break;
        case 2:
          htmlStr += '<span class="ant-tag ant-tag-has-color ck" style="background-color: #D9001B;">' + this.$t("global-btn.delete") + '</span>';
          break;
        case 3:
          htmlStr += '<span class="ant-tag ant-tag-has-color ck" style="background-color: #2DB7F5;">' + this.$t("global-btn.update") + '</span>';
          break;
        default:
          break;
      }
      return htmlStr;
    },
    /**
     * 设置节点样式
     * @param treeId
     * @param treeNode
     */
    setNodeFontCss(treeId, treeNode) {
      let color = {};
      // 新增置灰
      if (treeNode.optType === 1) {
        return {'color': '#DDDDDD'};
      }
      switch (treeNode.struTypeCode) {
        case '02' :
          color = {'color': 'rgb(66, 167, 94)'};
          break;
        case '04' :
          color = {'color': '#5b9bd5'};
          break;
        case '05' :
          color = {'color': '#5b9bd5'};
          break;
        case '06' :
          color = {'color': 'rgb(200, 77, 60)'};
          break;
        default:
          break;
      }
      return color;
    }
  }
};

/**
 * 同步
 * @param id
 */
window.sync = function (id) {
  sync(id);
}
</script>

<style lang="less" scoped>

/deep/ .ztree * {
  font-size: 14px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
}

/deep/ .ztree {
  padding: 0;
  border-left: 1px solid #E3E3E3;
  border-right: 1px solid #E3E3E3;
  border-bottom: 1px solid #E3E3E3;
}

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

/deep/ .ztree li > a .node_name {
  margin-left: 5px;
}

/deep/ .ztree li a {
  vertical-align: middle;
  height: 32px;
  padding: 0px;
}

/deep/ .ztree li > a {
  width: 100%;
}

/deep/ .ztree li ul {
  padding-left: 0px
}

/deep/ .ztree div.divTd {
  height: 100%;
  line-height: 30px;
  border-top: 1px solid #E3E3E3;
  border-left: 1px solid #E3E3E3;
  text-align: center;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
}

/deep/ .ztree div.divTd:nth-of-type(2) {
  color: #000000;
}

/deep/ .ztree div.divTd:nth-of-type(3) {
  color: #000000;
}

/deep/ .ztree div.divTd:first-child {
  text-align: left;
  text-indent: 10px;
  border-left: none;
}

/deep/ .ztree .head {
  background: #f5f6f7;
  height: 54px;
}

/deep/ .ztree .head div.divTd {
  text-align: center;
  color: #393939;
  font-weight: bold;
  line-height: 54px;
  height: 54px;
}

/deep/ .ztree .ck {
  padding: 0 7px;
  font-size: 12px;
}

/deep/ li {
  background-color: #FFFFFF;
}

/deep/ .ztree li a.curSelectedNode {
  background-color: #FFFFFF;
  border: 2px dashed #1890FF;
  height: 32px;
}

/deep/ .ztree #diffTree_1 {
  height: 50vh;
  overflow: auto; /* 显示滚动条，根据内容决定是否显示 */
  /* 隐藏默认的滚动条样式 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/deep/ .ztree #diffTree_1::-webkit-scrollbar {
  display: none; /* Chrome, Safari, and Opera */
}

</style>
