<template>
  <div class="root">
    <div id="headPanel">
      <!-- <span class="logo">G6 入门教程 - 脑图</span> -->
      <i class="gb-toggle-btn" />
    </div>
    <div class="crumb-nav"  v-if="activeMenu + 'TITLE'">
      <template v-for="(nav, index) in crumbNavs">
        {{ index > 0 ? '>' : '' }}
        <span :key="nav.id" class="nav-text" @click="changeNode(nav)">{{ nav.label }}</span>
      </template>
    </div>
    <div class="text-nav">
      <span>{{ chart.option.title.text }}</span>
    </div>
    <!-- canvas 挂载节点 -->
    <div id="graph" />
    <!-- 输入框 -->
    <input v-show="showInput" id="input-controller" ref="inputController" v-model="inputValue" :style="{
        top: `${input.y}px`,
        left: `${input.x}px`,
      }" type="text" @blur="inputBlur">
    <el-dialog title="文件预览" :visible.sync="dialogVisible" destroy-on-close width="90%" top="6vh" height="90%">
      <el-button size="small" type="primary" icon="el-icon-download" v-privilege="activeMenu + 'DOWNLOAD'"
        @click="downloadFile(chart.fileData)" :loading="loading" style="position: absolute; right: 100px; top: 20px;">
        点击保存
      </el-button>
      <iframe :src="previewUrl" width="100%" :height="singleTableHeight"></iframe>
    </el-dialog>
  </div>
</template>

<script>
  import G6 from 'G6-4.3.11';
  import registerEdge from './register-edge';
  import registerNode from './register-node';
  import formulaEditor from '~/components/zg/formulaEditor.vue';
  import {
    zCheckNumber1
  } from '~/utils/validator.js';
  import {
    formatDate
  } from '@/utils/util.js';
  import store from '@/store/index.js';

  export default {
    name: 'root',
    data() {
      return {
        multipleSelection: [],
        tableFormDataObj: {},
        form: {
          imgSavePath: '',
        },
        filterForm: {
          show: true,
          data: {
            uploadFileid: '',
            securityTypeid: '',
            securityTag: '',
            isprimary: '',
            version: formatDate(new Date(), 'yyyyMM00'),
            fileName: '',
            pattern: 'table'
          },
          rules: {},
          file: ''
        },
        listTopicTree: {
          show: true,
          loading: false,
          data: [],
          defaultProps: {
            children: 'children',
            label: 'securityName'
          }
        },
        pageNum: 1,
        pageSize: 20,
        total: 0,
        singleTableHeight: '720px',
        tableData: [],
        nameObj: {
          uploadFile: {
            obj: {},
            arr: []
          },
          securityType: {
            obj: {},
            arr: []
          },
          unitid: {
            obj: {},
            arr: []
          },
          roleList: {
            obj: {},
            arr: []
          }, // 角色信息
          securityTag: {
            obj: {},
            arr: []
          },
          pattern: {
            obj: {
              'graphical': '图例',
              'table': '表格'
            },
            arr: [{
                id: 'graphical',
                name: '图例'
              },
              {
                id: 'table',
                name: '表格'
              }
            ]
          }
        },
        loading: false,
        tableLoading: false,
        dialog: {
          editorBox: {
            show: false,
            fileType: '',
            form: {
              default: {
                workprocid: ''
              },
              data: {
                itemid: '',
                productid: '',
                workprocid: '',
                isprimary: '0',
                unitid: '',
                seqno: '',
                code: '',
                fileType: ''
              },
              rules: {
                productid: [{
                  required: true,
                  message: '该项不能为空',
                  trigger: 'change'
                }],
                workprocid: [{
                  required: true,
                  message: '该项不能为空',
                  trigger: 'change'
                }],
                seqno: [{
                  validator: zCheckNumber1,
                  trigger: 'change'
                }]
              }
            }
          },
          equationEditing: {
            show: false,
            form: {
              data: {
                clock: '',
                code: ''
              }
            }
          }
        },
        store,
        userInfo: {}, // 用户信息
        qrRole: [],
        userRoles: [],
        dialogVisible: false,
        previewUrl: '',
        chart: {
          height: '1024px',
          show: false,
          fileData: {
            fileName: '',
            fileUrl: ''
          },
          option: {
            title: {
              text: '典型事故应急"四步"管控体系'
            },
            tooltip: {
              trigger: 'item',
              triggerOn: 'mousemove'
            },
            toolbox: {
              feature: {
                saveAsImage: {}
              }
            },
            series: [{
              type: 'tree',
              data: [],
              top: '2%',
              left: '25%',
              bottom: '1%',
              right: '20%',
              symbolSize: 8,
              nodePadding: 50,
              label: {
                position: 'left',
                verticalAlign: 'bottom',
                align: 'right',
                fontSize: 14
              },
              leaves: {
                label: {
                  position: 'right',
                  verticalAlign: 'middle',
                  align: 'left'
                }
              },
              emphasis: {
                focus: 'descendant'
              },
              initialTreeDepth: 2,
              expandAndCollapse: true,
              animationDuration: 550,
              animationDurationUpdate: 750,
              roam: true
            }]
          }
        },
        graph: null,
        showInput: false,
        inputValue: '',
        activeMenu: '',
        input: {
          x: 0,
          y: 0,
        },
        currentNode: {
          id: null,
        },
        crumbNavs: [],
      };
    },
    created() {
      this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    mounted() {
      let that = this;
      that.getFileTreeData();
    },
    beforeDestroy() {
      this.graph.destroy();
    },
    methods: {
      createGraphic() {
        const vm = this;

        registerEdge(G6);
        registerNode(G6);

        const menu = new G6.Menu({
          offsetY: -20,
          itemTypes: ['node'],
          getContent(e) {
            return `
       <p class="menu-item" command="edit-node">编辑文本</p>
       <p class="menu-item" command="delete-node">删除节点</p>
     `;
          },
          handleMenuClick(target, item) {
            const command = target.getAttribute('command');

            switch (command) {
              case 'edit-node':
                vm.editNode(item);
                break;
              case 'delete-node':
                vm.deleteNode(item);
                break;
            }
          },
        });
        const graph = new G6.TreeGraph({
          container: document.getElementById('graph'),
          width: window.innerWidth - 10,
          height: window.innerHeight - 10,
          defaultNode: {
            type: 'tree-node',
            style: {
              width: 100,
              height: 30,
              radius: 4,
              fill: '#ffffff00',
              stroke: '#999',
            },
            labelCfg: {
              style: {
                fontSize: 14,
              },
            },
          },
          defaultEdge: {
            type: 'right-tree',
          },
          layout: {
            type: 'mindmap',
            direction: 'H',
            getHeight: function getHeight() {
              return 16;
            },
            getWidth: function getWidth() {
              return 16;
            },
            getVGap: function getVGap() {
              return 20;
            },
            getHGap: function getHGap() {
              return 120;
            },
          },
          modes: {
            default: [
              'drag-canvas',
              'zoom-canvas',
              'drag-node',
              // {
              //   type: 'collapse-expand',
              //   onChange(item, collapsed) {
              //     const data = item.get('model');
              //     data.collapsed = collapsed;
              //     return true;
              //   },
              // },
            ],
          },
          // plugins: [menu],
          fitView: true,
          fitViewPadding: 80,
        });
        // graph.data(vm.chart.option.series[0].data[0]);
        // gragh.render();
        graph.read({
          ...vm.chart.option.series[0].data[0]
        });
        graph.fitView(80);
        this.graph = graph;
        this.bindEvents();
      },
      /*
       * 1:        1
       * 1-1:      1     1-1
       * 1-1-1:    1     1-1     1-1-1
       * 1-1-1-1:  1     1-1     1-1-1      1-1-1-1
       */
      getParentNodes(node, id, deep = 1) {
        if (id.substring(0, 1) === '1' && deep === 1) {
          this.crumbNavs.push(node);
        }
        if (id.length > 1) {
          const $id = id.substring(0, deep * 2 + 1);
          const $node = node.children.find(item => item.id === $id);

          if ($node) {
            this.crumbNavs.push($node);

            if ($node.children && $node.children.length > 0) {
              this.getParentNodes($node, id, deep + 1);
            }
          }
        }
      },
      bindEvents() {
        this.graph.on('node:click', e => {
          const model = e.item.getModel();

          if (e.target.cfg.name === 'node-icon-text') {
            /* 展开按钮的事件 */
            model.collapsed = !model.collapsed;
            this.graph.updateItem(e.item, model);
            this.graph.layout();
            this.graph.fitView(80);;
          } else {
            if (model.value) {
              let args = {
                fileName: model.label,
                fileUrl: model.value
              } //当前节点及其子节点的值
              this.preview(args);
            } else {
              if(model.id.length === 1) {
                // this.chart.option.title.text = '安泰控股集团';
              } else {
                // this.chart.option.title.text = model.label;
              }
              /* 节点点击事件 */
              // 记录当前节点 id
              model.collapsed = false;
              this.currentNode.id = model.id;
              this.crumbNavs = [];
              // 查找所有的节点路径
              this.getParentNodes(this.chart.option.series[0].data[0], model.id);
              this.graph.changeData(JSON.parse(JSON.stringify(model)));
              this.graph.fitView(80);
            }
          }
          e.item.toFront();
        });
      },
      inputBlur() {
        this.showInput = false;

        const item = this.graph.findById(this.currentNode.id);
        const model = item.getModel();

        model.label = this.inputValue;
        this.graph.updateItem(item, model);
      },
      // 编辑节点
      editNode(item) {
        const model = item.getModel();
        const {
          cacheCanvasBBox
        } = item.get('group').cfg;

        this.showInput = true;
        this.inputValue = model.label;
        this.currentNode.id = model.id;
        this.input.x = cacheCanvasBBox.x;
        this.input.y = cacheCanvasBBox.y;
        this.$nextTick(() => {
          this.$refs.inputController.focus();
        });
      },
      deleteNode(item) {
        const id = item.get('id');

        if (id.length > 1) {
          const parentId = id.substring(0, id.length - 2);
          const parent = this.graph.findById(parentId);

          parent.toFront();
        }
        this.graph.removeChild(id);

        if (id.length > 1) {
          const parentId = id.substring(0, id.length - 2);
          const parent = this.graph.findById(parentId);
          const model = parent.get('model');

          if (model.children.length === 0) {
            const group = parent.get('group');
            const {
              children
            } = group.cfg;

            const icon = children.find(child => child.name === 'node-icon');
            const iconText = children.find(child => child.name === 'node-icon-text');

            if (icon) {
              icon.remove();
              iconText.remove();
            }
          }
        }
      },
      changeNode(node) {
        if(node.id.length === 1) {
          // this.chart.option.title.text = '安泰控股集团';
        } else {
          // this.chart.option.title.text = node.label;
        }
        this.graph.changeData(JSON.parse(JSON.stringify(node)));
        this.graph.fitView(80);;
      },
      getFileTreeData() {
        let that = this,
          params = {
            fileName: that.filterForm.data.fileName,
            type: that.filterForm.data.securityTypeid,
            fileType: that.filterForm.data.securityTag.toString()
          };
        that.tableLoading = true;
        let url = 'pass/ems/v1/uploadfiles/getFileTree/?securityInfo=' + that.qrRole;
        that.axios.get(url, {
            params: params
          })
          .then(function(res) {
            if (res.code === '0') {
              let arr = [];
              // that.chart.height = res.data.length * 100 + 'px';
              arr = that.treeDataUtil(res.data, '');
              // arr = that.getParentNodes(res.data, 1)
              arr[0].labelCfg = {
                style: {
                  fontSize: 30,
                },
              };
              arr[0].id = '1';
              arr[0].collapsed = false,
              that.chart.option.series[0].data = arr;
              // that.setGraphical();
              that.createGraphic();
            } else {
              that.$message.error(res.message);
            }
            that.tableLoading = false;
          }).catch(function() {
            that.tableLoading = false;
          });
      },
      treeDataUtil(treeData, id) {
        let that = this;
        let data = [];
        let children = [];
        let children1 = [];
        let i = 0;
        let k = 0;
        let j = 0;
        let g = 0;
        let name = '';
        for (let item of treeData) {
          i++;
          if (item.fileName === null) {
            g++;
            if (item.children !== null) {
              if (id == '') {
                children = that.treeDataUtil(item.children, i);
              } else {
                children = that.treeDataUtil(item.children, id + '-' + g);
              }
            };
            data.push({
              collapsed: true,
              id: id + '-' + g,
              nodeType: 'node',
              label: item.createMan,
              children: children,
            });
            children = [];
          } else {
            if (name === '' || i === 1) {
              name = item.createMan;
            } else if (name !== item.createMan) {
              g++;
              for (let ch of children1) {
                ch.id = id + '-' + g + ch.id.substring(ch.id.lastIndexOf("-"))
              }
              data.push({
                collapsed: true,
                id: id + '-' + g,
                nodeType: 'node',
                isCollapsed: true,
                label: name,
                children: children1,
              });
              j = 0;
              children1 = [];
              name = item.createMan;
            }
            j++;
            children1.push({
              id: id + '-' + g + '-' + j,
              label: item.fileName,
              value: item.fileUrl,
              children: [],
            });
          }
          if (i === treeData.length && children1.length !== 0) {
            g++;
            for (let ch of children1) {
              ch.id = id + '-' + g + ch.id.substring(ch.id.lastIndexOf("-"))
            }
            data.push({
              collapsed: true,
              id: id + '-' + g,
              nodeType: 'node',
              isCollapsed: true,
              label: name,
              children: children1,
            });
          }
        }
        return data;
      },
      downloadFile(data) {
        let that = this;
        let SubmitData = {
          fileName: data.fileName,
          fileUrl: data.fileUrl
        };
        // 不带token访问方式，留底后端修改shiroconfig.java,application.properties
        //     let url = '/zhongsteel.pass.web/pass/ems/v1/uploadfiles/downloadFile/?fileName=' + that.tableFormDataObj[key].fileName + '&fileUrl=' + that.tableFormDataObj[key].fileUrl;
        // const xhr = new XMLHttpRequest();
        // xhr.open('GET', url, true);
        // xhr.responseType = 'blob';
        // xhr.onload = () => {
        //     if (xhr.status === 200) {
        //         var fileName = that.tableFormDataObj[key].fileName;
        //         // 获取文件blob数据并保存
        //         that.saveAs(xhr.response, fileName);
        //     }
        // };
        // xhr.send();
        that.loading = true;
        let urla = 'pass/ems/v1/uploadfiles/downloadFile/';
        that.axios.get(urla, {
          params: SubmitData,
          responseType: 'blob'
        }).then(function(res) {
          that.saveAs(res, data.fileName);
          that.$message({
            message: '下载成功',
            type: 'success'
          });
          that.loading = false;
        }).catch(function() {
          that.$message.error('下载失败');
          that.loading = false;
        })
      },
      // js实现文件下载而不直接打开
      saveAs(data, fileName) {
        this.loading = true;
        let urlObject = window.URL || window.webkitURL || window;
        // 将二进制流转为blob
        let exportBlob = new Blob([data]);
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(exportBlob, decodeURI(fileName));
          this.loading = false;
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          let blobURL = urlObject.createObjectURL(exportBlob);
          let saveLink = document.createElement('a');
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof saveLink.download === 'undefined') {
            saveLink.setAttribute('target', '_blank');
          } else {
            saveLink.download = fileName;
          }
          // 创建新的URL并指向File对象或者Blob对象的地址
          saveLink.href = blobURL;
          saveLink.click();
          // 释放blob URL地址
          urlObject.revokeObjectURL(exportBlob);
          this.loading = false;
          // let blob = new Blob([data])
          // let fileURL = urlObject.createObjectURL(blob);
          // 下载代码
          // let downEle = document.createElement('a')
          // let fname = `download` //下载文件的名字
          // downEle.href = fileURL
          // downEle.setAttribute('download', fname)
          // document.body.appendChild(downEle)
          // downEle.click()
          // window.open(fileURL);
        }
      },
      preview(data) {
        let that = this;
        that.loading = true;
        that.chart.fileData = data;
        let SubmitData = {
          fileName: data.fileName,
          fileUrl: data.fileUrl
        };
        let urla = 'pass/ems/v1/uploadfiles/getfile/';
        let type = 'text/html';
        let responseType = 'application/json';
        let fileExtension = data.fileName.substring(data.fileName.lastIndexOf('.') + 1);
        if (fileExtension === 'pdf') {
          urla = 'pass/ems/v1/uploadfiles/downloadFile/';
          type = 'application/pdf';
          responseType = 'blob';
        }
        that.tableLoading = true;
        that.axios.get(urla, {
          params: SubmitData,
          responseType: responseType
        }).then(function(res) {
          console.log('111');
          let urlObject = window.URL || window.webkitURL || window;
          // 将二进制流转为blob
          let blob = new Blob([res], {
            type: type
          });
          if (fileExtension !== 'pdf') {
            blob = new Blob([res.data], {
              type: type
            });
          }
          // if (typeof window.navigator.msSaveBlob !== 'undefined') {
          //   // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          //   window.navigator.msSaveBlob(blob, decodeURI(fileName))
          // } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          let blobURL = urlObject.createObjectURL(blob);
          that.dialogVisible = true;
          that.previewUrl = blobURL;
          that.tableLoading = false;
          that.loading = false;
          // 'https://file.keking.cn/onlinePreview?url=' + encodeURIComponent(blobURL)
          // http://view.officeapps.live.com/op/view.aspx?src' + blobURL;
          // 创建a标签，用于跳转至下载链接
          // let tempLink = document.createElement('a')
          // tempLink.style.display = 'none'
          // tempLink.href = blobURL;
          // tempLink.setAttribute('download', decodeURI(fileName))
          // 兼容：某些浏览器不支持HTML5的download属性
          // if (typeof tempLink.download === 'undefined') {
          //   tempLink.setAttribute('target', '_blank')
          // }
          // // 挂载a标签
          // document.body.appendChild(tempLink)
          // tempLink.click()
          // // 销毁a标签
          // document.body.removeChild(tempLink)
          // 释放blob URL地址
          // urlObject.revokeObjectURL(blobURL);
          setTimeout(() => {
            urlObject.revokeObjectURL(blobURL);
          }, 1000)
        }).catch(function() {
          that.tableLoading = false;
          that.$message.error('预览失败');
          that.loading = false;
        })
      },
    },
  };
</script>

<style lang="scss">
  .root {
    background: url(../../../../assets/img/img/filebg.png) center bottom no-repeat;
    background-size: 100% 100%;
  }

  .crumb-nav {
    position: absolute;
    top: 20px;
    left: 40px;
    background: #73bf8f;
    border-radius: 4px;
    color: #fff;
  }

  .nav-text {
    display: inline-block;
    height: 36px;
    line-height: 36px;
    margin: 0 10px;
    cursor: pointer;
  }

  .g6-component-contextmenu {
    width: 100px;
    padding: 6px 0;
    cursor: pointer;

    .menu-item {
      padding: 0 10px;
      line-height: 26px;

      &:hover {
        background: #f0f0f0;
      }
    }
  }

  #input-controller {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 12;
    width: 100px;
    height: 30px;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding-left: 6px;
    font-size: 14px;
  }
  .text-nav {
    position: absolute;
    top: 20px;
    left: 36%;
    font-size: 40px;
    // background: #73bf8f;
    // border-radius: 4px;
    color: #000000;
  }
</style>
