<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: 'CustomEchartBar',
  props: {
    chartData: {
      type: Array,
      default: () => [],
      required: true,
    },
    option: {
      type: Object,
      default: () => ({}),
    },
    type: {
      type: String,
      default: 'bar',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
    isSeries: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['click'],
  setup(props, { emit }) {
    const chartRef = ref(null);
    const { setOptions, getInstance } = useEcharts(chartRef);
    const option = reactive({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          label: {
            show: true,
            backgroundColor: '#333',
          },
        },
      },
      legend: {
        top: 30,
      },
      grid: {
        top: 60,
      },
      xAxis: {
        type: 'category',
        data: [],
      },
      yAxis: {
        type: 'value',
      },
      series: [],
    });

    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, type: props.type, ...barStyle };
        let data = [];
        xAxisData.forEach((x) => {
          let dataArr = props.chartData.filter((item) => type === item.type && item.name == x);
          if (dataArr && dataArr.length > 0) {
            data.push(dataArr[0].value);
          } else {
            data.push(null);
          }
        });
        obj['data'] = data;
        if (props.option?.color) {
          obj.color = props.option?.color[index];
        }
        seriesData.push(obj);
      });
      option.series = props.isSeries && option.series.length > 0 ? option.series : seriesData;
      option.xAxis.data = xAxisData;
      setOptions(option);
      getInstance()?.off('click', onClick);
      getInstance()?.on('click', onClick);
    }

    function onClick(params) {
      emit('click', params);
    }
    return { chartRef };
  },
};
</script>
