<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 v-model="queryForm.monitorId" placeholder="输入测点ID" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 分钟趋势 -->
    <el-card shadow="never" class="mt-4">
      <template #header>
        <div class="card-header">
          <span class="font-bold">分钟趋势</span>
          <HelpButton title="分钟趋势" :content="TREND_HELP" />
        </div>
      </template>
      <div ref="minuteChartRef" class="chart-container-lg" />
    </el-card>

    <!-- 小时趋势 -->
    <el-card shadow="never" class="mt-4">
      <template #header>
        <div class="card-header">
          <span class="font-bold">小时趋势（含最高/最低温带）</span>
          <HelpButton title="小时趋势" :content="TREND_HELP" />
        </div>
      </template>
      <div ref="hourlyChartRef" class="chart-container-lg" />
    </el-card>

    <!-- 日均温趋势 -->
    <el-card shadow="never" class="mt-4">
      <template #header>
        <div class="card-header">
          <span class="font-bold">日均温趋势</span>
          <HelpButton title="日均温趋势" :content="TREND_HELP" />
        </div>
      </template>
      <div ref="dailyChartRef" class="chart-container" />
    </el-card>

    <!-- 峰谷时刻表 -->
    <el-card shadow="never" class="mt-4">
      <template #header>
        <div class="card-header">
          <span class="font-bold">峰谷时刻表</span>
          <HelpButton title="峰谷时刻表" :content="TREND_HELP" />
        </div>
      </template>
      <el-table :data="peakValleyList" stripe size="small">
        <el-table-column prop="monitorId" label="测点ID" width="150" />
        <el-table-column prop="monitorName" label="测点名称" width="180" />
        <el-table-column prop="peakTemp" label="峰值温度" width="100" align="right">
          <template #default="{ row }"><span class="text-red-500 font-bold">{{ row.peakTemp?.toFixed(2) }}℃</span></template>
        </el-table-column>
        <el-table-column prop="peakTime" label="峰值时间" width="200" />
        <el-table-column prop="valleyTemp" label="谷值温度" width="100" align="right">
          <template #default="{ row }"><span class="text-blue-500 font-bold">{{ row.valleyTemp?.toFixed(2) }}℃</span></template>
        </el-table-column>
        <el-table-column prop="valleyTime" label="谷值时间" width="200" />
      </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 { getMinuteTrend, getHourlyTrend, getDailyTrend, getPeakValley } from '@/api/ems/report/tempBoard'
import type { TempBoardQuery, TempBoardTrendVO } from '@/api/ems/report/tempBoard'
import HelpButton from '../components/HelpButton.vue'
import { TREND_HELP } from '../components/helpContent'
import { useChartResize } from '../components/useChartResize'

defineOptions({ name: 'TempBoardTrend' })

const timeRange = ref<[string, string]>(['', ''])
const queryForm = reactive<TempBoardQuery>({ monitorId: '' })
const loading = ref(false)
const minuteChartRef = ref<HTMLElement>()
const hourlyChartRef = ref<HTMLElement>()
const dailyChartRef = ref<HTMLElement>()
const peakValleyList = ref<TempBoardTrendVO[]>([])

const { getChart } = useChartResize(minuteChartRef, hourlyChartRef, dailyChartRef)

/** 初始化默认时间范围：昨天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 renderLineChart(el: Ref<HTMLElement | undefined>, data: TempBoardTrendVO[], options?: { showBand?: boolean }) {
  const chart = getChart(el)
  if (!chart || !data.length) return
  const times = data.map(d => d.statTime!)
  const series: any[] = [{
    name: '平均温度',
    type: 'line',
    data: data.map(d => d.avgTemp),
    smooth: true,
    lineStyle: { width: 2, color: '#409eff' },
    itemStyle: { color: '#409eff' },
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(64,158,255,0.3)' },
        { offset: 1, color: 'rgba(64,158,255,0.02)' }
      ])
    }
  }]
  if (options?.showBand) {
    series.push({
      name: '最高温度', type: 'line', data: data.map(d => d.maxTemp),
      lineStyle: { width: 1, type: 'dashed', color: '#f56c6c' },
      itemStyle: { color: '#f56c6c', opacity: 0.6 },
      symbol: 'none'
    })
    series.push({
      name: '最低温度', type: 'line', data: data.map(d => d.minTemp),
      lineStyle: { width: 1, type: 'dashed', color: '#67c23a' },
      itemStyle: { color: '#67c23a', opacity: 0.6 },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64,158,255,0.15)' },
          { offset: 1, color: 'rgba(64,158,255,0.05)' }
        ])
      },
      symbol: 'none'
    })
  }
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        let html = `<b>${params[0].axisValue}</b><br/>`
        params.forEach((p: any) => { html += `${p.marker} ${p.seriesName}: <b>${p.value}℃</b><br/>` })
        return html
      }
    },
    legend: { data: series.map(s => s.name), top: 0, textStyle: { color: '#666' } },
    grid: { left: 60, right: 30, top: 40, bottom: 30 },
    xAxis: { type: 'category', data: times, axisLabel: { color: '#999' }, boundaryGap: false },
    yAxis: { type: 'value', name: '℃', axisLabel: { color: '#666' }, splitLine: { lineStyle: { type: 'dashed' } } },
    series
  })
}

async function handleQuery() {
  if (timeRange.value?.[0]) {
    queryForm.startTime = timeRange.value[0]
    queryForm.endTime = timeRange.value[1]
  }
  loading.value = true
  try {
    const [minRes, hourRes, dayRes, pvRes] = await Promise.all([
      getMinuteTrend(queryForm),
      getHourlyTrend(queryForm),
      getDailyTrend(queryForm),
      getPeakValley(queryForm)
    ])
    await nextTick()
    renderLineChart(minuteChartRef, minRes.data)
    renderLineChart(hourlyChartRef, hourRes.data, { showBand: true })
    renderLineChart(dailyChartRef, dayRes.data, { showBand: true })
    peakValleyList.value = pvRes.data
  } 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: 320px;
}
.chart-container-lg {
  width: 100%;
  min-height: 360px;
}
</style>
