<template>
  <div ref="chartContainer"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from "vue";
import chart from "@/plugins/echarts";

const chartContainer = ref(null);
const props = defineProps(["data", "colors", "labelFormatter"]);

const defaultColors = ["#1890ff", "#FF7F50"];

let resizeObserver;
const initChart = () => {
  const myChart = chart.init(chartContainer.value);
  const option = {
    legend: {
      left: "center",
      top: "bottom"
    },
    series: [
      {
        type: "pie",
        radius: "50%",
        data: props.data,
        color: props.colors?.length ? props.colors : defaultColors,
        label: {
          show: true,
          // position: "inside",
          formatter: props.labelFormatter || "{d}%"
        }
      }
    ]
  };
  myChart.setOption(option);
  resizeObserver && resizeObserver.disconnect();
  // 使用 Resize Observer 监听元素大小变化
  resizeObserver = new ResizeObserver(() => {
    myChart.resize();
  });

  resizeObserver.observe(chartContainer.value);
};

onMounted(() => {
  initChart();
});

watch(
  [props.data, props.colors],
  () => {
    chartContainer.value && initChart();
  },
  { deep: true }
);

// 在组件销毁时停止 Resize Observer
onUnmounted(() => {
  resizeObserver.disconnect();
});
</script>

<style lang="scss" scoped>
/* 可以添加一些样式 */
</style>
