/* eslint-disable no-param-reassign */
import { getInstanceByDom } from 'echarts/core';
import { cloneDeep } from 'lodash-es';

export default {
  data() {
    return {
      legendData: null,
    };
  },
  computed: {
    chart() {
      if (this.chartElement) {
        return getInstanceByDom(this.chartElement);
      }
      return null;
    },
  },
  watch: {
    data: {
      handler(val) {
        this.legendData = cloneDeep(val);
      },
      immediate: true,
    },
  },
  methods: {
    selectSeriesItem(series) {
      series.selected = !series.selected;
      this.updateLegendStatus();
    },

    handleSeriesHighlight(seriesName) {
      this.chart.dispatchAction({
        type: 'highlight',
        seriesName,
      });
    },

    handleSeriesDownplay(seriesName) {
      this.chart.dispatchAction({
        type: 'downplay',
        seriesName,
      });
    },

    updateLegendStatus() {
      this.chart.setOption({
        legend: {
          selected: this.selectedObj,
        },
      });
    },

    isFocused(seriesName) {
      const selectedSeries = Object.keys(this.selectedObj).filter(x => this.selectedObj[x]);
      return selectedSeries.length === 1 && selectedSeries[0] === seriesName;
    },
  },
};
