<template>
  <div ref="element" class="common-chart" />
</template>

<script lang="ts">
import {
  defineComponent,
  toRefs,
  ref,
  onMounted,
  onUnmounted,
  watch
} from 'vue'
import * as echarts from 'echarts/core'
import {
  BarChart,
  // 系列类型的定义后缀都为 SeriesOption
  PieChart,
  LineChart,
} from 'echarts/charts'

import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer
])

export default defineComponent({
  props: {
    data: {
      type: Object,
      default: null
    }
  },
  setup(props) {
    const { data } = toRefs(props)
    const element = ref(null)
    let chart: echarts.ECharts
    onMounted(() => {
      chart = echarts.init(element.value as unknown as HTMLElement)
      chart.setOption(data.value as unknown as any)
      ;(window as any).onresize = () => {
        chart.resize()
      }
    })
    onUnmounted(() => {
      chart.dispose()
    })
    watch(data.value, () => {
      if (chart) {
        chart.setOption(data.value as unknown as any, {
          notMerge: true
        })
      }
    })
    return { element }
  }
})
</script>

<style lang="scss">
.common-chart {
  // width: 100%;
  height: 100%;
  background: #fff;
  margin: 0 20px 0 0 !important;
}
</style>
