<template>
  <div class="n-go"></div>
</template>

<script>
import {loadGo, create, getLinkTemplate, getNodeTemplate} from './draw'
import {prop} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-go',
  props: {
    // 数据集合
    dataList: prop.array(),
    // 关系集合
    linkList: prop.array(),
    // 基础配置
    getConfig: prop.function(),
    // 自定义渲染节点
    renderNodeTemplate: prop.function(null),
    // 自定义渲染关系
    renderLinkTemplate: prop.function(null)
  },
  watch: {
    dataList () {
      this.updateDiagram()
    }
  },
  mounted () {
    this.updateDiagram()
  },
  beforeDestroy () {
    this.go = null
    this.diagram = null
  },
  methods: {
    updateDiagram () {
      Promise.resolve(this.diagram)
        .then((diagram) => diagram || this.createDiagram())
        .then(() => this.renderData())
    },
    // 创建diagram
    createDiagram () {
      return loadGo().then(go => {
        this.go = go
        this.diagram = create(this.$el, this.getConfig(go))
        this.diagram.nodeTemplate = (this.renderNodeTemplate || getNodeTemplate)(this.go)
        this.diagram.linkTemplate = (this.renderLinkTemplate || getLinkTemplate)(this.go)
        this.$emit('on-mounted', this.diagram, this.go)
        return this.diagram
      })
    },
    // 渲染数据
    renderData () {
      if (this.dataList.length && this.linkList.length) {
        this.diagram.model = new this.go.GraphLinksModel(this.dataList, this.linkList)
      } else if (this.dataList.length) {
        this.diagram.model = new this.go.TreeModel(this.dataList)
      }
      this.$emit('on-done', this.diagram, this.go)
    },
    // 全部显示
    zoomToFit () {
      if (this.diagram) {
        this.diagram.commandHandler.zoomToFit()
      }
    }
  }
}

</script>
