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

<script setup>
import { ref, onMounted, onBeforeUnmount, onActivated } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "300px",
  },
});
const categoryChart = ref(null);
let myChart = null; //普通变量接收echart,否则tooltip不展示

// 图表初始化
function initChart() {
  setTimeout(() => {
    if (myChart === null) {
      myChart = echarts.init(categoryChart.value);
    }
    myChart.setOption(getChartData());
  }, 200);
}
// 处理图表数据
function getChartData() {
  let optionData = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: props.chartData.legendData,
    },
    grid: {
      left: "3%",
      right: "8%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      name: props.chartData.xAxisName,
      boundaryGap: false,
      data: props.chartData.xAxisData,
      axisLabel: {
        formatter: props.chartData.axisLabel,
      },
    },
    yAxis: {
      type: "value",
      name: props.chartData.yAxisName,
    },
    series: [],
  };
  props.chartData.seriesData.forEach((item, index) => {
    optionData.series.push({
      name: props.chartData.legendData[index],
      smooth: true,
      type: "line",
      data: item,
      stack: "Total",
      animationDuration: 2800,
    });
  });
  return optionData;
}

onMounted(() => {
  initChart();
});
window.addEventListener("resize", function () {
  if (myChart) {
    myChart.resize();
  }
});
watch(
  () => props.chartData,
  (val) => {
    if (val) {
      initChart();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
onActivated(() => {
  if (myChart) {
    myChart.resize();
  }
});
onBeforeUnmount(() => {
  if (myChart) {
    // 销毁echarts实例
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style></style>
