<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(['name',"data", "legendData"]);

let resizeObserver;
const initChart = () => {
  console.log(props.data);

  if (!props.data) return;
  const myChart = chart.init(chartContainer.value);
  // console.log('max',max)
  const option = {
    legend: {
      data: props.legendData || [],
      top: "bottom",
      selectedMode: false
    },
    grid: {
      top: "10%",
      left: "10%",
      right: "5%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      // boundaryGap: true,
      axisTick: false,
      axisLine: {
        show: false
      },
      axisLabel: {
        interval: 0,
        rotate: 30
      },
      data: props.data.list.map(v => v.indicatorName)
    },
    yAxis: {

      // splitLine: {
      //   show: false
      // },
      // axisLine: { show: true },
      // axisLabel: { show: false },
      type: "value"
    },
    color: ["#1890ff", "#FF7F50"],
    series: props.legendData.map((legend, seriesIndex) => {

      return {
        name: legend,
        type: "bar",
        stack: "stack",
        data: props.data.value[seriesIndex],
        barWidth: 50,
        label: {
          show: true,
          // color: "#fff",
          formatter: params => {
            // console.log(params, max[params.dataIndex])
            return params.value
              ? `${params.value}人`
              : "";
          }
        }
      };
    })
  };
  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, props.legendData],
  () => {
    chartContainer.value && initChart();
  },
  { deep: true }
);

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

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