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

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

const props = defineProps(["data"]);

const chartContainer = ref(null);
let resizeObserver;

const initChart = () => {
  const myChart = chart.init(chartContainer.value);
  const option = {
    series: [{
      name: "仪表盘",
      type: "gauge",
      detail: {
        formatter: "{value}%",
        fontSize: 16,
      },
      data: [
        {
          value: props.data.value,
          // name: props.data.name
        }
      ],
      axisLabel: {
        show: true,
        formatter: "{value}%",
        fontSize: 10
      },
      pointer: {
        width: 5
      },
      splitLine: {
        length: 5
      }
    }]
  };
  console.log(option);
  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 }
);

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

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