<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form :inline="true" :model="queryForm" size="small">
        <el-form-item label="时间范围">
          <el-date-picker v-model="timeRange" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" style="width: 380px" />
        </el-form-item>
        <el-form-item label="高温阈值">
          <el-input-number v-model="queryForm.highTempThreshold" :min="0" :max="100" :precision="1" style="width: 120px" />
          <span class="ml-1 text-xs text-gray-400">℃</span>
        </el-form-item>
        <el-form-item label="低温阈值">
          <el-input-number v-model="queryForm.lowTempThreshold" :min="-50" :max="50" :precision="1" style="width: 120px" />
          <span class="ml-1 text-xs text-gray-400">℃</span>
        </el-form-item>
        <el-form-item label="温升阈值">
          <el-input-number v-model="queryForm.rapidRiseThreshold" :min="0.1" :max="10" :precision="1" :step="0.1" style="width: 120px" />
          <span class="ml-1 text-xs text-gray-400">℃/min</span>
        </el-form-item>
        <el-form-item label="抖动阈值">
          <el-input-number v-model="queryForm.stddevThreshold" :min="0.1" :max="10" :precision="1" :step="0.1" style="width: 120px" />
          <span class="ml-1 text-xs text-gray-400">σ</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 异常统计卡片 -->
    <el-row :gutter="16" class="mt-4">
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card kpi-danger">
          <el-statistic title="高温事件" :value="highTempList.length" />
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card kpi-primary">
          <el-statistic title="低温事件" :value="lowTempList.length" />
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card kpi-warning">
          <el-statistic title="温升过快" :value="rapidRiseList.length" />
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card kpi-purple">
          <el-statistic title="温度抖动" :value="jitterList.length" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 高温事件 + 低温事件 -->
    <el-row :gutter="16" class="mt-4">
      <el-col :xs="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <el-tag type="danger" size="small">高温事件明细</el-tag>
              <HelpButton title="异常分析 — 高温事件" :content="ANOMALY_HELP" />
            </div>
          </template>
          <el-table :data="highTempList" stripe size="small" max-height="320">
            <el-table-column prop="monitorName" label="测点" show-overflow-tooltip />
            <el-table-column prop="temperature" label="温度" width="80" align="right">
              <template #default="{ row }"><span class="text-red-500 font-bold">{{ row.temperature?.toFixed(2) }}</span></template>
            </el-table-column>
            <el-table-column prop="collectTime" label="时间" width="160" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <el-tag type="primary" size="small">低温事件明细</el-tag>
              <HelpButton title="异常分析 — 低温事件" :content="ANOMALY_HELP" />
            </div>
          </template>
          <el-table :data="lowTempList" stripe size="small" max-height="320">
            <el-table-column prop="monitorName" label="测点" show-overflow-tooltip />
            <el-table-column prop="temperature" label="温度" width="80" align="right">
              <template #default="{ row }"><span class="text-blue-500 font-bold">{{ row.temperature?.toFixed(2) }}</span></template>
            </el-table-column>
            <el-table-column prop="collectTime" label="时间" width="160" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 连续高温时段 -->
    <el-card shadow="never" class="mt-4">
      <template #header>
        <div class="card-header">
          <span class="font-bold">连续高温时段</span>
          <HelpButton title="连续高温时段" :content="ANOMALY_HELP" />
        </div>
      </template>
      <el-table :data="continuousList" stripe size="small" max-height="300">
        <el-table-column prop="monitorId" label="测点ID" width="150" />
        <el-table-column prop="monitorName" label="测点名称" width="180" />
        <el-table-column prop="startTime" label="开始时间" width="200" />
        <el-table-column prop="endTime" label="结束时间" width="200" />
        <el-table-column prop="maxTemp" label="最高温" width="100" align="right">
          <template #default="{ row }"><span class="text-red-500 font-bold">{{ row.maxTemp?.toFixed(2) }}℃</span></template>
        </el-table-column>
        <el-table-column prop="sampleCount" label="持续样本数" width="100" align="right" />
      </el-table>
    </el-card>

    <!-- 温升过快 + 温度抖动 -->
    <el-row :gutter="16" class="mt-4">
      <el-col :xs="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <el-tag type="warning" size="small">温升过快事件</el-tag>
              <HelpButton title="温升过快事件" :content="ANOMALY_HELP" />
            </div>
          </template>
          <el-table :data="rapidRiseList" stripe size="small" max-height="320">
            <el-table-column prop="monitorName" label="测点" show-overflow-tooltip />
            <el-table-column prop="risePerMin" label="温升速率" width="90" align="right">
              <template #default="{ row }"><span class="text-orange-500 font-bold">{{ row.risePerMin?.toFixed(2) }}</span></template>
            </el-table-column>
            <el-table-column prop="collectTime" label="时间" width="160" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <el-tag type="info" size="small">温度抖动异常（按小时）</el-tag>
              <HelpButton title="温度抖动异常" :content="ANOMALY_HELP" />
            </div>
          </template>
          <el-table :data="jitterList" stripe size="small" max-height="320">
            <el-table-column prop="monitorName" label="测点" show-overflow-tooltip />
            <el-table-column prop="tempStddev" label="标准差" width="80" align="right">
              <template #default="{ row }"><span class="text-purple-500 font-bold">{{ row.tempStddev?.toFixed(4) }}</span></template>
            </el-table-column>
            <el-table-column prop="statTime" label="时段" width="160" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getHighTempEvents, getLowTempEvents, getContinuousHighTemp, getRapidRiseEvents, getJitterAnomalies } from '@/api/ems/report/tempBoard'
import type { TempBoardQuery, TempBoardAnomalyVO } from '@/api/ems/report/tempBoard'
import HelpButton from '../components/HelpButton.vue'
import { ANOMALY_HELP } from '../components/helpContent'

defineOptions({ name: 'TempBoardAnomaly' })

const timeRange = ref<[string, string]>(['', ''])
const queryForm = reactive<TempBoardQuery>({ highTempThreshold: 35, lowTempThreshold: 10, rapidRiseThreshold: 1.0, stddevThreshold: 2.0 })
const loading = ref(false)
const highTempList = ref<TempBoardAnomalyVO[]>([])
const lowTempList = ref<TempBoardAnomalyVO[]>([])
const continuousList = ref<TempBoardAnomalyVO[]>([])
const rapidRiseList = ref<TempBoardAnomalyVO[]>([])
const jitterList = ref<TempBoardAnomalyVO[]>([])

/** 初始化默认时间范围：昨天8:30 ~ 今天8:30 */
function initTimeRange() {
  const now = new Date()
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 30, 0)
  const start = new Date(end.getTime() - 24 * 3600 * 1000)
  const p = (n: number) => n.toString().padStart(2, '0')
  const fmt = (d: Date) => `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
  timeRange.value = [fmt(start), fmt(end)]
}

async function handleQuery() {
  if (timeRange.value?.[0]) { queryForm.startTime = timeRange.value[0]; queryForm.endTime = timeRange.value[1] }
  loading.value = true
  try {
    const [htRes, ltRes, cRes, rrRes, jRes] = await Promise.all([
      getHighTempEvents(queryForm), getLowTempEvents(queryForm),
      getContinuousHighTemp(queryForm), getRapidRiseEvents(queryForm), getJitterAnomalies(queryForm)
    ])
    highTempList.value = htRes.data; lowTempList.value = ltRes.data
    continuousList.value = cRes.data; rapidRiseList.value = rrRes.data; jitterList.value = jRes.data
  } finally { loading.value = false }
}

onMounted(() => { initTimeRange(); handleQuery() })
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.kpi-card {
  text-align: center;
}
.kpi-danger :deep(.el-statistic__number) { color: #f56c6c }
.kpi-primary :deep(.el-statistic__number) { color: #409eff }
.kpi-warning :deep(.el-statistic__number) { color: #e6a23c }
.kpi-purple :deep(.el-statistic__number) { color: #9b59b6 }
</style>
