<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="DISTRIBUTION_HELP" />
            </div>
          </template>
          <div ref="intervalChartRef" 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">温度直方图（1℃分箱）</span>
              <HelpButton title="温度直方图" :content="DISTRIBUTION_HELP" />
            </div>
          </template>
          <div ref="histogramChartRef" 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="DISTRIBUTION_HELP" />
        </div>
      </template>
      <div ref="calendarHeatmapRef" 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="DISTRIBUTION_HELP" />
        </div>
      </template>
      <div ref="hourlyHeatmapRef" class="chart-container-lg" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getIntervalDistribution, getHistogram, getCalendarHeatmap, getHourlyHeatmap } from '@/api/ems/report/tempBoard'
import type { TempBoardQuery, TempBoardDistributionVO } from '@/api/ems/report/tempBoard'
import HelpButton from '../components/HelpButton.vue'
import { DISTRIBUTION_HELP } from '../components/helpContent'
import { useChartResize } from '../components/useChartResize'

defineOptions({ name: 'TempBoardDistribution' })

const timeRange = ref<[string, string]>(['', ''])
const queryForm = reactive<TempBoardQuery>({})
const loading = ref(false)
const intervalChartRef = ref<HTMLElement>()
const histogramChartRef = ref<HTMLElement>()
const calendarHeatmapRef = ref<HTMLElement>()
const hourlyHeatmapRef = ref<HTMLElement>()

const { getChart } = useChartResize(intervalChartRef, histogramChartRef, calendarHeatmapRef, hourlyHeatmapRef)

/** 初始化默认时间范围：昨天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 [intervalRes, histRes, calRes, hourRes] = await Promise.all([
      getIntervalDistribution(queryForm), getHistogram(queryForm),
      getCalendarHeatmap(queryForm), getHourlyHeatmap(queryForm)
    ])
    await nextTick()
    renderIntervalChart(intervalRes.data)
    renderHistogramChart(histRes.data)
    renderCalendarHeatmap(calRes.data)
    renderHourlyHeatmap(hourRes.data)
  } finally { loading.value = false }
}

/** 温度区间分布环形图 */
function renderIntervalChart(data: TempBoardDistributionVO[]) {
  const chart = getChart(intervalChartRef)
  if (!chart || !data.length) return
  const colorPalette = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399', '#9b59b6', '#1abc9c']
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: (p: any) => `${p.name}<br/>样本数: <b>${p.value}</b><br/>占比: <b>${p.percent}%</b>`
    },
    legend: {
      orient: 'vertical', left: 'left', top: 'middle',
      textStyle: { color: '#666' },
      formatter: (name: string) => name
    },
    color: colorPalette,
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      data: data.map(d => ({ name: d.tempBucket, value: d.sampleCount })),
      emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' } },
      label: { formatter: '{b}\n{d}%', fontSize: 12 },
      itemStyle: { borderRadius: 6, borderColor: '#fff', borderWidth: 2 }
    }]
  })
}

/** 温度直方图 */
function renderHistogramChart(data: TempBoardDistributionVO[]) {
  const chart = getChart(histogramChartRef)
  if (!chart || !data.length) return
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => `${params[0].name}<br/>样本数: <b>${params[0].value}</b>`
    },
    grid: { left: 60, right: 30, top: 30, bottom: 40 },
    xAxis: {
      type: 'category', data: data.map(d => `${d.tempBin}℃`), name: '温度',
      axisLabel: { color: '#666', rotate: 30 }
    },
    yAxis: { type: 'value', name: '样本数', axisLabel: { color: '#666' }, splitLine: { lineStyle: { type: 'dashed' } } },
    series: [{
      type: 'bar',
      data: data.map(d => d.sampleCount),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#67c23a' },
          { offset: 1, color: '#b3e19d' }
        ]),
        borderRadius: [4, 4, 0, 0]
      },
      label: { show: true, position: 'top', fontSize: 10, color: '#666' },
      barMaxWidth: 30
    }]
  })
}

/** 日历热力图 */
function renderCalendarHeatmap(data: TempBoardDistributionVO[]) {
  const chart = getChart(calendarHeatmapRef)
  if (!chart || !data.length) return
  const dates = data.map(d => d.statDate!)
  const range = dates.length ? [dates[0], dates[dates.length - 1]] : []
  chart.setOption({
    tooltip: {
      formatter: (p: any) => `${p.value[0]}<br/>平均温度: <b>${p.value[1]?.toFixed(2)}℃</b>`
    },
    visualMap: {
      min: 10, max: 30, calculable: true,
      orient: 'horizontal', left: 'center', bottom: 0,
      inRange: { color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#fee090', '#fdae61', '#f46d43', '#d73027'] },
      textStyle: { color: '#666' }
    },
    calendar: {
      range,
      cellSize: ['auto', 30],
      itemStyle: { borderWidth: 3, borderColor: '#fff' },
      yearLabel: { show: false },
      dayLabel: { color: '#666' },
      monthLabel: { color: '#333' }
    },
    series: [{
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: data.map(d => [d.statDate, d.avgTemp]),
      itemStyle: { borderRadius: 2 }
    }]
  })
}

/** 小时热力图 */
function renderHourlyHeatmap(data: TempBoardDistributionVO[]) {
  const chart = getChart(hourlyHeatmapRef)
  if (!chart || !data.length) return
  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
  const dates = [...new Set(data.map(d => d.statDate!))]
  chart.setOption({
    tooltip: {
      formatter: (p: any) => `${p.value[0]} ${hours[p.value[1]]}<br/>平均温度: <b>${p.value[2]?.toFixed(2)}℃</b>`
    },
    grid: { left: 100, right: 60, top: 10, bottom: 60 },
    xAxis: { type: 'category', data: hours, splitArea: { show: true }, axisLabel: { color: '#666' } },
    yAxis: { type: 'category', data: dates, splitArea: { show: true }, axisLabel: { color: '#666' } },
    visualMap: {
      min: 10, max: 30, calculable: true,
      orient: 'horizontal', left: 'center', bottom: 0,
      inRange: { color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#fee090', '#fdae61', '#f46d43', '#d73027'] },
      textStyle: { color: '#666' }
    },
    series: [{
      type: 'heatmap',
      data: data.map(d => [d.statHour, d.statDate, d.avgTemp]),
      label: { show: false },
      emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.5)' } },
      itemStyle: { borderRadius: 2, borderColor: '#fff', borderWidth: 1 }
    }]
  })
}

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

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