<template>
  <el-dialog v-model="visible" title="评分模板管理" width="680px" :modal="false" @close="handleClose">
    <el-table :data="templates" size="small" style="width: 100%">
      <el-table-column prop="id" label="ID" width="50" />
      <el-table-column prop="name" label="考试名称" min-width="130" />
      <el-table-column prop="course" label="课程" min-width="100" />
      <el-table-column label="题目数" width="70">
        <template #default="{ row }">{{ row.questions?.length || 0 }}</template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="150" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button text size="small" :disabled="!row.questions?.length" @click="selectTemplate(row)">使用</el-button>
          <el-button text size="small" type="danger" @click="deleteTemplate(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 12px; display: flex; gap: 8px;">
      <el-button size="small" @click="exportTemplates">导出</el-button>
      <el-button size="small" @click="importTemplates">导入</el-button>
    </div>

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

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

const appStore = useAppStore()
const visible = ref(false)
const templates = ref<TemplateItem[]>([])

watch(() => appStore.isTemplateDialogOpen, (val) => {
  visible.value = val
  if (val) loadTemplates()
})

async function loadTemplates() {
  if (window.electronAPI) {
    templates.value = await window.electronAPI.template.list()
  }
}

async function selectTemplate(tpl: TemplateItem) {
  if (!tpl.questions?.length) {
    ElMessage.warning('该模板没有题目数据')
    return
  }
  const ok = await window.electronAPI?.template.apply(tpl.id)
  if (ok) {
    handleClose()
  } else {
    ElMessage.error('应用模板失败')
  }
}

async function exportTemplates() {
  const ok = await window.electronAPI?.template.exportJson()
  if (ok) {
    ElMessage.success('模板已导出')
  } else if (ok === false) {
    ElMessage.warning('导出失败或已取消')
  }
}

async function importTemplates() {
  const result = await window.electronAPI?.template.importJson()
  if (result) {
    ElMessage.success(`已导入 ${result.count} 个模板`)
    loadTemplates()
  }
}

async function deleteTemplate(tpl: TemplateItem) {
  if (window.electronAPI) {
    const ok = await window.electronAPI.template.delete(tpl.id)
    if (ok) {
      ElMessage.success('已删除')
      loadTemplates()
    }
  }
}

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

<style scoped>
</style>
