<template>
	<div class="devLink_Precess_container" ref="linkDesigner"></div>
</template>

<script>
const { Graph, Dom } = require("@antv/x6");
import '@antv/x6-vue-shape'
const nodeComponent = require("./linknode.vue").default;

export default {
  props: {
    jobId: [String],
    nodeList: [Array]
  },
  watch: {
    nodeList: {
      handler(val) {
        this.initData()
      },
      immediate: true
    }
  },
  data() {
    return {
      job: {},
    };
  },
  created() {},
  methods: {
    initData() {
      if(this.$refs.linkDesigner) {
        this.job = {
          id: this.jobId,
          graph: undefined, //画布
          data: this.getNodePosition(this.nodeList),
          taskState: ""
        };
        this.registerNode();
        this.initCanvas();
      }
    },
    /**
     * @Author: y_zp
     * @description: 注册节点
     */
    registerNode() {
      const node = {
        name: 'custom-lane',
        options: {
          inherit: 'vue-shape',
          width: 200,
        }
      }
      Graph.registerNode(node.name, node.options, true)
    },
    /**
     * @Author: y_zp
     * @description: 链路数据绘制
     */
    initCanvas() {
      this.$nextTick(() => {
        const graphOpetion = this.getGraphOpetion();
        this.job.graph = new Graph(graphOpetion);
        if (this.job.data) {
          try {
            this.setCanvas(this.job);
          } catch (e) {
            console.error(e);
          }
        }
      })
    },
    /**
		 * @Author: y_zp
		 * @description: 设置节点位置信息
		 */
		getNodePosition(data) {
			let _width = this.$refs.linkDesigner.scrollWidth
      let newData = JSON.parse(JSON.stringify(data));
			const result = [];
			const itemMap = {};
			// 数据转化为一棵树
			data.forEach(item => {
				const id = item.id;
				const nextId = item.nextId;
				if (!itemMap[id]) {
					itemMap[id] = {
						children: [],
					};
				}
				const treeItem = {
					...item,
					children: itemMap[id]["children"],
				};

				if (nextId == null) {
					result.push(treeItem);
				} else {
					if (!itemMap[nextId]) {
						itemMap[nextId] = {
							children: [],
						};
					}
					itemMap[nextId].children.push(treeItem);
				}
			})

			// 设置位置信息
			const setPosition = (data, i) => {
				let num = i + 1;
				data.forEach((item, index) => {
          // 获取当前节点
          let curNodeList = newData.filter(v => { return v.id == item.id });
          let initY = 100;
          let position = {
            x: _width - (400 + num * 320),
            y: initY + index * 60
          };
          if(!curNodeList[0].position || (curNodeList[0].position && position.x < curNodeList[0].position.x)) {
            // 和下一个节点的Y轴对齐
            let nextNodeList = [];
            curNodeList.forEach(v => {
              let val = newData.find(vl => { return vl.id == v.nextId })
              val && nextNodeList.push(val)
            })
            if(nextNodeList[0] && nextNodeList[0].position.y > initY) {
              initY = nextNodeList[0].position.y;
            }
            position.y = initY + index * 60;
            
            curNodeList.forEach(v => {
              v.position = position;
            })
          }
          
					if (item.children.length > 0) {
						setPosition(item.children, num);
					}
				})
			}

			setPosition(result, 0);

      return newData;
		},

		/**
		 * @Author: y_zp
		 * @description: 绘制链路图
		 */
		setCanvas(job) {
			const cells = [];
			job.data.forEach(node => {
				let status = job.taskState.toLocaleLowerCase() || "";
				let cell = {
					label: node.name,
					width: 200,
					height: 40,
					id: node.id,
					shape: "custom-lane",
					position: node.position,
					component: this.renderNodeBtn(node, status)
				}
				cells.push(job.graph.createNode(cell));

				if (node.nextId) {
					let nodeItem = {
						shape: "edge",
						id: `${node.id}${node.nextId}`,
						source: node.id,
						target: node.nextId,
						label: {
							data: node,
							position: 50
						},
						attrs: {
							line: {
								stroke: "#c9c9c9",
								strokeWidth: 1,
								strokeDasharray: 3,
							}
						}
					}
					cells.push(job.graph.createEdge(nodeItem))
				}
			});
			job.graph.resetCells(cells);
			job.graph.centerContent();
		},

		renderNodeBtn(node, status) {
			return {
				template: `<node-component />`,
				provide() {
					return {
						nodeData: { ...node, status }
					}
				},
				components: {
					nodeComponent
				},
			}
		},

		getGraphOpetion(id) {
      return {
        container: this.$refs.linkDesigner, //容器对象 //容器对象
        grid: true, //
        autoResize: true, //是否允许更新容器大小
        // history: true,
        height: "100%",
        width: "100%",
        panning: {
          //支持水平平移
          enabled: true,
          eventTypes: ["leftMouseDown", "rightMouseDown", "mouseWheel"],
        },
        mousewheel: {
          //允许缩放
          enabled: true, //启动
          zoomAtMousePosition: true,
          modifiers: "ctrl",
          minScale: 0.5,
          maxScale: 3,
        },
        connecting: {
          //连线规则
          router: {
            name: "manhattan",
            args: { padding: 30 },
          },
        },
        resizing: true, //缩放节点
        rotating: false, //旋转节点
        selecting: {
          enabled: true,
          rubberband: true,
          showNodeSelectionBox: true,
        },
        minimap: {
          enabled: true
        },
        snapline: true, //对齐线是移动节点排版的辅助工具
        keyboard: true, //键盘快捷键
        clipboard: true, //剪切板
      };
    },

  }
};
</script>
<style lang="less" scoped>
.devLink_Precess_container {
  width: 100%;
  height: 100%;
}
</style>