<template>
  <n-resize class="n-chart" :class="{inherit}" @update="onResize"></n-resize>
</template>

<script>
import NResize from '@uif/next/lib/components/resize'
import {prop, hasElementSize, debounce, loadCharts} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-chart',
  components: {
    NResize
  },
  props: {
    // 图表配置
    config: prop.object(),
    // 绝对定位
    inherit: prop.boolean(),
    // 强制刷新（每次都会重置echarts）
    force: prop.boolean()
  },
  data () {
    return {
      onResize: debounce(() => this.resize(), 100)
    }
  },
  watch: {
    config: {
      deep: true,
      handler () {
        this.update()
      }
    }
  },
  mounted () {
    this.update()
  },
  beforeDestroy () {
    this.destroy()
  },
  methods: {
    resize () {
      if (this.chart && this.$el && hasElementSize(this.$el)) {
        this.chart.resize()
      }
    },
    destroy () {
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
    },
    update () {
      return Promise.resolve()
        // 强制刷新
        .then(() => this.force && this.destroy())
        // 初始化 echart
        .then(() => !this.chart && loadCharts().then(echarts => {
          if (!this.chart) {
            this.chart = echarts.init(this.$el)
            this.$emit('chart-created', this.chart)
          }
        }))
        // 设置 config
        .then(() => this.config && this.chart.setOption(this.config))
        // 销毁
        .then(() => !this.config && this.destroy())
    }
  }
}
</script>
