<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  onMounted,
  watch,
  getCurrentInstance,
  onBeforeUnmount
} from 'vue'
import { useECharts, useInstance, addEvent, removeEvent } from '@/utils'
import { EChartsType } from 'echarts'

export default defineComponent({
  name: 'DefChart',
  props: {
    options: {
      type: Object,
      required: true
    }
  },
  setup(prop) {
    // 初始化图表
    const chartRef = ref<HTMLElement>()
    let chart: EChartsType | null = null
    let throttleResize: {
      (this: Window, ev: UIEvent): any
      (this: Window, ev: UIEvent): any
    }
    onMounted(() => {
      chart = useECharts(chartRef.value!, prop.options)
      // 防抖自适应
      const { $throttle } = useInstance(getCurrentInstance)
      throttleResize = $throttle(() => {
        chart?.resize()
      }, 500)
      addEvent(window, 'resize', throttleResize)
      // window.addEventListener('resize', throttleResize)
    })
    onBeforeUnmount(() => {
      // window.removeEventListener('resize', throttleResize)
      removeEvent(window, 'resize', throttleResize)
    })
    watch(
      () => prop.options,
      (newValue) => {
        if (newValue) {
          chart?.setOption(newValue)
          chart?.resize()
        }
      }
    )
    return {
      chartRef
    }
  }
})
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
