<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>

<script>
import { ref, reactive, watchEffect } from 'vue';
import { cloneDeep } from 'lodash';
import { useEcharts } from '../../hooks/useEcharts';

export default {
  name: 'CustomEchartMixin',
  props: {
    chartData: {
      type: Array,
      default: () => [],
    },
    option: {
      type: Object,
      default: () => ({}),
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
  },
  setup(props) {
    const chartRef = ref(null);
    const { setOptions } = useEcharts(chartRef);
    const option = reactive({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          label: {
            show: true,
            backgroundColor: '#333',
          },
        },
      },
      xAxis: {
        type: 'category',
        data: [],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: 'bar',
          type: 'bar',
          data: [],
          itemStyle: {
            barWidth: 10,
          },
        },
      ],
    });

    watchEffect(() => {
      props.chartData && initCharts();
    });

    function initCharts() {
      if (props.option) {
        Object.assign(option, cloneDeep(props.option));
      }
      let typeArr = Array.from(new Set(props.chartData.map((item) => item.type)));
      let xAxisData = Array.from(new Set(props.chartData.map((item) => item.name)));
      let seriesData = [];
      typeArr.forEach((type, index) => {
        const barStyle = props.option?.barStyle ?? {};
        let obj = { name: type, ...barStyle };
        let chartArr = props.chartData.filter((item) => type === item.type);
        obj['data'] = chartArr.map((item) => item.value);
        obj['type'] = chartArr[0].seriesType;
        obj['stack'] = chartArr[0].stack;
        obj['itemStyle'] = chartArr[0].itemStyle;
        seriesData.push(obj);
      });
      option.series = seriesData;
      option.xAxis.data = xAxisData;
      setOptions(option);
    }
    return { chartRef };
  },
};
</script>
