<template>
  <div ref="el" style="width:100%;height:300px;"></div>
</template>

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

const props = defineProps<{ deviceId?: string, rangeUnit: 'minutes'|'hours'|'days', rangeValue: number }>()

const el = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null

function buildRangeISO(unit: string, value: number) {
  const end = new Date()
  const start = new Date(end.getTime())
  const v = Math.max(1, value)
  if (unit === 'minutes') start.setMinutes(end.getMinutes() - v)
  else if (unit === 'hours') start.setHours(end.getHours() - v)
  else start.setDate(end.getDate() - v)
  return { start: start.toISOString(), end: end.toISOString() }
}

async function loadSeries() {
  if (!el.value) return
  const { start, end } = buildRangeISO(props.rangeUnit, props.rangeValue)
  const params: any = { start, end, page: 1, page_size: 1000, sort: 'asc' }
  if (props.deviceId) params.device_id = props.deviceId
  const { data } = await axios.get('/api/readings', { params })
  const items = data?.items ?? []
  const xs = items.map((r: any) => r.timestamp)
  const ys = items.map((r: any) => r.pressure)

  if (!chart) chart = echarts.init(el.value)
  chart.setOption({
    animation: true,
    tooltip: { trigger: 'axis' },
    grid: { left: 30, right: 18, top: 24, bottom: 28 },
    xAxis: { type: 'category', data: xs, axisLabel: { color: '#9bb0d3' } },
    yAxis: { type: 'value', name: 'MPa', axisLabel: { color: '#9bb0d3' } },
    series: [{
      type: 'line', data: ys, smooth: true,
      showSymbol: false,
      lineStyle: { width: 3, color: '#4f7cff' },
      areaStyle: { color: 'rgba(79,124,255,0.12)' }
    }]
  })
}

onMounted(loadSeries)
watch(() => [props.deviceId, props.rangeUnit, props.rangeValue], loadSeries)
onBeforeUnmount(() => { if (chart) { chart.dispose(); chart = null } })
</script>

<style scoped>
</style>


