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

const route = useRoute()

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

// Current evaluation result
const currentResult = ref(null)

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

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

// ── package picker modal ──────────────────────────────────────────────────────
const pickerVisible = ref(false)
const pickerSearch = ref('')
const pickerCategoryId = ref('')
const pickerCategories = ref([])
const pickerPackages = ref([])
const pickerLoading = ref(false)

const openPicker = async () => {
  pickerSearch.value = ''
  pickerCategoryId.value = ''
  pickerVisible.value = true
  if (!pickerCategories.value.length) {
    try {
      const tree = await getPkgCategoryTree()
      const flatten = (nodes, result = []) => {
        for (const n of nodes) {
          result.push({ value: String(n.id), label: n.name })
          if (n.children?.length) flatten(n.children, result)
        }
        return result
      }
      pickerCategories.value = flatten(tree)
    } catch {}
  }
  await loadPickerPackages()
}

const loadPickerPackages = async () => {
  pickerLoading.value = true
  try {
    const data = await getEvalPackages({
      category_id: pickerCategoryId.value || '',
      name: pickerSearch.value.trim(),
    })
    pickerPackages.value = data
  } finally {
    pickerLoading.value = false
  }
}

const selectPackage = (pkg) => {
  form.package_id = pkg.id
  form.package_name = pkg.name
  pickerVisible.value = false
}

// ── actions ───────────────────────────────────────────────────────────────────
const loadModels = async () => {
  models.value = await getEvalModels()
}

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 selectedRecords = ref([])
const handleRecordSelectionChange = (rows) => {
  selectedRecords.value = rows
}

const handleBatchDeleteRecords = async () => {
  if (!selectedRecords.value.length) return
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedRecords.value.length} 条评估记录吗？此操作不可恢复。`,
      '批量删除',
      { type: 'warning' },
    )
    await Promise.all(selectedRecords.value.map((r) => deleteEvalRecord(r.id)))
    ElMessage.success(`已删除 ${selectedRecords.value.length} 条评估记录`)
    if (selectedRecords.value.some((r) => r.id === currentResult.value?.id)) currentResult.value = null
    selectedRecords.value = []
    await loadRecords()
  } catch {
    // user cancelled
  }
}

const fmtMetric = (v) => (v != null ? Number(v).toFixed(5) : '-')
const fmtMape = (v) => (v != null ? Number(v).toFixed(3) + ' %' : '-')
const fmtR2 = (v) => (v != null ? Number(v).toFixed(6) : '-')

onMounted(async () => {
  await Promise.all([loadModels(), loadRecords()])
  // Pre-select model from query param (e.g. from ModelList 评估 button)
  const qModelId = route.query.model_id
  if (qModelId) {
    form.model_id = Number(qModelId)
  }
})
</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: 280px"
          >
            <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>
          <div class="pkg-picker-row">
            <el-input
              :model-value="form.package_name || ''"
              placeholder="点击右侧按钮选择数据包"
              readonly
              style="width: 220px"
            />
            <el-button @click="openPicker">选择</el-button>
          </div>
        </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 meta-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">模型</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>
        <!-- 评估指标行 -->
        <div class="metrics-row">
          <div class="metric-chip">
            <span class="metric-label">MSE（均方误差）</span>
            <span class="metric-value">{{ fmtMetric(currentResult.mse) }}</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">MAE（平均绝对误差）</span>
            <span class="metric-value">{{ fmtMetric(currentResult.mae) }} ℃</span>
          </div>
          <div class="metric-chip">
            <span class="metric-label">MAPE（平均绝对百分比误差）</span>
            <span class="metric-value">{{ fmtMape(currentResult.mape) }}</span>
          </div>
          <div class="metric-chip">
            <span class="metric-label">R²（决定系数）</span>
            <span class="metric-value">{{ fmtR2(currentResult.r2) }}</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>
          <div style="display:flex;gap:8px;align-items:center">
            <el-button
              type="danger"
              plain
              size="small"
              :disabled="!selectedRecords.length"
              @click="handleBatchDeleteRecords"
            >批量删除</el-button>
            <el-button :icon="Refresh" size="small" plain :loading="loadingRecords" @click="loadRecords">
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="records"
        v-loading="loadingRecords"
        border
        stripe
        height="calc(100vh - 580px)"
        @selection-change="handleRecordSelectionChange"
      >
        <el-table-column type="selection" width="44" />
        <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="88" align="center">
          <template #default="{ row }">{{ row.total_count }}</template>
        </el-table-column>
        <el-table-column label="MSE" width="100" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtMetric(row.mse) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="RMSE (℃)" width="100" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtMetric(row.rmse) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="MAE (℃)" width="100" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtMetric(row.mae) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="MAPE" width="90" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtMape(row.mape) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="R²" width="90" align="center">
          <template #default="{ row }">
            <span class="metric-cell">{{ fmtR2(row.r2) }}</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="900px"
      destroy-on-close
    >
      <div v-loading="dialogLoading" style="min-height: 120px">
        <template v-if="dialogRecord">
          <!-- 样本数 / 评估时间行 -->
          <div class="metrics-row meta-row" style="margin-bottom: 8px">
            <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">评估时间</span>
              <span class="metric-value">{{ dialogRecord.created_at }}</span>
            </div>
          </div>
          <!-- 评估指标行 -->
          <div class="metrics-row" style="margin-bottom: 12px">
            <div class="metric-chip">
              <span class="metric-label">MSE（均方误差）</span>
              <span class="metric-value">{{ fmtMetric(dialogRecord.mse) }}</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">MAE（平均绝对误差）</span>
              <span class="metric-value">{{ fmtMetric(dialogRecord.mae) }} ℃</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">MAPE（平均绝对百分比误差）</span>
              <span class="metric-value">{{ fmtMape(dialogRecord.mape) }}</span>
            </div>
            <div class="metric-chip">
              <span class="metric-label">R²（决定系数）</span>
              <span class="metric-value">{{ fmtR2(dialogRecord.r2) }}</span>
            </div>
          </div>
          <EvalChart :chart-data="dialogRecord.chart_data || []" height="400px" />
        </template>
      </div>

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

    <!-- ── package picker dialog ─────────────────────────────────────────── -->
    <el-dialog
      v-model="pickerVisible"
      title="选择评估数据包"
      width="640px"
      :close-on-click-modal="false"
    >
      <div class="picker-filters">
        <el-select
          v-model="pickerCategoryId"
          placeholder="所有分类"
          clearable
          style="width:180px"
          @change="loadPickerPackages"
        >
          <el-option
            v-for="opt in pickerCategories"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
        <el-input
          v-model="pickerSearch"
          placeholder="数据包名称 / 备注"
          :prefix-icon="Search"
          clearable
          style="flex:1"
          @keyup.enter="loadPickerPackages"
          @clear="loadPickerPackages"
        />
        <el-button type="primary" @click="loadPickerPackages">搜索</el-button>
      </div>

      <el-table
        :data="pickerPackages"
        v-loading="pickerLoading"
        border
        stripe
        highlight-current-row
        height="360px"
        style="cursor:pointer;margin-top:10px"
        @row-click="selectPackage"
      >
        <el-table-column prop="name" label="数据包名称" show-overflow-tooltip />
        <el-table-column prop="data_count" label="数据量" width="90" align="center" />
      </el-table>
    </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;
  }
}

.pkg-picker-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.picker-filters {
  display: flex;
  gap: 8px;
  align-items: center;
}

.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;
}

.meta-row {
  padding-bottom: 4px;

  .metric-chip {
    background: #f1f5f9;
    border-color: #cbd5e1;
  }
}

.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>

