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

<script setup>
import * as echarts from "echarts";
import { onMounted, onBeforeUnmount, onActivated } from "vue";
const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "500px",
  },
});
const barChart = ref(null);
const myChart = ref(null);
function initChart() {
  setTimeout(() => {
    if (myChart.value === null) {
      myChart.value = echarts.init(barChart.value);
    }
    myChart.value.setOption(getChartData());
  }, 200);
}
// 处理图表数据
function getChartData() {
  let optionData = {
    tooltip: {
      trigger: "item",
      formatter: props.chartData.tooltipFormatter,
    },
    xAxis: {
      type: "value",
      splitLine: {
        show: false,
      },
      show: false,
    },
    grid: {
      containLabel: true,
    },
    yAxis: {
      type: "category",
      axisLabel: {
        formatter: function (value) {
          var maxLength = 8;
          if (value.length > maxLength) {
            return value.substring(0, maxLength) + "...";
          }
          return value;
        },
      },
      data: props.chartData.yAxisData,
      splitArea: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
        lineStyle: {
          color: "#000",
        },
      },
    },
    series: [
      {
        type: "bar",
        data: props.chartData.seriesData,
        // 设置柱状图的宽度
        barWidth: 20,
        // 柱状图颜色
        itemStyle: {
          color: "#569be5",
        },
      },
    ],
  };
  return optionData;
}
window.addEventListener("resize", function () {
  if (myChart.value) {
    myChart.value.resize();
  }
});
watch(
  () => props.chartData,
  (val) => {
    if (val) {
      initChart();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
onMounted(() => {
  initChart();
});
onActivated(() => {
  if (myChart.value) {
    myChart.value.resize();
  }
});
onBeforeUnmount(() => {
  if (myChart.value) {
    // 销毁echarts实例
    myChart.value.dispose();
    myChart.value = null;
  }
});
</script>
