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

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

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

const defaultColors = ["#1890ff", "#096dd9", "#0050b3", "#003a8c", "#002766"];

let resizeObserver;
const initChart = () => {
  const myChart = chart.init(chartContainer.value);
  if (!props.data) return;
  const option = {
    // legend: {
    //   left: "bottom",
    // },

  xAxis: {
    type: 'category',
      axisTick: false,
      axisLabel: {
        interval: 0,
        rotate: 30
      },
    data: props.data.map(v => v.name),
  },
  yAxis: {
    type: 'value'
  },
    series: [
      {
        type: "bar",
        data: props.data.map(v => v.value),
        color: props.colors?.length ? props.colors : defaultColors,
        barMaxWidth: '50',
        // barWidth: Math.floor((myChart.getWidth() - 20) / props.data.length) - 40,
        label: {
          show: true,
          position: "top",
          formatter: "{c}人",
        },
      },
    ],
  };
  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>


