<template>
  <div class="list">
    <div v-for="item in items" :key="item.id" class="list-item">
      <div>
        <div><b>{{ item.pressure.toFixed(3) }} MPa</b> · <span class="sub">{{ formatTime(item.timestamp) }}</span></div>
        <div class="sub">电压 {{ item.voltage.toFixed(3) }} V · 设备 {{ item.device_id }}</div>
      </div>
      <div :class="(isAlarm(item) ? 'badge-err' : 'badge-ok')">{{ isAlarm(item) ? '报警' : '正常' }}</div>
    </div>
    <div v-if="!loading && items.length === 0" class="sub">暂无记录</div>
    <div v-if="loading" class="sub">加载中...</div>
  </div>
</template>

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

const props = defineProps<{ deviceId?: string, minPressure?: number, maxPressure?: number }>()
const items = ref<any[]>([])
const loading = ref(false)

function formatTime(iso: string) {
  return new Date(iso).toLocaleString()
}

function isAlarm(r: any) {
  const min = props.minPressure
  const max = props.maxPressure
  if (min != null && r.pressure < min) return true
  if (max != null && r.pressure > max) return true
  return false
}

async function load() {
  loading.value = true
  const params: any = { page: 1, page_size: 100 }
  if (props.deviceId) params.device_id = props.deviceId
  if (props.minPressure != null) params.min_pressure = props.minPressure
  if (props.maxPressure != null) params.max_pressure = props.maxPressure
  const { data } = await axios.get('/api/alarms', { params })
  if (data?.ok) {
    items.value = data.items
  }
  loading.value = false
}

onMounted(load)
watch(() => [props.deviceId, props.minPressure, props.maxPressure], load)
</script>

<style scoped>
</style>


