<template>
  <div ref="lineChartRef" class="chart"></div>
</template>

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

defineOptions({ name: 'BreathLineChart' })

const props = withDefaults(
  defineProps<{
    data: number[]
  }>(),
  {
    data: () => [],
  }
)

const lineChartRef = ref<HTMLDivElement | null>(null)
const lineChart = ref<echarts.ECharts | null>(null)
const option = ref<echarts.EChartsOption>()

onMounted(() => {
  lineChart.value = echarts.init(lineChartRef.value!)

  // -----------------------------
  // 配置显示的时间和数据点
  // -----------------------------
  const totalSeconds = 60 // 显示1分钟的数据
  const step = 1 // 每秒一个点
  const maxPoints = totalSeconds / step + 1
  const xAxisData = Array.from({ length: maxPoints }, (_, i) => i * step)
  const lineData: number[] = [] // 初始基准数据

  // 初始化图表配置
  option.value = {
    title: [
      {
        text: '呼吸率曲线', // 主标题
        left: 'center',
        top: 20,
        textStyle: { fontSize: 14 },
      },
      {
        text: 'BPM: 0 次/分钟', // 实时呼吸率显示
        left: 'center',
        top: 50, // 放在主标题下方
        textStyle: { fontSize: 12, color: '#007bff' },
        id: 'bpmText',
      },
      {
        text: '时间 (秒)', // X轴文字
        left: 'right',
        top: 'bottom',
        textStyle: { fontSize: 12, color: '#888888', fontWeight: 'normal' },
      },
    ],
    grid: { left: 60, right: 20, top: 80, bottom: 50 }, // 图表边距
    xAxis: { type: 'category', data: xAxisData, boundaryGap: false, splitLine: { show: false } },
    yAxis: {
      type: 'value',
      min: 0,
      max: 40,
      name: '呼吸率（次）',
      nameLocation: 'end',
      nameGap: 20,
      nameTextStyle: { fontSize: 12, color: '#888888', fontWeight: 'normal' },
      splitLine: { show: true },
    },
    series: [
      {
        type: 'line' as const,
        smooth: true,
        symbol: 'none' as const,
        lineStyle: { color: '#007bff', width: 2 }, // 折线样式
        data: lineData.slice(),
      },
    ],
    animation: true,
    animationDuration: 100,
  }

  lineChart.value.setOption(option.value)

  // 自适应窗口大小
  window.addEventListener('resize', () => lineChart.value!.resize())
})

watch(
  () => props.data,
  (newData) => {
    const list = newData
    if (list.length > 60) {
      list.shift()
    }
    lineChart.value!.setOption(
      {
        series:
          option.value && option.value.series
            ? Array.isArray(option.value.series)
              ? [{ ...option.value.series[0], data: list }]
              : [{ ...option.value.series, data: list }]
            : [{ data: list }], // 更新折线数据
        title: [{}, { text: `BPM: ${list && list.length && list[list.length - 1]} 次/分钟` }, {}], // 更新实时BPM
      },
      { notMerge: false }
    )
  },
  { deep: true }
)
</script>

<style scoped lang="less">
.chart {
  width: 100%;
  height: 300px;
  background: #fff;
  border-radius: 4px;
}
</style>
