<template>
  <div ref="main" style="width: 100%;height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, onUnmounted, defineProps, reactive, watch, nextTick } from "vue";

const main = ref();
const myChart = ref();
const pageData = reactive({
  list: []
})

const props = defineProps({
  data: Array,
  keys: Number,
  text: {
    type: String,
    default: ''
  },
  itemGap: {
    type: Number,
    default: 30
  }
})

// 监听 keys 变化
watch(() => props.keys, () => {
  // 清空原有数据
  pageData.list = []

  // 重新填充数据
  for (let i = 0; i < props.data.length; i++) {
    const item = props.data[i]
    pageData.list.push({
      ...item,
      itemStyle: {
        color: item.color
      }
    })
  }

  // 重新渲染图表
  if (myChart.value) {
    myChart.value.setOption(setOptions());
  }
})

// 监听 data 变化（可选，如果数据也会独立变化）
watch(() => props.data, () => {
  refreshChart()
})

// 初始化
onMounted(() => {
  initChart()
});

// 初始化图表
const initChart = () => {
  for (let i = 0; i < props.data.length; i++) {
    const item = props.data[i]
    pageData.list.push({
      ...item,
      itemStyle: {
        color: item.color
      }
    })
  }

  myChart.value = echarts.init(main.value);
  myChart.value.setOption(setOptions());

  // 监听窗口变化
  window.addEventListener("resize", () => {
    myChart.value.resize();
  });
}

// 刷新图表函数
const refreshChart = () => {
  pageData.list = []

  for (let i = 0; i < props.data.length; i++) {
    const item = props.data[i]
    pageData.list.push({
      ...item,
      itemStyle: {
        color: item.color
      }
    })
  }

  if (myChart.value) {
    myChart.value.setOption(setOptions());
  }
}

const setOptions = () => {
  return {
    tooltip: {
      trigger: 'item'
    },
    graphic: {
      type: 'text',
      left: '27%',
      top: '40%',
      style: {
        text: String(props.text).replace(/(\d)(?=(?:\d{6})+$)/g, '$1.'),
        textAlign: 'center',
        fill: '#333',
        width: 30,
        height: 30,
        fontSize: 14
      }
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 100,
      top: 10,
      bottom: 20,
      itemGap: props.itemGap,
      itemWidth: 14,
      itemHeight: 14,
      icon: "circle",
      textStyle: {
        fontSize: 16
      },
      formatter: function (name) {
        var data = pageData.list;
        var total = data.reduce(function (sum, item) {
          return sum + item.value;
        }, 0);
        var target = data.find(function (item) {
          return item.name === name;
        });
        if (!target) return name;
        var percentage = ((target.value / (total == 0 ? 1 : total)) * 100).toFixed(1) + '%';
        return `${name}     ${percentage}     ${target.value}`;
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ["30%", "45%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: false,
          }
        },
        labelLine: {
          show: false
        },
        data: pageData.list
      }
    ]
  };
}

// 组件卸载时销毁图表
onUnmounted(() => {
  if (myChart.value) {
    myChart.value.dispose();
  }
  window.removeEventListener("resize", () => {
    myChart.value && myChart.value.resize();
  });
});
</script>

<style lang="scss" scoped>
::v-deep canvas {
  width: 100% !important;
  height: 100% !important;
}
</style>