<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.time);
        seriesData.push(i.value);
      });
    }
    chartInstance = echarts.init(chartDustRef.value);
    const option = getDustLineOption(xData, seriesData);
    nextTick(() => {
      // DOM 更新完成后执行
      chartInstance.setOption(option);
    });
  }
};

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

  },
  { deep: true }
);

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

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

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