<script setup lang="ts">
import { computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent, DataZoomComponent } from 'echarts/components'
import VChart from 'vue-echarts'

use([CanvasRenderer, LineChart, GridComponent, LegendComponent, TooltipComponent, DataZoomComponent])

export interface WatchTrendPoint {
  recorded_at?: string
  server_id?: number
  cpu_pct?: number | null
  mem_pct?: number | null
  disk_pct?: number | null
  net_up_bps?: number | null
  net_down_bps?: number | null
  disk_read_bps?: number | null
  disk_write_bps?: number | null
}

const props = withDefaults(defineProps<{
  points: WatchTrendPoint[]
  series: Array<'cpu_pct' | 'mem_pct' | 'disk_pct' | 'net_up_bps' | 'net_down_bps'>
  height?: number
}>(), {
  height: 360,
})

const labels: Record<string, string> = {
  cpu_pct: 'CPU %',
  mem_pct: '内存 %',
  disk_pct: '磁盘 %',
  net_up_bps: '上行 B/s',
  net_down_bps: '下行 B/s',
  disk_read_bps: '磁盘读 B/s',
  disk_write_bps: '磁盘写 B/s',
}

const chartOption = computed(() => {
  const xs = props.points.map((p) => p.recorded_at || '')
  const series = props.series.map((key) => ({
    name: labels[key] || key,
    type: 'line',
    showSymbol: false,
    smooth: true,
    data: props.points.map((p) => p[key] ?? null),
  }))
  return {
    tooltip: { trigger: 'axis' },
    legend: { type: 'scroll', top: 0 },
    grid: { left: 48, right: 16, top: 40, bottom: 56 },
    dataZoom: [{ type: 'inside' }, { type: 'slider', height: 18, bottom: 8 }],
    xAxis: { type: 'category', data: xs, axisLabel: { showMaxLabel: true } },
    yAxis: { type: 'value', scale: true },
    series,
  }
})
</script>

<template>
  <v-chart
    class="watch-trend-chart"
    :style="{ height: `${height}px` }"
    :option="chartOption"
    :update-options="{ notMerge: true }"
    autoresize
  />
</template>

<style scoped>
.watch-trend-chart {
  width: 100%;
}
</style>
