<template>
  <div :id="domId" :style="styleObj" class="chart_graph"></div>
</template>

<script>
import { generateUUID } from '@/utils'
export default {
  name: 'chartGraph',
  props: {
    h: {
      type: [Number, String],
      default: 300
    },
    w: {
      type: [Number, String],
      default: 300
    },
    nodes: {
      type: Array,
      default: () => [] // [{category: 0, id: '1', name: '张三'， symbolSize: 10, value: 2}]
    },
    links: {
      type: Array,
      default: () => [] // [{source: '1', target: '0'}]
    },
    categories: {
      type: Array,
      default: () => [] // [{name: '员工'}]
    },
    name: {
      type: String
    },
    layout: {
      type: String,
      default: () => 'circular'
    },
    showlegend: {
      type: Boolean,
      default: false
    },
    top: {
      type: [Number, String],
      default: () => 20
    },
    bottom: {
      type: [Number, String],
      default: () => 20
    },
    roam: {
      type: Boolean,
      default: true
    },
    label: {
      type: Object,
      default: () => {
        return {
          position: 'right',
          formatter: '{b}'
        }
      }
    },
    force: {
      type: Object
    },
    circular: {
      type: Object,
      default: () => {
        return { rotateLabel: true }
      }
    },
    grid: {
      type: Object,
      default: () => {
        return { }
      }
    },
    itemStyle: {
      type: Object,
      default: () => {
        return { }
      }
      // 点颜色
    },
    emphasis: {
      // 线颜色
      type: Object,
      default: () => {
        return { }
      }
    },
    lineStyle: {
      type: Object,
      default: () => {
        return {
          color: 'target',
          curveness: 0.3
        }
      }
    },
    focusNodeAdjacency: {
      type: Boolean,
      default: false
    },
    isknowledgegraph: {
      type: Boolean,
      default: false
    },
    legendOrient: {
      type: String,
      default: 'horizontal'
    },
    legendLeft: {
      type: String,
      default: 'center'
    },
    draggable: {
      type: Boolean,
      default: false
    },
    legendType: {
      type: String,
      default: ''
    },
    edgeSymbol: {
      type: Array,
      default: () => { return [] }
    },
    edgeSymbolSize: {
      type: Array,
      default: () => { return [] }
    }
  },
  data () {
    return {
      zoom: 1,
      domId: generateUUID(),
      chart: null,
      timer: null,
      innerWidth: null,
      innerHeight: null
    }
  },

  computed: {
    styleObj () {
      const regPos = / ^\d+$/
      const style = {
        height: this.h || '300px',
        width: this.w || '300px'
      }
      if ((typeof this.h === 'string' && regPos.test(this.h)) || typeof this.h === 'number') {
        style.height = this.h + 'px'
      }
      if ((typeof this.w === 'string' && regPos.test(this.w)) || typeof this.w === 'number') {
        style.width = this.w + 'px'
      }
      style.zoom = this.zoom
      style.transform = `scale(${1 / this.zoom})`
      style.transformOrigin = '0 0'
      return style
    }
  },
  created () { },
  mounted () {
    const _this = this
    window.onresize = function () {
      _this.innerWidth = document.documentElement.clientWidth
      _this.innerHeight = document.documentElement.clientHeight
    }
    this.$nextTick(_ => this.initChart())
  },
  destroyed () {
    window.onresize = null
  },
  methods: {
    initChart () {
      const self = document.getElementById(this.domId)
      if (!self) return
      const setSelected = {}
      this.categories.map((item, index) => {
        if (index === 0) {
          setSelected[item.name] = true
        } else {
          setSelected[item.name] = false
        }
        return item
      })
      const option = {
        grid: this.grid,
        tooltip: this.isknowledgegraph
          ? {
              formatter: e => {
                if (e.name === '大') {
                  const tooltipSrc = this.$store.state.statistics.epbigTooltip
                  const str = '- ' + tooltipSrc.join('<br>- ')
                  return str
                } else if (e.name === '中') {
                  const tooltipSrc = this.$store.state.statistics.epmediTooltip
                  const str = '- ' + tooltipSrc.join('<br>- ')
                  return str
                } else if (e.name === '小') {
                  const tooltipSrc = this.$store.state.statistics.epsmallTooltip
                  const str = '- ' + tooltipSrc.join('<br>- ')
                  return str
                }
              }
            }
          : {
              formatter: e => {
                if (e.data.pageName === 'staff') {
                  return `<b>${e.name}</b> <br/>
                    所属机构： ${e.data.info.departmentName}<br/>
                    入职时间：${e.data.info.empEntryTime}<br/>
                    岗位：${e.data.info.empPostName}<br/>
                    学历：${e.data.info.empAcademicDegree}<br/>
                    出生日期：${e.data.info.empBirth}<br/>
                    性别：${e.data.info.empSex}<br/>
                    `
                } else if (e.data.pageName === 'network' || e.data.pageName === 'subBranch') {
                  return `<b>${e.name}</b>`
                } else {
                  return ''
                }
              }
            },
        legend: [
          {
            show: this.showlegend,
            data: this.categories,
            orient: this.legendOrient,
            left: this.legendLeft,
            type: this.legendType
          }
        ],
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            draggable: this.draggable,
            name: this.name,
            type: 'graph',
            layout: this.layout,
            circular: this.circular,
            data: this.nodes,
            links: this.links,
            categories: this.categories,
            roam: this.roam,
            label: this.label,
            lineStyle: this.lineStyle,
            edgeSymbol: this.edgeSymbol || ['', ''],
            edgeSymbolSize: this.edgeSymbolSize || [],
            top: this.top,
            bottom: this.bottom,
            itemStyle: this.itemStyle,
            emphasis: this.emphasis,
            focusNodeAdjacency: this.focusNodeAdjacency
          }
        ]
      }

      if (this.force) Object.keys(this.force).length && (option.series[0].force = this.force)

      this.chart = this.$echarts.init(self)
      this.chart.on('click', event => this.$emit('click', event))
      this.chart.on('mousemove', this.onMousemove)
      this.chart.on('mouseout', this.onMouseout)
      this.chart.setOption(option)
    },
    updatedChart () {
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.chart && this.chart.dispose()
        this.initChart()
        this.timer = null
      }, 100)
    }
  },
  watch: {
    innerWidth: function (val) { // 监听屏幕宽度变化
      this.updatedChart()
    },
    innerHeight: function (val) {
      this.updatedChart()
    },
    styleObj: {
      handler () {
        if (this.chart) {
          this.chart.resize()
        }
      }
    },
    nodes: {
      handler (val) {
        if (val) {
          this.updatedChart()
        }
      },
      deep: true
    },
    links: {
      handler (val) {
        if (val) {
          this.updatedChart()
        }
      },
      deep: true
    },
    categories: {
      handler (val) {
        if (val) {
          this.updatedChart()
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
.chart_graph {
  height: 300px;
  width: 300px;
}
</style>
