<script setup>
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import {
  deleteEvalRecord,
  getEvalModels,
  getEvalPackages,
  getEvalRecord,
  getEvalRecords,
  runEvaluation,
} from '@/api/evalManagement'
import EvalChart from './components/EvalChart.vue'

// ── form ──────────────────────────────────────────────────────────────────────
const packages = ref([])
const models = ref([])
const form = reactive({ model_id: '', package_id: '' })
const evaluating = ref(false)

// Current evaluation result (shown directly above the records table)
const currentResult = ref(null) // { model_name, package_name, mae, rmse, chart_data }

// ── records ───────────────────────────────────────────────────────────────────
const records = ref([])
const loadingRecords = ref(false)

// ── dialog for historical view ────────────────────────────────────────────────
const dialogVisible = ref(false)
const dialogRecord = ref(null)
const dialogLoading = ref(false)

// ── actions ───────────────────────────────────────────────────────────────────
const loadDropdowns = async () => {
  const [pkgs, mdls] = await Promise.all([getEvalPackages(), getEvalModels()])
  packages.value = pkgs
  models.value = mdls
}

const loadRecords = async () => {
  loadingRecords.value = true
  try {
    records.value = await getEvalRecords()
  } finally {
    loadingRecords.value = false
  }
}

const handleEvaluate = async () => {
  if (!form.model_id) { ElMessage.warning('请选择模型'); return }
  if (!form.package_id) { ElMessage.warning('请选择数据包'); return }

  evaluating.value = true
  currentResult.value = null
  try {
    const result = await runEvaluation({ model_id: form.model_id, package_id: form.package_id })
    currentResult.value = result
    ElMessage.success('评估完成')
    await loadRecords()
  } catch (e) {
    ElMessage.error(e?.message || '评估失败')
  } finally {
    evaluating.value = false
  }
}

const handleView = async (row) => {
  dialogLoading.value = true
  dialogVisible.value = true
  dialogRecord.value = null
  try {
    dialogRecord.value = await getEvalRecord(row.id)
  } finally {
    dialogLoading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除模型"${row.model_name}"在"${row.package_name}"上的评估记录吗？`,
      '提示',
      { type: 'warning' },
    )
    await deleteEvalRecord(row.id)
    ElMessage.success('已删除')
    if (currentResult.value?.id === row.id) currentResult.value = null
    await loadRecords()
  } catch {
    // user cancelled
  }
}

const fmtMetric = (v) => (v != null ? Number(v).toFixed(5) : '-')

onMounted(async () => {
  await Promise.all([loadDropdowns(), loadRecords()])
})
</script>

<template>
  <div class="eval-page">
    <!-- ── top: config ──────────────────────────────────────────────────── -->
    <el-card class="config-card" shadow="hover">
      <template #header>
        <span class="card-title">评估配置</span>
      </template>

      <el-form :model="form" inline class="eval-form">
        <el-form-item label="选择模型" required>
          <el-select
            v-model="form.model_id"
            placeholder="请选择已保存模型"
            filterable
            style="width: 260px"
          >
            <el-option
              v-for="m in models"
              :key="m.id"
              :label="`${m.model_name}（训练包：${m.package_name}）`"
              :value="m.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择数据包" required>
          <el-select
            v-model="form.package_id"
            placeholder="请选择评估数据包"
            filterable
            style="width: 240px"
          >
            <el-option
              v-for="p in packages"
              :key="p.id"
              :label="`${p.name}（${p.data_count} 条）`"
              :value="p.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="evaluating" @click="handleEvaluate">
            开始评估
          </el-button>
        </el-form-item>
      </el-form>

      <!-- result metrics + chart -->
      <template v-if="evaluating">
        <div class="eval-loading">
          <el-icon class="is-loading" style="font-size:24px;color:#409EFF"><Refresh /></el-icon>
          <span>正在推理，请稍候…</span>
        </div>
      </template>

      <template v-else-if="currentResult">
        <div class="metrics-row">
          <div class="metric-chip">
            <span class="metric-label">评估样本</span>
            <span class="metric-value">{{ currentResult.total_count }} 条</span>
          </div>
          <div class="metric-chip">
            <span class="metric-label">MAE</span>
            <span class="metric-value">{{ fmtMetric(currentResult.mae) }} ℃</span>
          </div>
          <div class="metric-chip">
            <span class="metric-label">RMSE</span>
            <span class="metric-value">{{ fmtMetric(currentResult.rmse) }} ℃</span>
          </div>
          <div class="metric-chip">
            <span class="metric-label">模型</span>
            <span class="metric-value">{{ currentResult.model_name }}</span>
          </div>
          <div class="metric-chip">
            <span class="metric-label">数据包</span>
            <span class="metric-value">{{ currentResult.package_name }}</span>
          </div>
        </div>
        <EvalChart :chart-data="currentResult.chart_data" height="340px" />
      </template>
    </el-card>

    <!-- ── bottom: records table ────────────────────────────────────────── -->
    <el-card class="records-card" shadow="hover">
      <template #header>
        <div class="card-header-row">
          <span class="card-title">评估记录</span>
          <el-button :icon="Refresh" size="small" plain :loading="loadingRecords" @click="loadRecords">
            刷新
          </el-button>
        </div>
      </template>

      <el-table
        :data="records"
        v-loading="loadingRecords"
        border
        stripe
        height="calc(100vh - 580px)"
      >
        <el-table-column prop="model_name" label="模型名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="package_name" label="评估数据包" min-width="130" show-overflow-tooltip />
        <el-table-column label="样本数" width="90" align="center">
          <template #default="{ row }">{{ row.total_count }}</template>
        </el-table-column>
        <el-table-column label="MAE (℃)" width="110" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtMetric(row.mae) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="RMSE (℃)" width="110" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtMetric(row.rmse) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="评估时间" width="165" />
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- ── historical view dialog ───────────────────────────────────────── -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogRecord ? `${dialogRecord.model_name} — ${dialogRecord.package_name}` : '评估详情'"
      width="860px"
      destroy-on-close
    >
      <div v-loading="dialogLoading" style="min-height: 120px">
        <template v-if="dialogRecord">
          <div class="metrics-row" style="margin-bottom: 12px">
            <div class="metric-chip">
              <span class="metric-label">样本数</span>
              <span class="metric-value">{{ dialogRecord.total_count }}</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">MAE</span>
              <span class="metric-value">{{ fmtMetric(dialogRecord.mae) }} ℃</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">RMSE</span>
              <span class="metric-value">{{ fmtMetric(dialogRecord.rmse) }} ℃</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">评估时间</span>
              <span class="metric-value">{{ dialogRecord.created_at }}</span>
            </div>
          </div>
          <EvalChart :chart-data="dialogRecord.chart_data || []" height="380px" />
        </template>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.eval-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
}

.config-card,
.records-card {
  flex-shrink: 0;

  :deep(.el-card__header) {
    padding: 12px 20px;
    border-bottom: 1px solid #e8edf3;
  }

  :deep(.el-card__body) {
    padding: 16px 20px;
  }
}

.records-card {
  flex: 1;
  min-height: 200px;
}

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

.card-header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.eval-form {
  :deep(.el-form-item) {
    margin-bottom: 0;
    margin-right: 16px;
  }
}

.eval-loading {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 24px 0 8px;
  color: #64748b;
  font-size: 14px;
}

.metrics-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 16px 0 12px;
}

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

.metric-label {
  font-size: 11px;
  color: #94a3b8;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.metric-value {
  font-size: 15px;
  font-weight: 600;
  color: #0f172a;
}

.metric-cell {
  font-size: 13px;
  color: #0f766e;
  font-weight: 500;
}
</style>
