<template>
  <div class="chart-container">
    <div class="chart" ref="chart" :style="{ height: `${height}px` }"></div>
  </div>
</template>

<script>
/* eslint-disable no-unused-expressions,no-param-reassign */
import { getInstanceByDom, throttle, use as useChart, init as initChart, connect as connectChart } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TitleComponent,
  MarkLineComponent,
} from 'echarts/components';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import { merge } from 'lodash-es';
import { addListener, removeListener } from 'resize-detector';
import { getDefaultOption, getMarkLineOption } from './defaultOption';

useChart([
  BarChart,
  LineChart,
  PieChart,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
  DatasetComponent,
  TitleComponent,
  MarkLineComponent,
]);

export default {
  name: 'BaseChart',
  props: {
    option: {
      type: Object,
    },
    height: {
      type: Number,
      default: 300,
    },
    group: {
      type: String,
    },
  },
  data() {
    return {
      chartElement: null,
    };
  },
  computed: {
    mergedOption() {
      return merge({}, getDefaultOption(), this.option);
    },

    chart() {
      if (this.chartElement) {
        return getInstanceByDom(this.chartElement);
      }
      return null;
    },

    resizeHandler() {
      return throttle(this.chart?.resize, 100);
    },
  },
  created() {},
  mounted() {
    this.drawChart();
    addListener(this.chartElement, this.resizeHandler);
  },
  beforeDestroy() {
    removeListener(this.chartElement, this.resizeHandler);
    this.chart?.clear();
    this.chart?.dispose();
  },
  watch: {
    option: {
      deep: true,
      handler() {
        this.drawChart();
      },
    },
  },
  methods: {
    clean() {
      this.chart?.clear();
      this.chart?.dispose();
    },

    drawChart() {
      let { chart } = this;
      if (chart) {
        // chart?.clear();
      } else {
        this.chartElement = this.$refs.chart;
        chart = initChart(this.chartElement);
        if (this.group) {
          chart.group = this.group;
          connectChart(this.group);
        }
      }
      console.log(this.mergedOption);
      chart.setOption(this.mergedOption, true);
    },
  },
};
</script>
