<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"]);

let resizeObserver;
const initChart = () => {
  const myChart = chart.init(chartContainer.value);
  const option = {
    legend: {
      left: "center",
      top: "bottom"
    },
    series: [
      {
        type: "pie",
        radius: ["30%", "50%"],
        data: props.data,
        color: [
          "#e74c3c", // 重点关爱人群 - 红色
          "#f39c12", // 一般健康人群 - 蓝色
          "#2ecc71" // 基本健康人群 - 绿色
        ],
        label: {
          show: true,
          // position: "inside",
          formatter: "{b} {d}%"
        }
      }
    ]
  };
  myChart.setOption(option);
  resizeObserver && resizeObserver.disconnect();
  // 使用 Resize Observer 监听元素大小变化
  resizeObserver = new ResizeObserver(() => {
    myChart.resize();
  });

  resizeObserver.observe(chartContainer.value);
};

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

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

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

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