<template>
  <view
    :id="htmlId"
    ref="echartsRef"
    :style="{ width: '100%', height: `${height ? height : data.length * 100}rpx` }"
    @click="viewClick"
  ></view>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { computed, onMounted, ref } from 'vue';

const props = withDefaults(
  defineProps<{
    htmlId: string;
    data: DataItem[];
    height?: number;
    legendVisible?: boolean;
  }>(),
  {},
);

interface DataItem {
  value: number;
  name: string;
  color?: string;
  labelVisible?: boolean;
  labelPosition?: string;
  labelFormatter?: (param: any) => string;
}

const myChart = ref<echarts.ECharts | null>(null);

const colors = [
  '#FBCA85',
  '#F5EB82',
  '#FB8F85',
  '#82F58B',
  '#85FBDE',
  '#85DEFB',
  '#9FA7FB',
  '#D59FFB',
  '#FB9FD5',
];

const viewClick = (e: MouseEvent) => {};

const seriesData = computed(() => {
  return props.data.map((item, index) => {
    return {
      value: item.value,
      name: item.name,
      itemStyle: {
        color: item.color ?? colors[index],
      },
      label: {
        show: item.labelVisible ?? true,
        formatter: (param: any) => {
          if (item.labelFormatter && typeof item.labelFormatter === 'function') {
            return item.labelFormatter(param);
          }
          return `${param.value}%`;
        },
        color: colors[index],
        position: item.labelPosition ?? 'outside',
      },
    };
  });
});

const options = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
    },
    legend: props.legendVisible ?? {
      bottom: '0%',
      left: 'center',
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        startAngle: 0,
        endAngle: 360,
        data: seriesData.value,
      },
    ],
  };
});

const initEcharts = async () => {
  myChart.value = echarts.init(document.getElementById(props.htmlId));

  myChart.value && myChart.value.setOption(options.value);
};
onMounted(() => {
  initEcharts();
});
</script>

<style scoped lang="scss"></style>
