<template>
  <el-dialog v-model="visible" title="历史记录" width="800px" fullscreen :modal="false" @close="handleClose">
    <el-table :data="records" style="width: 100%" size="small" v-loading="loading">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="ai_score" label="AI分数" width="80" />
      <el-table-column prop="teacher_score" label="教师分数" width="80" />
      <el-table-column prop="confidence" label="可信度" width="80">
        <template #default="{ row }">
          {{ Math.round(row.confidence * 100) }}%
        </template>
      </el-table-column>
      <el-table-column prop="student_answer" label="答案摘要" min-width="200" show-overflow-tooltip />
      <el-table-column prop="created_at" label="时间" width="160" />
      <el-table-column label="操作" width="80" fixed="right">
        <template #default="{ row }">
          <el-button text size="small" type="danger" @click="deleteRecord(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button size="small" @click="handleClose">关闭</el-button>
      <el-button size="small" @click="refresh">刷新</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '@/stores/app'
import type { HistoryRecord } from '@/types'

const appStore = useAppStore()
const visible = ref(false)
const loading = ref(false)
const records = ref<HistoryRecord[]>([])

watch(() => appStore.isHistoryDialogOpen, (val) => {
  visible.value = val
  if (val) refresh()
})

async function refresh() {
  loading.value = true
  try {
    if (window.electronAPI) {
      records.value = await window.electronAPI.history.list()
    }
  } catch {
    records.value = []
  } finally {
    loading.value = false
  }
}

async function deleteRecord(id: number) {
  try {
    await ElMessageBox.confirm('确定删除该记录？', '提示')
    if (window.electronAPI) {
      await window.electronAPI.history.delete(id)
      ElMessage.success('已删除')
      refresh()
    }
  } catch { /* cancelled */ }
}

function handleClose() {
  window.electronAPI?.dialog.close()
}
</script>
