<template>
  <a-modal
      destroy-on-close
      class="structureNetDialog"
      :visible.sync="dialogFormVisible"
      :maskClosable="true"
      @cancel="close"
      width="100%"
      :footer="false">
    <div slot="title" class="funcNetTitle">
      {{ $t('functional-analysis.top-modal.structure-net') }}
    </div>
    <div>
      <a-form-model>
        <a-form-model-item>
          <span class="ml10">
            <label>
              {{ $t('functional-analysis.top-modal.show-function') }}
            </label>
            <a-switch
                class="ml5"
                size="small"
                :defaultChecked="false"
                @change="functionSwitchChange"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
          </span>
          <span class="ml10">
            <label>
              {{ $t('functional-analysis.top-modal.show-failure') }}
            </label>
            <a-switch
                class="ml5"
                size="small"
                :defaultChecked="false"
                @change="faultSwitchChange"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
          </span>
          <span class="ml10">
            <a-tooltip :title="$t('functional-analysis.net.download')">
              <a-button type="primary" size="small" @click="downloadHtml()">
                  <i class="iconfont iconxiazai2"/>
              </a-button>
            </a-tooltip>
          </span>
          <!-- 导出图片 -->
          <span class="ml10">
            <a-tooltip :title="$t('global-btn.export.picture')">
              <a-button type="primary" size="small" @click="downloadHtmlImage()">
                  <i class="iconfont iconxiazai"/>
              </a-button>
            </a-tooltip>
          </span>
        </a-form-model-item>
      </a-form-model>
      <template>
        <a-spin
            :tip="spinTip"
            :spinning="structureNetLoading">
          <div class="pr net-container" style="height: calc(100vh - 160px)">
            <table id="structure-net-tree" ref="structureNetTree" class="ml10 table htree"></table>
          </div>
        </a-spin>
      </template>
    </div>
  </a-modal>
</template>
<script>

import {buildNet, dragZoom} from './components/index';
import {downloadHtml} from '@/utils/download-html';
import html2canvas from 'html2canvas';

/** 节点颜色 */
let nodeColor = {
  "02": {'color': 'rgb(66, 167, 94)'},
  "04": {'color': '#5b9bd5'},
  "05": {'color': '#5b9bd5'},
  "06": {'color': 'rgb(200, 77, 60)'},
};

export default {
  name: "StructureNetModal",
  props: {
    showStructureNetModal: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    showStructureNetModal(val) {
      this.dialogFormVisible = val;
    },
  },
  data() {
    return {
      /** 模态框状态 */
      dialogFormVisible: false,
      /** 结构网加载中状态 */
      structureNetLoading: false,
      /** 自定义Loading描述文案 */
      // spinTip: "加载中...",
      spinTip: "",
      /** 功能开关 */
      functionSwitch: false,
      /** 失效开关 */
      faultSwitch: false,
    };
  },
  mounted() {
    this.forbiddenRightClick();
  },
  methods: {
    /**
     * 下载Html
     */
    downloadHtml() {
      const html = this.$refs.structureNetTree.outerHTML;
      downloadHtml(html, this.$t('functional-analysis.top-modal.structure-net'));
    },
    /**
     * 导出图片
     */
    downloadHtmlImage() {
      // 获取id为'structure-net-tree'的元素
      const element = document.getElementById('structure-net-tree');
      // 获取类名为'htree'的ul元素的宽度，除目标节点外的所有子节点总长度
      var children = document.querySelector('ul.htree');
      console.log(children.offsetWidth, 'chil');
      var childrenWidth = children ? children.offsetWidth : 0;
      // 使用html2canvas将元素转换为canvas
      html2canvas(element,
        {
          // 设置canvas的窗口高度为浏览器窗口高度
          windowHeight: $(window).height(),
          // 设置canvas的窗口宽度为目标元素宽度（100）加上childrenWidth
          windowWidth: 100 + childrenWidth
        }).then(canvas => {
          // 将canvas转换为图片URL
          const imgData = canvas.toDataURL('image/png');
          // 创建一个隐藏的链接元素
          const link = document.createElement('a');
          link.href = imgData;
          link.download = 'structure.png';
          link.style.display = 'none'; // 隐藏链接
          // 将链接添加到DOM中
          document.body.appendChild(link);
          // 触发点击事件
          link.click();
          // 移除链接
          document.body.removeChild(link);
        });
    },
    /**
     * 初始化结构网数据
     */
    initStructureNetData() {
      let _that = this;
      _that.structureNetLoading = true;
      _that.$api.getStruNetData({
        fmeaId: _that.$store.getters.rfmeaId
      }).then(res => {
        if (res.flag) {
          _that.handleStructureNetData(res.data);
        }
      }).finally(() => {
        _that.structureNetLoading = false;
      });
    },
    /**
     * 处理结构网数据
     * @param resData 响应数据
     */
    handleStructureNetData(resData) {
      let id = resData.rootNodeJson.struId;
      let nodeData = {};
      nodeData[resData.rootNodeJson.struId] = JSON.parse(resData.rootNodeJson.nodeJson);
      let netData = [];
      resData.nodes.forEach(node => {
        if (node.parentStruId !== '00000000000000000000000000000000') {
          netData.push([node.parentStruId, node.struId]);
          nodeData[node.struId] = JSON.parse(node.nodeJson);
        }
      });
      netData = $.unique(netData);
      this.handleStructureNet(id, nodeData, netData);
    },
    /**
     * 处理结构网
     * @param id 根节点ID
     * @param nodeData 节点数据
     * @param netData 网数据
     */
    handleStructureNet(id, nodeData, netData) {
      // 初期化网
      buildNet('table#structure-net-tree', {target: id, nodes: nodeData, net: netData}, {
        htmlNullLeft: '',
        htmlNullRight: '',
        cssCenter: '',
        cssRight: '',
        editable: false,
        buildNodeHtmlFunc: function (o) {
          let scode = '';
          if (o.struCode) scode = '(' + o.struCode + ')';
          let content = '<p style="line-height: 20px; color: #111111; white-space: normal'
              + '" title="' + o.struName + scode + '">'
              + o.struName + scode
              + '</p>';
          if (!o.funList) return content;
          for (let i = 0, len = o.funList.length; i < len; i++) {
            // 功能
            content = content + '<small class="function" style="white-space: normal;'
                + 'line-height: 20px; color: '
                + nodeColor[o.funList[i].struTypeCode]["color"]
                + '" title="' + o.funList[i].struName + '">'
                + o.funList[i].struName
                + '</small>';
            // 失效
            if (!o.funList[i].failList) continue;
            for (let j = 0, len = o.funList[i].failList.length; j < len; j++) {
              if (o.funList[i].failList[j].struTypeCode === '06') {
                content = content + '<small class="fault" style="white-space: normal;' +
                    'line-height: 20px; margin-left: 10px; color: '
                    + nodeColor[o.funList[i].failList[j].struTypeCode]["color"]
                    + '" title="' + o.funList[i].failList[j].struName + '">'
                    + o.funList[i].failList[j].struName
                    + '</small>';
              } else if (o.funList[i].failList[j].struTypeCode === '05') {
                content = content + '<small class="reuqire" style="white-space: normal;' +
                    'line-height: 20px; margin-left: 10px; color: '
                    + nodeColor[o.funList[i].failList[j].struTypeCode]["color"]
                    + '" title="' + o.funList[i].failList[j].struName + '">'
                    + o.funList[i].failList[j].struName
                    + '</small>';
              }
            }
          }
          return content;
        }
      });
      // 元素拖动、缩放
      dragZoom(document.querySelector('#structure-net-tree'));
      // 默认隐藏功能
      this.functionSwitchChange(false);
      // 默认隐藏失效
      this.faultSwitchChange(false);
    },
    /**
     * 功能开关改变事件
     * @param checked
     */
    functionSwitchChange(checked) {
      this.functionSwitch = checked
      if (checked) {
        $('.function').show();
        $('.reuqire').show();
      } else if (this.faultSwitch) {
        $('.function').hide();
      } else {
        $('.function').hide();
        $('.reuqire').hide();
      }
    },
    /**
     * 失效开关改变事件
     * @param checked
     */
    faultSwitchChange(checked) {
      this.faultSwitch = checked
      if (checked) {
        $('.fault').show();
        $('.reuqire').show();
      } else if (this.functionSwitch) {
        $('.fault').hide();
      } else {
        $('.fault').hide();
        $('.reuqire').hide();
      }
    },
    /**
     * 关闭
     */
    close() {
      this.$emit("closeStructureNetModal");
    },
    /**
     * 禁用浏览器右键菜单
     */
    forbiddenRightClick() {
      document.body.oncontextmenu = function () {
        return false;
      };
    }
  },
  destroyed() {
    this.close();
  }
};
</script>
<style lang="less" scoped>

// 设置model 全屏
/deep/ .ant-modal {
  top: 0 !important;
}

// 设置model 全屏
/deep/ .ant-modal-content {
  height: calc(100vh);
}

// 不加上弹窗就会有滚动条;
/deep/ .ant-modal-wrap {
  overflow: hidden !important
}

/deep/ .ant-form-item {
  margin-bottom: 10px;
}
</style>
