<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 = () => {
  if (!props.data) return
  const myChart = chart.init(chartContainer.value);
  const xMax = props.data.reduce((total, item) => total + item.value, 0)
  const option = {
    xAxis: {
      type: 'value',
      position: 'top',
      max: 100,
      axisLabel: {
        show: false,
        formatter: '{value}%'
      },
    },
    grid: {
      left: '20%',
      top: '0%',
      bottom: '0%',
    },
    yAxis: {
      type: 'category',
      axisTick: {
        show: false // 隐藏X轴刻度
      },
      axisLine: {
        show: false // 隐藏X轴刻度
      },
      data: props.data.map(item => item.name),
    },
    series: [{
      data: props.data.map(item => parseFloat((item.value / xMax  * 100).toFixed(2))),
      type: 'bar',
      itemStyle: {
        color: '#1890ff' // 设置柱状图的颜色，可以根据需要自行更改
      },
      label: {
        show: true,
        formatter: '{c}%', // 将柱状图上的数值格式化为百分比
        position: 'right'
      }
    }]
  };

  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>
