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

<script>
import {getGo, create, getLinkTemplate, getNodeTemplate} from './draw'

export default {
  name: 'u-go',
  props: {
    dataList: {
      type: Array,
      default () {
        return []
      }
    },
    linkList: {
      type: Array,
      default () {
        return []
      }
    },
    getConfig: {
      type: Function,
      default () {
        return () => {}
      }
    },
    renderNodeTemplate: {
      type: Function,
      default: null
    },
    renderLinkTemplate: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
    }
  },
  watch: {
    dataList () {
      this.updateDiagram()
    }
  },
  mounted () {
    this.updateDiagram()
  },
  beforeDestroy () {
    this.go = null
    this.diagram = null
  },
  methods: {
    updateDiagram () {
      if (!this.diagram) {
        this.createDiagram().then(() => {
          this.loadData()
        })
      } else {
        this.loadData()
      }
    },
    // 创建diagram
    createDiagram () {
      return new Promise((resolve) => {
        getGo().then(go => {
          this.go = go
          this.diagram = create(this.$el, this.getConfig(this.go))
          this.diagram.nodeTemplate = (this.renderNodeTemplate || getNodeTemplate)(this.go)
          this.diagram.linkTemplate = (this.renderLinkTemplate || getLinkTemplate)(this.go)
          this.$emit('on-created', this.diagram, this.go)
          resolve(this.diagram)
        })
      })
    },
    // 渲染数据
    loadData () {
      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-loaded', this.diagram, this.go)
    },
    // 全部显示
    zoomToFit () {
      if (this.diagram) {
        this.diagram.commandHandler.zoomToFit()
      }
    }
  }
}

</script>
