<template>
  <div
    class="chartContainer"
    @reset="reset"
    :style="{ height: isNaN(height) ? height : height + 'px', width: width ? width + 'px' : '100%' }"
    :ref="chartRef"
  ></div>
</template>
<script>
import * as echarts from 'echarts/core'
import { TitleComponent, ToolboxComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer
])
function debounce(fn, wait) {
  let timer
  let dur = wait || 400
  return () => {
    clearTimeout(timer)
    let self = this
    let args = arguments
    timer = setTimeout(() => {
      fn.apply(self, args)
    }, dur)
  }
}

export default {
  name: 'BarChart',
  props: {
    chartRef: {
      type: String,
      default: 'barChart'
    },
    option: {
      type: Object,
      required: false
    },
    height: {
      type: Number | String,
      required: false,
      default: 300
    },
    width: {
      type: Number,
      required: false
    }
  },
  data() {
    return {
      myChart: null,
      tiemID: ''
    }
  },
  watch: {
    option: {
      handler() {
        this.option && this.myChart && this.myChart.setOption(this.option)
      },
      deep: true
    }
  },
  mounted() {
    let chartDom = this.$refs[this.chartRef]
    this.myChart = echarts.init(chartDom)
    this.option && this.myChart.setOption(this.option)
    window.addEventListener('resize', this.debounce(this.reset))
  },
  methods: {
    debounce,
    reset() {
      this.myChart?.dispose()
      let chartDom = this.$refs[this.chartRef]
      if (!chartDom) return
      this.myChart = echarts.init(chartDom)
      this.option && this.myChart.setOption(this.option)
    }
  },
  destroyed() {
    window.removeEventListener('resize', debounce)
    this.myChart = null
  }
}
</script>
