<template>
  <div class="root">
    <div id="headPanel">
      <!-- <span class="logo">G6 入门教程 - 脑图</span> -->
      <i class="gb-toggle-btn" />
    </div>
    <div class="crumb-nav">
      <template v-for="(nav, index) in crumbNavs">
        {{ index > 0 ? '>' : '' }}
        <span :key="nav.id" class="nav-text" @click="changeNode(nav)">{{ nav.label }}</span>
      </template>
    </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">
  </div>
</template>

<script>
  import G6 from '@antv/g6';
  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: {},
        activeMenu: '',
        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() {
        let that = this;
        var tree = new G6.Tree({
          id: 'graph', // 容器ID
          width: window.innerWidth,
          height: window.innerHeight, // 画布高
          fitView: 'autoZoom', // 自动缩放
          layoutCfg: {
            direction: 'H', // 方向（LR/RL/H/TB/BT/V）
            getHGap: function( /* d */ ) { // 横向间距
              return 100;
            },
            getVGap: function( /* d */ ) { // 竖向间距
              return 10;
            },
          },
        });
        var canvas = new G6.Canvas({
            containerId: 'graph',
            width: 600,
            height: 600
          });
        canvas.addShape('text', {
            attrs: {
              x: 150,
              y: 150,
              fontFamily: 'PingFang SC',
              text: '文本文本',
              fontSize: 90,
              stroke: 'black'
            },
            });
            canvas.draw();
        tree.source(that.chart.option.series[0].data[0]);
        tree.node()
          .label(function(obj) {
            return obj.name;
          })
          .style({
            fillOpacity: 1
          })
          // smooth 曲线
        tree.edge().shape('VH');
        tree.render();
      //   // 悬浮事件
      // tree.on('itemmouseenter', function(ev){
      //    let item = ev.item;
      //    tree.update(item, {
      //      color: 'red'
      //    });
      // tree.refresh();
      // });
      // tree.on('itemmouseleave', function(ev){
      //      let item = ev.item;
      //      tree.update(item, {
      //        color: null,
      //        fontSize: 8
      //      });
      //      tree.refresh();
      // });
      tree.on('itemclick', function(ev){
              alert("击中" + ev.item.get('model').value + "!");
      });
        that.graph = tree;
      },
      /*
       * 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) {
              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();
          } else {
            /* 节点点击事件 */
            // 记录当前节点 id
            this.currentNode.id = model.id;
            this.crumbNavs = [];
            // 查找所有的节点路径
            this.getParentNodes(data, model.id);
            this.graph.changeData(JSON.parse(JSON.stringify(model)));
          }
          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 + 40;
        this.input.y = cacheCanvasBBox.y + 40;
        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) {
        this.graph.changeData(JSON.parse(JSON.stringify(node)));
      },
      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)
              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) {
        let that = this;
        let data = [];
        let children = [];
        let children1 = [];
        let i = 0;
        let name = '';
        for (let item of treeData) {
          i++;
          if (item.fileName === null) {
            if (item.children !== null) {
              children = that.treeDataUtil(item.children);
            };
            data.push({
              nodeType: 'node',
              name: item.createMan,
              children: children,
            });
            children = [];
          } else {
            if(name === '' || i === 1){
              name = item.createMan;
            } else if (name !== item.createMan) {
              data.push({
                nodeType: 'node',
                isCollapsed: true,
                name: name,
                children: children1,
              });
              children1 = [];
              name = item.createMan;
            }
            children1.push({
              itemType: 'edge',
              name: item.fileName,
              value: item.fileUrl,
              children: [],
            });
          }
          if ( i=== treeData.length && children1.length !== 0 ) {
            data.push({
              nodeType: 'node',
              isCollapsed: true,
              name: name,
              children: children1,
            });
          }
        }
        return data;
      },
    },
  };
</script>

<style lang="scss">
  .crumb-nav {
    position: absolute;
    top: 50px;
    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;
  }
</style>
