<script setup>
import * as echarts from 'echarts'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'
import { getHistoryList, getHistoryDetail } from '@/api/historyData'

// ── 列表 ───────────────────────────────────────────────────────────────────────
const records = ref([])
const loadingList = ref(false)
const selectedId = ref(null)

const loadList = async () => {
  loadingList.value = true
  try {
    records.value = await getHistoryList()
  } catch {
    ElMessage.error('加载历史数据失败')
  } finally {
    loadingList.value = false
  }
}

// ── 详情 ───────────────────────────────────────────────────────────────────────
const detail = ref(null)
const loadingDetail = ref(false)

let tempChart = null
let currChart = null
const tempChartRef = ref(null)
const currChartRef = ref(null)

const disposeCharts = () => {
  tempChart?.dispose()
  currChart?.dispose()
  tempChart = null
  currChart = null
}

const initCharts = (points, targetTemp) => {
  disposeCharts()
  if (!tempChartRef.value || !currChartRef.value) return

  tempChart = echarts.init(tempChartRef.value)
  currChart = echarts.init(currChartRef.value)

  const xData = points.map((d) => `步${d.step_idx}`)
  const actuals = points.map((d) => d.actual_temp)
  const refs = points.map((d) => d.reference_temp)
  const currents = points.map((d) => d.current_output)
  const targetLine = points.map(() => targetTemp)

  const intervalVal = Math.max(0, Math.floor(xData.length / 10) - 1)

  tempChart.setOption({
    animation: false,
    color: ['#409EFF', '#67C23A', '#F56C6C'],
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.96)',
      borderColor: '#e2e8f0',
      borderWidth: 1,
      formatter(params) {
        if (!params?.length) return ''
        const lines = [`<div style="margin-bottom:4px;font-weight:600">${params[0].axisValue}</div>`]
        params.forEach((p) => {
          const v = p.data != null ? Number(p.data).toFixed(3) + ' °C' : '--'
          lines.push(
            `<div style="display:flex;justify-content:space-between;gap:16px">
              <span>${p.marker}${p.seriesName}</span><strong>${v}</strong>
            </div>`,
          )
        })
        return lines.join('')
      },
    },
    legend: { bottom: 4, itemWidth: 18, itemHeight: 8, textStyle: { color: '#475569', fontSize: 12 } },
    grid: { top: 16, left: 16, right: 16, bottom: 52, containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData,
      axisLabel: { color: '#64748b', fontSize: 11, interval: intervalVal },
      axisLine: { lineStyle: { color: '#cbd5e1' } },
    },
    yAxis: {
      type: 'value',
      name: '温度 (°C)',
      nameTextStyle: { color: '#64748b', fontSize: 11 },
      axisLabel: { color: '#64748b', fontSize: 11 },
      splitLine: { lineStyle: { color: '#e2e8f0' } },
    },
    series: [
      { name: '实际温度', type: 'line', data: actuals, smooth: true, symbol: 'none', lineStyle: { width: 2 } },
      { name: '参考轨迹', type: 'line', data: refs, smooth: true, symbol: 'none', lineStyle: { width: 1.5, type: 'dashed' } },
      { name: '目标温度', type: 'line', data: targetLine, symbol: 'none', lineStyle: { width: 1.5, type: 'dotted', color: '#F56C6C' } },
    ],
  })

  currChart.setOption({
    animation: false,
    color: ['#E6A23C'],
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.96)',
      borderColor: '#e2e8f0',
      borderWidth: 1,
      formatter(params) {
        if (!params?.length) return ''
        const v = params[0].data != null ? Number(params[0].data).toFixed(3) + ' A' : '--'
        return `<div style="font-weight:600">${params[0].axisValue}</div>
                <div>${params[0].marker}电流输出：<strong>${v}</strong></div>`
      },
    },
    legend: { bottom: 4, itemWidth: 18, itemHeight: 8, textStyle: { color: '#475569', fontSize: 12 } },
    grid: { top: 16, left: 16, right: 16, bottom: 52, containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData,
      axisLabel: { color: '#64748b', fontSize: 11, interval: intervalVal },
      axisLine: { lineStyle: { color: '#cbd5e1' } },
    },
    yAxis: {
      type: 'value',
      name: '电流 (A)',
      nameTextStyle: { color: '#64748b', fontSize: 11 },
      axisLabel: { color: '#64748b', fontSize: 11 },
      splitLine: { lineStyle: { color: '#e2e8f0' } },
      min: 0,
    },
    series: [
      { name: '电流输出', type: 'line', data: currents, smooth: false, symbol: 'none', lineStyle: { width: 2 }, areaStyle: { opacity: 0.08 } },
    ],
  })
}

const selectRecord = async (row) => {
  if (selectedId.value === row.id) return
  selectedId.value = row.id
  detail.value = null
  loadingDetail.value = true
  try {
    detail.value = await getHistoryDetail(row.id)
    await nextTick()
    if (detail.value?.points?.length) {
      initCharts(detail.value.points, detail.value.experiment?.target_temp)
    }
  } catch {
    ElMessage.error('加载详情失败')
  } finally {
    loadingDetail.value = false
  }
}

const onResize = () => {
  tempChart?.resize()
  currChart?.resize()
}

onMounted(async () => {
  await loadList()
  if (records.value.length) {
    await selectRecord(records.value[0])
  }
  window.addEventListener('resize', onResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', onResize)
  disposeCharts()
})

const fmtNum = (v, digits = 4) => (v != null ? Number(v).toFixed(digits) : '--')
</script>

<template>
  <div class="history-page">
    <!-- ── 左侧：记录列表 ────────────────────────────────────────────────── -->
    <div class="left-panel">
      <div class="panel-header">
        <span class="panel-title">历史数据</span>
        <el-button :icon="Refresh" size="small" plain :loading="loadingList" @click="loadList">
          刷新
        </el-button>
      </div>

      <div v-loading="loadingList" class="record-list">
        <el-empty v-if="!loadingList && !records.length" description="暂无已导出的历史数据" :image-size="80" />
        <div
          v-for="row in records"
          :key="row.id"
          class="record-item"
          :class="{ active: selectedId === row.id }"
          @click="selectRecord(row)"
        >
          <div class="record-name">{{ row.name }}</div>
          <div class="record-meta">
            <span>{{ row.model_name }}</span>
            <el-tag size="small" type="info" class="steps-tag">{{ row.total_steps }} 步</el-tag>
          </div>
          <div class="record-time">{{ row.stop_time ?? row.created_at }}</div>
        </div>
      </div>
    </div>

    <!-- ── 右侧：详情 ────────────────────────────────────────────────────── -->
    <div class="right-panel" v-loading="loadingDetail">
      <el-empty v-if="!detail && !loadingDetail" description="请在左侧选择一条历史记录" :image-size="100" />

      <template v-if="detail">
        <!-- 基本信息 -->
        <el-card shadow="hover" class="info-card">
          <div class="info-grid">
            <div class="info-item">
              <span class="label">试验名称</span>
              <span class="value">{{ detail.experiment?.name }}</span>
            </div>
            <div class="info-item">
              <span class="label">预测模型</span>
              <span class="value">{{ detail.experiment?.model_name }}</span>
            </div>
            <div class="info-item">
              <span class="label">初始数据包</span>
              <span class="value">{{ detail.experiment?.package_name }}</span>
            </div>
            <div class="info-item">
              <span class="label">目标温度</span>
              <span class="value highlight">{{ detail.experiment?.target_temp?.toFixed(1) }} °C</span>
            </div>
            <div class="info-item">
              <span class="label">开始时间</span>
              <span class="value">{{ detail.experiment?.start_time ?? '--' }}</span>
            </div>
            <div class="info-item">
              <span class="label">停止时间</span>
              <span class="value">{{ detail.experiment?.stop_time ?? '--' }}</span>
            </div>
          </div>
        </el-card>

        <!-- 指标摘要 -->
        <el-card v-if="detail.summary" shadow="hover" class="summary-card">
          <template #header><span class="card-title">控制性能指标</span></template>
          <div class="metrics-row">
            <div class="metric-chip">
              <span class="metric-label">采集步数</span>
              <span class="metric-value">{{ detail.summary.total_steps }}</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">仿真时长</span>
              <span class="metric-value">{{ detail.summary.duration_s }} s</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">初始温度</span>
              <span class="metric-value">{{ fmtNum(detail.summary.initial_temp, 2) }} °C</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">最终温度</span>
              <span class="metric-value">{{ fmtNum(detail.summary.final_temp, 2) }} °C</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">MAE</span>
              <span class="metric-value">{{ fmtNum(detail.summary.mae) }} °C</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">RMSE</span>
              <span class="metric-value">{{ fmtNum(detail.summary.rmse) }} °C</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">最大超调</span>
              <span class="metric-value">{{ fmtNum(detail.summary.overshoot) }} °C</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">调节时间</span>
              <span class="metric-value">{{ detail.summary.settling_step ?? '未稳定' }} 步</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">平均电流</span>
              <span class="metric-value">{{ fmtNum(detail.summary.avg_current) }} A</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">最大电流</span>
              <span class="metric-value">{{ fmtNum(detail.summary.max_current) }} A</span>
            </div>
          </div>
        </el-card>

        <!-- 温度曲线 -->
        <el-card shadow="hover" class="chart-card">
          <template #header><span class="card-title">温度曲线</span></template>
          <el-empty v-if="!detail.points?.length" description="暂无数据点" :image-size="60" />
          <div v-else ref="tempChartRef" class="chart-body" />
        </el-card>

        <!-- 电流曲线 -->
        <el-card shadow="hover" class="chart-card">
          <template #header><span class="card-title">电流输出曲线</span></template>
          <el-empty v-if="!detail.points?.length" description="暂无数据点" :image-size="60" />
          <div v-else ref="currChartRef" class="chart-body" />
        </el-card>
      </template>
    </div>
  </div>
</template>

<style scoped>
.history-page {
  display: flex;
  gap: 16px;
  height: calc(100vh - 60px);
  padding: 16px;
  box-sizing: border-box;
  overflow: hidden;
}

/* ── 左侧 ── */
.left-panel {
  width: 280px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #fff;
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.panel-title {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.record-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.record-item {
  padding: 10px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.15s;
  margin-bottom: 4px;
  border: 1px solid transparent;
}

.record-item:hover {
  background: #f1f5f9;
}

.record-item.active {
  background: #eff6ff;
  border-color: #bfdbfe;
}

.record-name {
  font-size: 13px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.record-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #64748b;
  margin-bottom: 2px;
}

.steps-tag {
  flex-shrink: 0;
}

.record-time {
  font-size: 11px;
  color: #94a3b8;
}

/* ── 右侧 ── */
.right-panel {
  flex: 1;
  min-width: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.info-card,
.summary-card,
.chart-card {
  flex-shrink: 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.label {
  font-size: 11px;
  color: #94a3b8;
}

.value {
  font-size: 13px;
  color: #1e293b;
  font-weight: 500;
}

.value.highlight {
  color: #2563eb;
  font-weight: 700;
}

.metrics-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.metric-chip {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 8px 14px;
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 100px;
}

.metric-label {
  font-size: 11px;
  color: #94a3b8;
}

.metric-value {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.card-title {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.chart-body {
  height: 260px;
  width: 100%;
}
</style>
