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

let resizeObserver;
const initChart = () => {
  if (!props.data || !props.data?.data[0]) return;
  const myChart = chart.init(chartContainer.value);
  console.log(props.data);
  const max = props.data.data[0].map((v, k) => {
    let sum = 0;
    props.legendData.forEach((v2, k2) => {
      sum += props.data.data[k2][k];
    });
    return sum;
  });
  console.log("max", max);
  const option = {
    legend: {
      // data: props.legendData || [],
      top: "bottom",
      selectedMode: false
    },
    grid: {
      top: "20",
      left: "5%",
      right: "5%",
      bottom: "30",
      containLabel: true
    },
    xAxis: {
      splitLine: {
        show: false
      },
      axisLabel: { show: false },
      type: "value"
    },
    yAxis: {
      type: "category",
      boundaryGap: true,
      axisTick: false,
      axisLine: {
        show: false
      },
      data: props.data.name
    },
    color: [
      "#9b59b6", // 已确诊 - 紫色
      "#e74c3c", // 有明显风险 - 红色
      "#f39c12", // 有一定风险 - 橙色
      "#2ecc71", // 暂无风险 - 绿色
      "#a5a5a5", // 缺乏评估数据 - 蓝色
      "#fff" // 补齐
    ],
    // tooltip: {},
    series: [
      ...props.legendData.map((legend, index) => {
        console.log(max[index], props.data.data);
        return {
          name: legend,
          type: "bar",
          stack: "total",
          data: props.data.data[index].map((v2, k2) =>
            parseFloat(((v2 / max[k2]) * 100).toFixed(2))
          ),
          itemStyle: {
            //   barBorderRadius: 2 // 设置柱子的圆角，分别对应左上、右上、右下、左下
          },
          label: {
            show: true,
            fontSize: 14,
            // color: "#fff",
            // position: "bottom",
            formatter: params => {
              // console.log(params, max[params.dataIndex]);
              //  占比${params.value}%
              // 人
              const val = props.data.data[index][params.dataIndex]
              return params.value
                ? ((val / max[params.dataIndex] * 100) > 5 ? `${val}人` : val)
                : "";
            }
          }
        };
      })
    ]
  };
  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>
