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

<script>
import {on, off} from '@uif/hq/lib/utils/dom'
import {debounce} from '@uif/hq/lib/utils/pipe'
import {loadCharts} from '@uif/admin/lib/utils/load'

const chart = {
  name: 'u-chart',
  props: {
    autoResize: {
      type: Boolean,
      default: true
    },
    config: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      onResize: debounce(() => this.resize(), 100)
    }
  },
  watch: {
    config: {
      deep: true,
      handler () {
        this.setOption()
      }
    }
  },
  mounted () {
    this.init()
    if (this.autoResize) {
      on(window, 'resize', this.onResize)
    }
  },
  beforeDestroy () {
    if (this.autoResize) {
      off(window, 'resize', this.onResize)
    }
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    init () {
      this.resize()
      loadCharts().then((echarts) => {
        this.chart = echarts.init(this.$el)
        this.setOption()
      })
    },
    resize () {
      if (this.chart && this.$el && this.$el.getBoundingClientRect().width) {
        this.chart.resize()
      }
    },
    setOption () {
      this.chart && this.chart.setOption(this.config)
    }
  }
}

chart.get = loadCharts

export default chart
</script>
