<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 :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card">
          <el-statistic title="活跃测点数" :value="overview.monitorCount ?? '-'" suffix="个" />
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card">
          <el-statistic title="平均温度" :value="overview.avgLatestTemp ?? '-'" :precision="2" suffix="℃" />
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card kpi-high">
          <el-statistic title="最高温度" :value="overview.maxLatestTemp ?? '-'" :precision="2" />
          <div v-if="overview.maxTempMonitorId" class="text-xs text-gray-400 mt-1">{{ overview.maxTempMonitorId }}</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card shadow="hover" class="kpi-card kpi-low">
          <el-statistic title="最低温度" :value="overview.minLatestTemp ?? '-'" :precision="2" />
          <div v-if="overview.minTempMonitorId" class="text-xs text-gray-400 mt-1">{{ overview.minTempMonitorId }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- TopN 排行 -->
    <el-row :gutter="16" class="mt-4">
      <el-col :xs="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="font-bold">高温 Top{{ queryForm.topN }}</span>
              <HelpButton title="总览 — 高温 TopN 排行" :content="OVERVIEW_HELP" />
            </div>
          </template>
          <div ref="highTopNChartRef" class="chart-container" />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="font-bold">低温 Top{{ queryForm.topN }}</span>
              <HelpButton title="总览 — 低温 TopN 排行" :content="OVERVIEW_HELP" />
            </div>
          </template>
          <div ref="lowTopNChartRef" class="chart-container" />
        </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="OVERVIEW_HELP" />
        </div>
      </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 } from '@/api/ems/report/tempBoard'
import type { TempBoardQuery, TempBoardOverviewVO } from '@/api/ems/report/tempBoard'
import HelpButton from '../components/HelpButton.vue'
import { OVERVIEW_HELP } from '../components/helpContent'
import { useChartResize } from '../components/useChartResize'

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>()

const { getChart } = useChartResize(highTopNChartRef, lowTopNChartRef)

/** 初始化默认时间范围：昨天8:30 ~ 今天8:30 */
function initDefaultTimeRange() {
  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 fmt = (d: Date) => {
    const p = (n: number) => n.toString().padStart(2, '0')
    return `${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 { data } = await getTempOverview(queryForm)
    overview.value = data
    await nextTick()
    renderTopNCharts()
  } finally { loading.value = false }
}

function handleReset() {
  Object.assign(queryForm, { highTempThreshold: 35, lowTempThreshold: 10, topN: 10 })
  initDefaultTimeRange()
  handleQuery()
}

function renderTopNCharts() {
  // 高温 TopN 横向条形图
  const highChart = getChart(highTopNChartRef)
  if (highChart && overview.value.highTempTopN) {
    const d = overview.value.highTempTopN
    highChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params: any) => `${params[0].name}<br/>温度: <b style="color:#f56c6c">${params[0].value}℃</b>`
      },
      grid: { left: 120, right: 50, top: 10, bottom: 20 },
      xAxis: { type: 'value', name: '℃', axisLabel: { color: '#666' } },
      yAxis: { type: 'category', data: d.map(i => i.monitorName || i.monitorId).reverse(), axisLabel: { color: '#333' } },
      series: [{
        type: 'bar',
        data: d.map(i => i.temperature).reverse(),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#f56c6c' },
            { offset: 1, color: '#fab6b6' }
          ]),
          borderRadius: [0, 4, 4, 0]
        },
        label: { show: true, position: 'right', formatter: '{c}℃', color: '#f56c6c', fontSize: 12 },
        barMaxWidth: 24
      }]
    })
  }
  // 低温 TopN 横向条形图
  const lowChart = getChart(lowTopNChartRef)
  if (lowChart && overview.value.lowTempTopN) {
    const d = overview.value.lowTempTopN
    lowChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params: any) => `${params[0].name}<br/>温度: <b style="color:#409eff">${params[0].value}℃</b>`
      },
      grid: { left: 120, right: 50, top: 10, bottom: 20 },
      xAxis: { type: 'value', name: '℃', axisLabel: { color: '#666' } },
      yAxis: { type: 'category', data: d.map(i => i.monitorName || i.monitorId).reverse(), axisLabel: { color: '#333' } },
      series: [{
        type: 'bar',
        data: d.map(i => i.temperature).reverse(),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#409eff' },
            { offset: 1, color: '#a0cfff' }
          ]),
          borderRadius: [0, 4, 4, 0]
        },
        label: { show: true, position: 'right', formatter: '{c}℃', color: '#409eff', fontSize: 12 },
        barMaxWidth: 24
      }]
    })
  }
}

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

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.chart-container {
  width: 100%;
  min-height: 320px;
}
.kpi-card { text-align: center }
.kpi-high :deep(.el-statistic__number) { color: #f56c6c }
.kpi-low :deep(.el-statistic__number) { color: #409eff }
</style>
