<template>
  <div :style="{ width: width, height: height }" ref="basicBarChart"></div>
</template>

<script setup>
import * as echarts from "echarts";
import { onMounted, onBeforeUnmount, watch, nextTick, onActivated } from "vue";
import { formatSecond } from "@/hooks/formatTime";
const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "300px",
  },
});
const basicBarChart = ref(null);
const myChart = ref(null);
function init() {
  setTimeout(() => {
    if (myChart.value === null) {
      myChart.value = echarts.init(basicBarChart.value);
    }

    const option = {
      title: {
        text: props.chartData.title,
        left: "center",
      },
      tooltip: {
        trigger: "item",
        formatter: function (params) {
          let result = params.name + "：" + "<br>" + formatSecond(params.value);
          return result;
        },
      },
      xAxis: {
        type: "category",
        name: props.chartData.xAxisName,
        data: props.chartData.xAxisData,
        axisLabel: {
          formatter: props.chartData.axisLabel,
        },
      },
      yAxis: {
        type: "value",
        name: props.chartData.yAxisName,
        splitNumber: 5, // 设置刻度分割数量，自行调整
        axisLabel: {
          formatter: function (value) {
            let hours = (value / 3600).toFixed(2); // 将秒转换为小时
            return hours;
          },
        },
      },
      series: [
        {
          data: props.chartData.seriesData,
          type: "bar",
        },
      ],
    };
    myChart.value.setOption(option);
  }, 200);
}
onMounted(() => {
  init();
});
watch(
  () => props.chartData,
  (val) => {
    if (val) {
      init();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
window.addEventListener("resize", function () {
  if (myChart.value !== null) {
    myChart.value.resize();
  }
});
onActivated(() => {
  if (myChart.value) {
    myChart.value.resize();
  }
});
onBeforeUnmount(() => {
  if (myChart.value) {
    // 销毁echarts实例
    myChart.value.dispose();
  }
});
</script>
