<template>
  <div class="page">
  <div class="chart-container">
    <div ref="spectrumChartRef" class="chart"></div>
  </div>
    </div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import { onMounted, onBeforeUnmount, ref, watch, nextTick } from "vue";

interface TimeDomainItem {
  Time: number;
  Val: number;
}

interface Props {
  rawData: TimeDomainItem[];
}

const props = defineProps<Props>();

const spectrumChartRef = ref<HTMLDivElement | null>(null);
let myChart: echarts.ECharts | null = null;

const defaultData = Array.from({ length: 10 }, (_, i) => [i, 0]);

onMounted(async () => {
  await nextTick();
  initChart();
  window.addEventListener("resize", resizeChart);
});

watch(
  () => props.rawData,
  () => updateChart(),
  { immediate: true }
);

function initChart() {
  if (!spectrumChartRef.value) return;
  myChart = echarts.init(spectrumChartRef.value);
  updateChart();
}

function updateChart() {
  if (!myChart) return;

  let data: [number, number][] = [];

  if (props.rawData && props.rawData.length > 0) {
    data = props.rawData.map((item) => [item.Time, item.Val]);
  } else {
    data = defaultData;
  }

  const xMax = data.length > 0 ? data[data.length - 1][0] : 10;

const option: echarts.EChartsOption = {
  backgroundColor: '#ffffff', // 设置背景为白色
  grid: { left: 50, right: 30, top: 20, bottom: 20, containLabel: true },
  graphic: [
    {
      type: "text",
      left: 10,
      top: "center",
      rotation: Math.PI / 2,
      style: { text: "时域波形", font: "16px sans-serif", fill: "#000" },
    },
  ],
  tooltip: { trigger: "axis" },
  xAxis: {
    type: "value",
    name: "时间",
    nameLocation: "middle",
    nameGap: 25,
    min: 0,
    max: xMax,
    axisLabel: { formatter: "{value}" },
  },
  yAxis: {
    type: "value",
    name: "值",
    nameLocation: "middle",
    nameGap: 40,
  },
  series: [
    {
      type: "line",
      showSymbol: false,
      data,
      lineStyle: {
        width: 2,
        type: props.rawData && props.rawData.length > 0 ? "solid" : "dashed",
        color: "#1e90ff",
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "rgba(30,144,255,0.5)" },
          { offset: 1, color: "rgba(30,144,255,0.05)" },
        ]),
      },
    },
  ],
};


  myChart.setOption(option);
}

function resizeChart() {
  myChart?.resize();
}

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style lang="scss" scoped>
.chart-container {
  width: 948px;
  height: 100%;
}
.chart {
  width: 100%;
  height: 220px;
}
.page {
  padding: 6px 0 0 0;
}
</style>
