<template>
  <div ref="chartDustRef" class="chart-line"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { getDustLineOption } from "@/utils/chart";

const props = defineProps({
  // 表格数据
  dustLineInfo: {
    type: Array,
    required: true,
    default: () => [],
  },
});

const chartDustRef = ref(null);
let chartInstance = null;

const initChart = () => {
  if (chartDustRef.value) {
    let xData = [];
    let seriesData = [];
    if (props.dustLineInfo) {
      props.dustLineInfo.forEach((i) => {
        xData.push(i.replaceTime);
        seriesData.push(i.period);
      });
    }
    chartInstance = echarts.init(chartDustRef.value);
    const option = getDustLineOption(xData, seriesData);
    nextTick(() => {
      // DOM 更新完成后执行
      chartInstance.setOption(option);
    });
  }
};

watch(
  () => props.dustLineInfo,
  () => {
    initChart();

  },
  { deep: true }
);

onMounted(() => {
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
});

onBeforeUnmount(() => {
  chartInstance?.dispose();
});
</script>

<style lang="scss"  scoped>
.chart-line {
  margin-top: 20px;
  canvas {
    width: 100%;
    height: 100%;
  }
}
</style>
