<template>
  <div style="width:100%;height:100%" class="relative-position align-view">
    <div
      v-loading="g_loading"
      style="width:100%;height:100%;background:#F5F5F5"
    >
      <SeeksRelationGraph
        ref="seeksRelationGraph"
        :options="graphOptions"
        :on-node-expand="onNodeExpand"
        :on-node-collapse="onNodeCollapse"
      >
      </SeeksRelationGraph>
    </div>
  </div>
</template>

<script>
import {
  queryUserOKRAlignView,
  queryUserOKRNextAlignView
} from "../../api/okr/work";
import SeeksRelationGraph from "../../components/relation/index";
export default {
  components: { SeeksRelationGraph },
  data() {
    return {
      g_loading: true,
      graphOptions: {
        debug: true,
        backgrounImage: "http://ai-mark.cn/images/ai-mark-desc.png",
        backgrounImageNoRepeat: true,
        layouts: [
          {
            label: "中心",
            layoutName: "tree",
            layoutClassName: "seeks-layout-center",
            defaultJunctionPoint: "border",
            defaultNodeShape: 0,
            defaultLineShape: 1,
            from: "left",
            min_per_width: "400",
            max_per_width: "400",
            min_per_height: "80",
            max_per_height: "100"
          }
        ],
        defaultLineMarker: {
          'markerWidth': 12,
          'markerHeight': 12,
          'refX': 6,
          'refY': 6,
          'data': 'M2,2 L10,6 L2,10 L6,6 L2,2'
        },
        defaultExpandHolderPosition: "right",
        defaultNodeShape: 1,
        defaultNodeWidth: "334",
        defaultLineShape: 4,
        defaultJunctionPoint: "lr",
        defaultNodeBorderWidth: 0,
        defaultLineColor: "#cecece",
        defaultNodeColor: "rgba(255,255,255,1)",
        defaultNodeFontColor: "rgba(0,0,0,1)"
      },
      proid: 51,
      rootObjList: [],
      graph_json_data: {
        rootId: "0",
        nodes: [],
        links: []
      }
    };
  },
  created() {},
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      queryUserOKRAlignView({
        PeriodId: this.proid
      }).then(r => {
        this.rootObjList = r.Data;
        this.genernalNodes();
      });
    },
    genernalNodes() {
      let node = {
        id: "0",
        disableDrag: true,
        text: "111"
      };
      this.graph_json_data.nodes.push(node);
      this.rootObjList.forEach((x,i) => {
        let q=`main-${this.randomString()}`
        this.graph_json_data.nodes.push(this.formatNode(x, q));
        this.graph_json_data.links.push(
          this.formatLink("0", `${q}_${x.Id}`, true)
        );
        x.ChildList.forEach(y => {
          let qy=`child-${this.randomString()}`
          this.graph_json_data.nodes.push(this.formatNode(y, qy));
          this.graph_json_data.links.push(
            this.formatLink(`${q}_${x.Id}`, `${qy}_${y.Id}`, false)
          );
        });
        x.ParentList.forEach(z => {
          let zy=`parent-${this.randomString()}`
          this.graph_json_data.nodes.push(this.formatNode(z, zy,true));
          this.graph_json_data.links.push(
            this.formatLink(`${zy}_${z.Id}`, `${q}_${x.Id}`, false)
          );
        });
      });
      this.g_loading = false;
      this.$refs.seeksRelationGraph.setJsonData(
        this.graph_json_data,
        seeksRGGraph => {
          var level_1_nodes = seeksRGGraph.getNodeById(
            this.graph_json_data.rootId
          ).lot.childs;
          level_1_nodes.forEach(thisLevel1Node => {
            this.applyCollapseStyle2Node(thisLevel1Node);
          });
          this.$refs.seeksRelationGraph.refresh();
        }
      );
    },
    randomString() {
      let length=6
      var str =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var result = "";
      for (var i = length; i > 0; --i)
        result += str[Math.floor(Math.random() * str.length)];
      return result;
    },
    formatNode(obj, prev, isParent) {
      let id = obj.Id.toString();
      if (prev && prev != "") {
        id = prev + "_" + id;
      }
      let node = {
        id,
        disableDrag: false,
        html: this.formatHtml(
          obj.EmName,
          obj.ProgressState,
          obj.Progress,
          obj.ProgressStateName,
          obj.Title
        ),
        childNum: obj.ChildList
          ? obj.ChildList.length
          : obj.ChildNum
          ? obj.ChildNum
          : 0
      };
      if (prev.indexOf('child') != -1) {
        node.childNum = obj.ChildList
          ? obj.ChildList.length
          : obj.ChildNum
          ? obj.ChildNum
          : 0;
      } else if (prev.indexOf('parent') != -1) {
        node.childNum = obj.ParentList
          ? obj.ParentList.length
          : obj.ParentNum
          ? obj.ParentNum
          : 0;
      }
      if (obj.ChildNum > 0 && !obj.ChildList) {
        node.data = {
          isNeedLoadDataFromRemoteServer: true,
          childrenLoaded: false
        };
        node.expandHolderPosition = "right";
        node.expanded = false;
      } else if (obj.ParentNum > 0 && !obj.ParentList) {
        node.data = {
          isNeedLoadDataFromRemoteServer: true,
          childrenLoaded: false
        };
        node.expandHolderPosition = "left";
        node.expanded = false;
        if (isParent) {
          node.nodeParent=true          
        }
      }
      return node;
    },
    formatLink(from, to, isHide) {
      return {
        from,
        to,
        isHideArrow: true,
        isHide: isHide
      };
    },
    formatHtml(name, status, progress, statusName, title) {
      let html = `<div class="parent-card"><div class="o-card flex row"><div class="col-auto q-mr-xs"><div style="width:20px;height:20px;font-size:14px;" class="bg-green-2 text-green vertical-middle rounded-borders text-center">${name.substring(
        0,
        1
      )}</div></div><div class="col q-ml-xs"><div class="flex row q-mb-xs"><div class="text-grey col f12">${name}</div><div class="text-negative text-weight-bold f12">${statusName} ${progress}%</div></div><div class="q-mt-xs ellipsis-2-lines" title="${title}">${title}</div></div></div></div>`;
      return html;
    },
    onSizeOptionChanged() {
      // 图谱的大小会随着父元素的宽高自动适应，所以修改父元素的宽高就可以设置图谱的宽高
      this.myGraphPanelSize.width = this.currentSize;
      this.myGraphPanelSize.height = this.currentSize;
      // 你也可以在调整完大小后刷新一下图谱，确保位置是合理的
      // this.$nextTick(() => { // $nextTick的功能你懂的
      //   this.$refs.seeksRelationGraph.refresh()
      // })
    },
    applyCollapseStyle2Node(_node) {
      // _node的子节点将被隐藏，同时让_node右侧显示一个加号，点击后可以展开子节点
      if (_node.lot.childs.length > 0) {
        _node.lot.childs.forEach(thisChildNode => {
          thisChildNode.isShow = false;
          this.applyCollapseStyle2Node(thisChildNode);
        });
        _node.expanded = false;
        _node.expandHolderPosition = "right";
      }
    },
    onNodeCollapse(node, e) {
      // 当有一些节点被显示或隐藏起来时，会让图谱看着很难看，需要布局器重新为节点分配位置，所以这里需要调用refresh方法来重新布局
      this.$refs.seeksRelationGraph.refresh();
    },
    onNodeExpand(node, e) {
      // 当有一些节点被显示或隐藏起来时，会让图谱看着很难看，需要布局器重新为节点分配位置，所以这里需要调用refresh方法来重新布局
      //this.$refs.seeksRelationGraph.refresh();
      // 根据具体的业务需要决定是否需要从后台加载数据
      if (!node.data.isNeedLoadDataFromRemoteServer) {
        this.$refs.seeksRelationGraph.refresh();
        return;
      }
      //判断是否已经动态加载数据了
      if (node.data.childrenLoaded) {
        this.$refs.seeksRelationGraph.refresh();
        return;
      }
      this.g_loading = true;
      node.data.childrenLoaded = true;
      this.loadChildNodesFromRemoteServer(node, new_data => {
        this.g_loading = false;
        this.$refs.seeksRelationGraph.appendJsonData(new_data, seeksRGGraph => {
          // 这些写上当图谱初始化完成后需要执行的代码
        });
      });
    },
    loadChildNodesFromRemoteServer(node, callback) {
      let Type=2
      if(node.id.indexOf('parent')!=-1){
        Type=1
      }
      queryUserOKRNextAlignView({
        PeriodId: this.proid,
        ObjectiveId: node.id.split("_")[1],
        Type
      }).then(r => {
        if (r.Data.length > 0) {
          var _new_json_data = {
            nodes: [],
            links: []
          };
          let zy=`child-${this.randomString()}`
          if(node.id.indexOf('parent')!=-1){
            zy=`parent-${this.randomString()}`
          }
          r.Data.forEach(x => {
            _new_json_data.nodes.push(this.formatNode(x, zy));
            if(zy.indexOf('child')!=-1){
              _new_json_data.links.push(this.formatLink(node.id, `${zy}_${x.Id}`, false));
            }else{
               _new_json_data.links.push(this.formatLink(`${zy}_${x.Id}`,node.id, false));
            }
          });
          callback(_new_json_data);
        }
      });
    }
  }
};
</script>

<style>
.align-view .parent-card {
  position: relative;
  width: 334px;
  background: #fff;
  border-radius: 2px;
  user-select: none;
  cursor: pointer;
  height: 88px;
}
.align-view .parent-card .o-card {
  max-height: 100%;
  height: 100%;
  padding: 12px;
  border-radius: 2px;
  background: #fff;
  background-color: #ffffff;
  cursor: pointer;
  box-shadow: 0 1px 10px rgba(31, 35, 41, 0.08);
}
.align-view .rel-map {
  background: #f5f5f5 !important;
}
.align-view .f12 {
  font-size: 12px !important;
}
.align-view .c-btn-open-close span {
  color: #111 !important;
  background-color: #ddd !important;
}
.align-view .rel-node-peel:first-child {
  display: none;
}
</style>
