<template>
  <AdminLayout>
    <div class="examinee-management-container">
      <div class="examinee-header">
        <h1>考生管理</h1>
        <el-button type="primary" @click="handleAddExaminee">+ 添加考生</el-button>
      </div>
      <div class="examinee-content">
        <el-table :data="examineeList" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="examinee_name" label="姓名" width="120" />
          <el-table-column prop="examinee_id_card" label="身份证号" width="180" />
          <el-table-column prop="examinee_admission_ticket" label="准考证号" width="180" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEditExaminee(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteExaminee(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/编辑考生弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="formData" label-width="120px" ref="formRef">
        <el-form-item label="考生姓名" prop="examinee_name" :rules="[{ required: true, message: '请输入考生姓名', trigger: 'blur' }]">
          <el-input v-model="formData.examinee_name" placeholder="请输入考生姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="examinee_gender">
          <el-select v-model="formData.examinee_gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="examinee_unit">
          <el-input v-model="formData.examinee_unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="笔试考场" prop="written_exam_room">
          <el-input v-model="formData.written_exam_room" placeholder="请输入笔试考场" />
        </el-form-item>
        <el-form-item label="笔试座位号" prop="written_exam_seat">
          <el-input v-model="formData.written_exam_seat" placeholder="请输入笔试座位号" />
        </el-form-item>
        <el-form-item label="机试考场" prop="computer_exam_room">
          <el-input v-model="formData.computer_exam_room" placeholder="请输入机试考场" />
        </el-form-item>
        <el-form-item label="机试座位号" prop="computer_exam_seat">
          <el-input v-model="formData.computer_exam_seat" placeholder="请输入机试座位号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="examinee_id_card" :rules="[{ required: true, message: '请输入身份证号', trigger: 'blur' }]">
          <el-input v-model="formData.examinee_id_card" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="准考证号" prop="examinee_admission_ticket" :rules="[{ required: true, message: '请输入准考证号', trigger: 'blur' }]">
          <el-input v-model="formData.examinee_admission_ticket" placeholder="请输入准考证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveExaminee">保存</el-button>
      </template>
    </el-dialog>
  </AdminLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import AdminLayout from '@/components/admin/AdminLayout.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据和状态
const examineeList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加考生')
const isEdit = ref(false)
const formRef = ref(null)

// 表单数据
const formData = ref({
  id: null,
  examinee_name: '',
  examinee_gender: '',
  examinee_unit: '',
  written_exam_room: '',
  written_exam_seat: '',
  computer_exam_room: '',
  computer_exam_seat: '',
  examinee_id_card: '',
  examinee_admission_ticket: ''
})

// 获取考生列表
const fetchExaminees = async () => {
  loading.value = true
  try {
    const result = await window.electronAPI.fetchAllExaminees()
    examineeList.value = result
  } catch (error) {
    ElMessage.error('获取考生列表失败: ' + error.message)
    console.error('获取考生列表失败', error)
  } finally {
    loading.value = false
  }
}

// 处理添加考生
const handleAddExaminee = () => {
  isEdit.value = false
  dialogTitle.value = '添加考生'
  formData.value = {
    id: null,
    examinee_name: '',
    examinee_gender: '',
    examinee_unit: '',
    written_exam_room: '',
    written_exam_seat: '',
    computer_exam_room: '',
    computer_exam_seat: '',
    examinee_id_card: '',
    examinee_admission_ticket: ''
  }
  dialogVisible.value = true
}

// 处理编辑考生
const handleEditExaminee = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑考生'
  formData.value = {...row}
  dialogVisible.value = true
}

// 处理保存考生
const handleSaveExaminee = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 将Proxy对象转换为普通对象
        const examineeData = {...formData.value};

        if (isEdit.value) {
          console.log(examineeData);
          await window.electronAPI.updateExaminee(examineeData.id, examineeData)
          ElMessage.success('考生更新成功')
        } else {
          await window.electronAPI.createExaminee(examineeData)
          ElMessage.success('考生添加成功')
        }
        dialogVisible.value = false
        fetchExaminees() // 重新加载列表
      } catch (error) {
        ElMessage.error('保存考生失败: ' + error.message)
        console.error('保存考生失败', error)
      }
    }
  });
}

// 处理删除考生
const handleDeleteExaminee = (id) => {
  ElMessageBox.confirm(
    '确定要删除该考生吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await window.electronAPI.deleteExaminee(id)
        ElMessage.success('考生删除成功')
        fetchExaminees() // 重新加载列表
      } catch (error) {
        ElMessage.error('删除考生失败: ' + error.message)
        console.error('删除考生失败', error)
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 组件挂载时加载数据
onMounted(() => {
  fetchExaminees()
})
</script>

<style scoped>
examinee-management-container {
  width: 100%;
  height: 100%;
}

examinee-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

examinee-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 确保表格单元格内容不换行 */
:deep(.el-table__cell) {
  white-space: nowrap;
}
</style>