<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>
          <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="24" :sm="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="font-bold">测点平均温度排行</span>
              <HelpButton title="测点平均温度排行" :content="COMPARISON_HELP" />
            </div>
          </template>
          <div ref="avgRankChartRef" 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">测点稳定性排行（标准差升序）</span>
              <HelpButton title="测点稳定性排行" :content="COMPARISON_HELP" />
            </div>
          </template>
          <div ref="stabilityChartRef" class="chart-container" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 今日vs昨日 + 波动幅度 -->
    <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">今日 vs 昨日 温度对比</span>
              <HelpButton title="今日vs昨日温度对比" :content="COMPARISON_HELP" />
            </div>
          </template>
          <div ref="dailyDiffChartRef" 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">波动幅度对比</span>
              <HelpButton title="波动幅度对比" :content="COMPARISON_HELP" />
            </div>
          </template>
          <div ref="fluctuationChartRef" 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="COMPARISON_HELP" />
        </div>
      </template>
      <el-table :data="peakList" stripe size="small" max-height="400">
        <el-table-column prop="monitorId" label="测点ID" width="150" />
        <el-table-column prop="monitorName" label="测点名称" width="200" />
        <el-table-column prop="maxTemp" label="峰值温度" width="120" align="right">
          <template #default="{ row }"><span class="font-bold">{{ row.maxTemp?.toFixed(2) }}℃</span></template>
        </el-table-column>
        <el-table-column prop="avgTemp" label="平均温度" width="120" align="right">
          <template #default="{ row }">{{ row.avgTemp?.toFixed(2) }}℃</template>
        </el-table-column>
        <el-table-column prop="tempRange" label="波动幅度" width="120" align="right">
          <template #default="{ row }">{{ row.tempRange?.toFixed(2) }}℃</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, type Ref } from 'vue'
import * as echarts from 'echarts'
import { getAvgTempRanking, getStabilityRanking, getDailyDiff, getPeakCompare, getFluctuationCompare } from '@/api/ems/report/tempBoard'
import type { TempBoardQuery, TempBoardComparisonVO } from '@/api/ems/report/tempBoard'
import HelpButton from '../components/HelpButton.vue'
import { COMPARISON_HELP } from '../components/helpContent'
import { useChartResize } from '../components/useChartResize'

defineOptions({ name: 'TempBoardComparison' })

const timeRange = ref<[string, string]>(['', ''])
const queryForm = reactive<TempBoardQuery>({})
const loading = ref(false)
const peakList = ref<TempBoardComparisonVO[]>([])
const avgRankChartRef = ref<HTMLElement>()
const stabilityChartRef = ref<HTMLElement>()
const dailyDiffChartRef = ref<HTMLElement>()
const fluctuationChartRef = ref<HTMLElement>()

const { getChart } = useChartResize(avgRankChartRef, stabilityChartRef, dailyDiffChartRef, fluctuationChartRef)

/** 初始化默认时间范围：昨天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)]
}

function renderBarH(el: Ref<HTMLElement | undefined>, data: TempBoardComparisonVO[], field: string, colorStart: string, colorEnd: string, label: string) {
  const chart = getChart(el)
  if (!chart || !data.length) return
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => {
        const p = params[0]
        return `${p.name}<br/>${p.seriesName}: <b>${p.value}</b> ${label === '℃' ? '℃' : label === 'σ' ? 'σ' : ''}`
      }
    },
    legend: { show: false },
    grid: { left: 120, right: 50, top: 10, bottom: 20 },
    xAxis: { type: 'value', name: label, axisLabel: { color: '#666' } },
    yAxis: { type: 'category', data: data.map(d => d.monitorName || d.monitorId).reverse(), axisLabel: { color: '#333' } },
    series: [{
      type: 'bar',
      name: label,
      data: data.map(d => d[field as keyof TempBoardComparisonVO]).reverse(),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: colorStart },
          { offset: 1, color: colorEnd }
        ]),
        borderRadius: [0, 4, 4, 0]
      },
      label: { show: true, position: 'right', formatter: '{c}', color: '#666', fontSize: 12 },
      barMaxWidth: 24
    }]
  })
}

async function handleQuery() {
  if (timeRange.value?.[0]) { queryForm.startTime = timeRange.value[0]; queryForm.endTime = timeRange.value[1] }
  loading.value = true
  try {
    const [avgRes, stabRes, diffRes, peakRes, fluctRes] = await Promise.all([
      getAvgTempRanking(queryForm), getStabilityRanking(queryForm),
      getDailyDiff(queryForm), getPeakCompare(queryForm), getFluctuationCompare(queryForm)
    ])
    peakList.value = peakRes.data
    await nextTick()
    renderBarH(avgRankChartRef, avgRes.data, 'avgTemp', '#f5a623', '#f7c948', '℃')
    renderBarH(stabilityChartRef, stabRes.data, 'tempStddev', '#36cfc9', '#5ad8a6', 'σ')
    renderBarH(fluctuationChartRef, fluctRes.data, 'tempRange', '#409eff', '#69c0ff', '℃')
    // 今日vs昨日用分组柱图
    const chart = getChart(dailyDiffChartRef)
    if (chart && diffRes.data.length) {
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: (params: any) => {
            let html = `<b>${params[0].name}</b><br/>`
            params.forEach((p: any) => { html += `${p.marker} ${p.seriesName}: <b>${p.value}℃</b><br/>` })
            return html
          }
        },
        legend: { data: ['今日', '昨日'], top: 0, textStyle: { color: '#666' } },
        grid: { left: 120, right: 30, top: 40, bottom: 20 },
        yAxis: { type: 'category', data: diffRes.data.map(d => d.monitorName || d.monitorId), axisLabel: { color: '#333' } },
        xAxis: { type: 'value', name: '℃', axisLabel: { color: '#666' } },
        series: [
          {
            name: '今日', type: 'bar',
            data: diffRes.data.map(d => d.todayAvg),
            itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: '#409eff' }, { offset: 1, color: '#69c0ff' }]), borderRadius: [0, 4, 4, 0] },
            barMaxWidth: 20
          },
          {
            name: '昨日', type: 'bar',
            data: diffRes.data.map(d => d.yesterdayAvg),
            itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: '#909399' }, { offset: 1, color: '#b1b3b8' }]), borderRadius: [0, 4, 4, 0] },
            barMaxWidth: 20
          }
        ]
      })
    }
  } finally { loading.value = false }
}

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

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.chart-container {
  width: 100%;
  min-height: 360px;
}
</style>
