<script setup lang="ts" name="HomeCharts">
import { ref, onMounted, watch, nextTick, inject } from "vue";
import * as echarts from "echarts";

const homeChartData: any = inject("homeChartData");
const barChart = ref();

let myChart;
watch(
  () => homeChartData,
  (newVal) => {
    nextTick().then(() => {
      myChart = echarts.init(barChart.value);

      if (newVal && myChart) {
        myChart.setOption({
          title: {
            text: '磁盘空间',
            textStyle: {
              color: "#7a8495",
            }
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#808eb7",
                width: 2,
              },
            },
          },
          yAxis: {
            type: "category",
            axisLine: {
              lineStyle: {
                color: "#808eb7",
                width: 2,
              },
            },
            splitLine: {
              //分割线配置
              lineStyle: {
                color: "#AAAAAA56",
              },
            },
            data: homeChartData.xList,
          },
          series: [
            {
              name: "已使用",
              type: "bar",
              barMaxWidth: 30,
              zlevel: 10,
              data: homeChartData.yList1,
              itemStyle: {
                normal: {
                  color: (params) => {
                    return generateRandomColors();
                  },
                },
              },
            },
            {
              name: "总空间",
              type: "bar",
              silent: true,
              barGap: '-100%',
              barMaxWidth: 30,
              data: homeChartData.yList2,
              itemStyle: {
                normal: {
                  color: "#dfe1e3",
                },
              },
            },
          ],
        });
      }
    });
  },
  { deep: true, immediate: true }
);

const generateRandomColors = () => {
  const hue = Math.floor(Math.random() * 360);
    const saturation = Math.floor(Math.random() * 30) + 70;
    const lightness = Math.floor(Math.random() * 20) + 40;
    const color = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
    return color;
}

onMounted(() => {
  myChart = echarts.init(barChart.value);
});
</script>
<template>
  <div class="echarts-wrapper">
    <div ref="barChart" id="barChart" class="bar-chart" />
  </div>
</template>
<style lang="scss" scoped>
.echarts-wrapper {
  height: 100%;
  width: 100%;
  .bar-chart {
    height: 100%;
    width: 100%;
  }
}
</style>