<template>
  <transition name="fade" mode="out-in">
    <div v-if="state.loaded" key="loaded">
      <div class="value">{{ displayPressure }}<span style="font-size:18px;margin-left:6px;">MPa</span></div>
      <div class="sub">电压：{{ last?.voltage?.toFixed(3) }} V</div>
      <div class="sub">时间：{{ displayTime }}</div>
    </div>
    <div v-else key="loading" class="sub">加载中...</div>
  </transition>
</template>

<script setup lang="ts">
import { onMounted, reactive, watch, computed } from 'vue'
import axios from 'axios'

const props = defineProps<{ deviceId?: string }>()

type Reading = {
  id: number
  device_id: string
  timestamp: string
  pressure: number
  voltage: number
}

const state = reactive<{ loaded: boolean } & { last: Reading | null }>({ loaded: false, last: null })

const last = computed(() => state.last)
const displayPressure = computed(() => last.value ? last.value.pressure.toFixed(3) : '--')
const displayTime = computed(() => last.value ? new Date(last.value.timestamp).toLocaleString() : '--')

async function fetchLatest() {
  const params: any = {}
  if (props.deviceId) params.device_id = props.deviceId
  const { data } = await axios.get('/api/readings/latest', { params })
  if (data?.ok) {
    state.last = data.item
  }
  state.loaded = true
}

onMounted(fetchLatest)
watch(() => props.deviceId, fetchLatest)
</script>

<style scoped>
</style>


