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

<script lang="ts">
import * as echarts from 'echarts/core'
import { BarChart, BarSeriesOption, LineChart, LineSeriesOption, PieChart, PieSeriesOption } from 'echarts/charts'
import {
  TitleComponent,
  TitleComponentOption,
  TooltipComponent,
  GridComponent,
  GridComponentOption,
  LegendComponent,
  LegendComponentOption,
  DatasetComponent,
  DatasetComponentOption,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'

type ECOption = echarts.ComposeOption<
  | BarSeriesOption
  | LineSeriesOption
  | PieSeriesOption
  | TitleComponentOption
  | GridComponentOption
  | LegendComponentOption
  | DatasetComponentOption
>

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DatasetComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer,
])

/**
 * 包装 echarts，支持折线图、柱状图、饼图
 * @see https://echarts.apache.org/zh/index.html
 */
@Component({
  name: 'EtChart',
})
export default class extends Vue {
  /**
   * echars 配置项
   */
  @Prop({ default: () => {} }) private option!: ECOption

  @Watch('option')
  private onOptionChange() {
    this.chart?.setOption(this.option)
  }

  mounted() {
    this.$nextTick(() => {
      this.init()
    })
  }

  beforeDestroy() {
    if (!this.chart) {
      return
    }

    if (!this.chart.isDisposed()) {
      this.chart.dispose()
    }
    this.chart = null
  }

  private chart: echarts.ECharts | null = null

  private init() {
    this.chart = echarts.init(this.$el as HTMLElement)
    this.chart.setOption(this.option)
  }

  /**
   * 改变图表尺寸
   * @param {Object} opts
   * @param {number | string} width 可显式指定实例宽度，单位为像素。如果传入值为 null/undefined/'auto'，则表示自动取 dom（实例容器）的宽度。
   * @param {number | string} height 可显式指定实例高度，单位为像素。如果传入值为 null/undefined/'auto'，则表示自动取 dom（实例容器）的高度。
   * @param {boolean} silent 是否禁止抛出事件。默认为 false。
   * @public
   */
  public resize(opts?: { width?: number | 'auto'; height?: number | 'auto'; silent?: boolean }) {
    this.chart?.resize(opts)
  }
}
</script>
