<template>
  <div class="app-container">
    <!-- 筛选区 -->
    <el-card shadow="never" class="filter-card">
      <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="TopN">
          <el-input-number v-model="queryForm.topN" :min="3" :max="50" style="width: 100px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- KPI 卡片 -->
    <el-row :gutter="16" class="mt-4">
      <el-col :span="6">
        <el-card shadow="hover" class="kpi-card">
          <el-statistic title="活跃测点数" :value="overview.monitorCount ?? '-'" suffix="个" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="kpi-card">
          <el-statistic title="平均温度" :value="overview.avgLatestTemp ?? '-'" :precision="2" suffix="℃" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="kpi-card kpi-high">
          <el-statistic title="最高温度" :value="overview.maxLatestTemp ?? '-'" :precision="2" suffix="℃">
            <template #suffix>
              <span class="text-xs">℃</span>
              <span v-if="overview.maxTempMonitorId" class="text-xs text-gray-400 ml-2">{{ overview.maxTempMonitorId }}</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="kpi-card kpi-low">
          <el-statistic title="最低温度" :value="overview.minLatestTemp ?? '-'" :precision="2" suffix="℃">
            <template #suffix>
              <span class="text-xs">℃</span>
              <span v-if="overview.minTempMonitorId" class="text-xs text-gray-400 ml-2">{{ overview.minTempMonitorId }}</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- TopN 排行 -->
    <el-row :gutter="16" class="mt-4">
      <el-col :span="12">
        <el-card shadow="never">
          <template #header><span class="font-bold">高温 Top{{ queryForm.topN }}</span></template>
          <div ref="highTopNChartRef" style="height: 320px" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never">
          <template #header><span class="font-bold">低温 Top{{ queryForm.topN }}</span></template>
          <div ref="lowTopNChartRef" style="height: 320px" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据新鲜度 -->
    <el-card shadow="never" class="mt-4">
      <template #header><span class="font-bold">数据新鲜度概览</span></template>
      <el-table :data="overview.freshnessList ?? []" stripe size="small" max-height="400">
        <el-table-column prop="monitorId" label="测点ID" width="160" />
        <el-table-column prop="monitorName" label="测点名称" width="200" />
        <el-table-column prop="temperature" label="当前温度" width="120" align="right">
          <template #default="{ row }">{{ row.temperature?.toFixed(2) }}℃</template>
        </el-table-column>
        <el-table-column prop="collectTime" label="采集时间" width="200" />
        <el-table-column prop="ageSeconds" label="延迟(秒)" width="120" align="right">
          <template #default="{ row }">
            <el-tag :type="row.ageSeconds < 60 ? 'success' : row.ageSeconds < 300 ? 'warning' : 'danger'" size="small">
              {{ row.ageSeconds }}s
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getTempOverview, type TempBoardOverviewVO, type TempBoardQuery } from '@/api/ems/report/tempBoard'

defineOptions({ name: 'TempBoardOverview' })

const timeRange = ref<[string, string]>(['', ''])
const queryForm = reactive<TempBoardQuery>({
  highTempThreshold: 35,
  lowTempThreshold: 10,
  topN: 10
})
const overview = ref<Partial<TempBoardOverviewVO>>({})
const loading = ref(false)

const highTopNChartRef = ref<HTMLElement>()
const lowTopNChartRef = ref<HTMLElement>()

/** 初始化默认时间范围：昨天8:30 ~ 今天8:30 */
function initDefaultTimeRange() {
  const now = new Date()
  // 结束时间：今天 8:30:00
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 30, 0)
  // 开始时间：昨天 8:30:00
  const start = new Date(end.getTime() - 24 * 3600 * 1000)
  const fmt = (d: Date) => {
    const pad = (n: number) => n.toString().padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(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 { data } = await getTempOverview(queryForm)
    overview.value = data
    await nextTick()
    renderTopNCharts()
  } finally {
    loading.value = false
  }
}

function handleReset() {
  queryForm.highTempThreshold = 35
  queryForm.lowTempThreshold = 10
  queryForm.topN = 10
  initDefaultTimeRange()
  handleQuery()
}

function renderTopNCharts() {
  // 高温 TopN 横向条形图
  if (highTopNChartRef.value && overview.value.highTempTopN) {
    const chart = echarts.init(highTopNChartRef.value)
    const data = overview.value.highTempTopN
    chart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 120, right: 40, top: 10, bottom: 20 },
      xAxis: { type: 'value', name: '℃' },
      yAxis: { type: 'category', data: data.map(d => d.monitorName || d.monitorId).reverse() },
      series: [{
        type: 'bar',
        data: data.map(d => d.temperature).reverse(),
        itemStyle: { color: '#f56c6c' },
        label: { show: true, position: 'right', formatter: '{c}℃' }
      }]
    })
  }
  // 低温 TopN 横向条形图
  if (lowTopNChartRef.value && overview.value.lowTempTopN) {
    const chart = echarts.init(lowTopNChartRef.value)
    const data = overview.value.lowTempTopN
    chart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 120, right: 40, top: 10, bottom: 20 },
      xAxis: { type: 'value', name: '℃' },
      yAxis: { type: 'category', data: data.map(d => d.monitorName || d.monitorId).reverse() },
      series: [{
        type: 'bar',
        data: data.map(d => d.temperature).reverse(),
        itemStyle: { color: '#409eff' },
        label: { show: true, position: 'right', formatter: '{c}℃' }
      }]
    })
  }
}

onMounted(() => {
  initDefaultTimeRange()
  handleQuery()
})
</script>

<style scoped>
.kpi-card { text-align: center; }
.kpi-high :deep(.el-statistic__number) { color: #f56c6c; }
.kpi-low :deep(.el-statistic__number) { color: #409eff; }
</style>
