<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: 'CustomEchartRadar',
  props: {
    chartData: {
      type: Array,
      default: () => [],
      required: true,
    },
    option: {
      type: Object,
      default: () => ({}),
    },
    type: {
      type: String,
      default: 'radar',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
  },
  emits: ['click'],
  setup(props, { emit }) {
    const chartRef = ref(null);
    const { setOptions, getInstance } = useEcharts(chartRef);
    const option = reactive({
      title: {
        text: '',
      },
      legend: {},
      radar: {},
      tooltip: {},
      series: [
        {
          type: 'radar',
          data: [],
        },
      ],
    });

    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 indicator = Array.from(
        new Set(
          props.chartData.map((item) => {
            let { name, max } = item;
            return { name, max };
          })
        )
      );
      let data = [];
      typeArr.forEach((type) => {
        const radarStyle = props.option?.radarStyle ?? {};
        let obj = { name: type, ...radarStyle };
        let chartArr = props.chartData.filter((item) => type === item.type);
        obj['value'] = chartArr.map((item) => item.value);
        data.push(obj);
      });
      option.radar.indicator = indicator;
      option.series[0]['data'] = data;
      setOptions(option);
      getInstance()?.off('click', onClick);
      getInstance()?.on('click', onClick);
    }

    function onClick(params) {
      emit('click', params);
    }

    return { chartRef };
  },
};
</script>
