<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="学生姓名" prop="studentId">
              <el-select v-model="queryParams.studentId" placeholder="选择学生" clearable filterable style="width: 180px" @keyup.enter="handleQuery">
                <el-option v-for="s in studentList" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="考试类型" prop="examType">
              <el-select v-model="queryParams.examType" placeholder="考试类型" clearable style="width: 140px">
                <el-option v-for="opt in examTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="科目" prop="subject">
              <el-input v-model="queryParams.subject" placeholder="科目" clearable style="width: 120px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:exam:add']" type="primary" plain icon="Plus" @click="handleAdd">新增考试</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:exam:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="examList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生" align="center" prop="studentName" width="100" show-overflow-tooltip />
        <el-table-column label="考试名称" align="center" prop="examName" min-width="160" show-overflow-tooltip />
        <el-table-column label="考试日期" align="center" prop="examDate" width="110">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag :type="getExamTypeTag(scope.row.examType)" size="small">{{ getExamTypeLabel(scope.row.examType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="科目" align="center" prop="subject" width="80" />
        <el-table-column label="学校" align="center" prop="school" width="120" show-overflow-tooltip />
        <el-table-column label="总分" align="center" prop="totalScore" width="80" />
        <el-table-column label="录入人" align="center" prop="recorderName" width="90" />
        <el-table-column label="操作" width="160" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="查看成绩" placement="top">
              <el-button v-hasPermi="['edu:exam:query']" link type="primary" icon="View" @click="handleViewScores(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button v-hasPermi="['edu:exam:edit']" link type="primary" icon="Edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:exam:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="720px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="学生" prop="studentId">
              <el-select v-model="form.studentId" placeholder="选择学生" filterable :disabled="!!form.id" style="width: 100%">
                <el-option v-for="s in studentList" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试名称" prop="examName">
              <el-input v-model="form.examName" placeholder="如：2024年期末考试" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="考试日期">
              <el-date-picker v-model="form.examDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考试类型">
              <el-select v-model="form.examType" placeholder="类型" style="width: 100%">
                <el-option v-for="opt in examTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学校">
              <el-input v-model="form.school" placeholder="考试学校" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">成绩明细</el-divider>
        <el-button type="primary" plain icon="Plus" size="small" @click="addScoreRow">添加科目成绩</el-button>
        <el-table border :data="form.scores" size="small" class="mt-2" max-height="300">
          <el-table-column label="科目" width="120">
            <template #default="{ row }">
              <el-input v-model="row.subject" placeholder="科目" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="得分" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.score" :min="0" :precision="1" size="small" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="满分" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.totalScore" :min="0" :precision="1" size="small" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="班级排名" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.classRank" :min="0" size="small" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="年级排名" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.gradeRank" :min="0" size="small" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="等级" width="90">
            <template #default="{ row }">
              <el-select v-model="row.gradeLevel" placeholder="等级" size="small" style="width: 100%">
                <el-option v-for="opt in gradeLevelOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="老师点评" min-width="160">
            <template #default="{ row }">
              <el-input v-model="row.teacherComment" placeholder="点评" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" icon="Delete" size="small" @click="removeScoreRow($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="备注" class="mt-4">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 查看成绩明细弹窗 -->
    <el-dialog v-model="scoreDialog.visible" title="成绩明细" width="700px" append-to-body>
      <el-descriptions :column="2" border class="mb-4" v-if="scoreDialog.exam">
        <el-descriptions-item label="学生">{{ scoreDialog.exam.studentName }}</el-descriptions-item>
        <el-descriptions-item label="考试名称">{{ scoreDialog.exam.examName }}</el-descriptions-item>
        <el-descriptions-item label="考试日期">{{ scoreDialog.exam.examDate ? proxy.parseTime(scoreDialog.exam.examDate, '{y}-{m}-{d}') : '-' }}</el-descriptions-item>
        <el-descriptions-item label="考试类型">
          <el-tag :type="getExamTypeTag(scoreDialog.exam.examType)" size="small">{{ getExamTypeLabel(scoreDialog.exam.examType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="学校">{{ scoreDialog.exam.school || '-' }}</el-descriptions-item>
        <el-descriptions-item label="录入人">{{ scoreDialog.exam.recorderName || '-' }}</el-descriptions-item>
      </el-descriptions>
      <el-table v-loading="scoreDialog.loading" border :data="scoreDialog.scores" size="small">
        <el-table-column label="科目" prop="subject" width="100" align="center" />
        <el-table-column label="得分" prop="score" width="80" align="center" />
        <el-table-column label="满分" prop="totalScore" width="80" align="center" />
        <el-table-column label="得分率" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.totalScore">{{ (row.score / row.totalScore * 100).toFixed(1) }}%</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="班级排名" prop="classRank" width="90" align="center" />
        <el-table-column label="年级排名" prop="gradeRank" width="90" align="center" />
        <el-table-column label="等级" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.gradeLevel" :type="gradeLevelOptions.find(o => o.value === row.gradeLevel)?.elTagType || 'info'" size="small">{{ row.gradeLevel }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="老师点评" prop="teacherComment" min-width="160" align="center" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <el-button @click="scoreDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduExam" lang="ts">
import { listExam, getExam, addExam, updateExam, delExam, getExamScores } from '@/api/edu/exam';
import { listStudent } from '@/api/edu/student';
import { ExamQuery, ExamVO, ExamForm, ExamScoreVO, examTypeOptions, gradeLevelOptions } from '@/api/edu/exam/types';
import { StudentVO } from '@/api/edu/student/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const examList = ref<ExamVO[]>([]);
const studentList = ref<StudentVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();

const dialog = reactive<{ visible: boolean; title: string }>({ visible: false, title: '' });
const scoreDialog = reactive<{ visible: boolean; loading: boolean; exam: ExamVO | null; scores: ExamScoreVO[] }>({
  visible: false,
  loading: false,
  exam: null,
  scores: []
});

const data = reactive<PageData<ExamForm, ExamQuery>>({
  form: {
    studentId: undefined,
    examName: '',
    examDate: '',
    subject: '',
    examType: '',
    school: '',
    totalScore: undefined,
    scores: [],
    remark: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    examType: '',
    subject: ''
  },
  rules: {
    studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
    examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getExamTypeLabel = (val: string) => examTypeOptions.find((o) => o.value === val)?.label || val;
const getExamTypeTag = (val: string) => examTypeOptions.find((o) => o.value === val)?.elTagType || 'info';

/** 加载学生列表 */
const loadStudents = async () => {
  const res = await listStudent({ pageNum: 1, pageSize: 1000 } as any);
  studentList.value = res.rows;
};

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listExam(queryParams.value);
  examList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: ExamVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 添加成绩行 */
const addScoreRow = () => {
  if (!form.value.scores) form.value.scores = [];
  form.value.scores.push({ subject: '', score: 0, totalScore: 100, classRank: undefined, gradeRank: undefined, gradeLevel: '', teacherComment: '' });
};

/** 移除成绩行 */
const removeScoreRow = (index: number) => {
  form.value.scores?.splice(index, 1);
};

/** 重置表单 */
const reset = () => {
  form.value = {
    studentId: undefined,
    examName: '',
    examDate: '',
    subject: '',
    examType: '',
    school: '',
    totalScore: undefined,
    scores: [],
    remark: ''
  };
  formRef.value?.resetFields();
};

/** 新增 */
const handleAdd = () => {
  reset();
  dialog.title = '新增考试';
  dialog.visible = true;
};

/** 编辑 */
const handleEdit = async (row: ExamVO) => {
  reset();
  const res = await getExam(row.id);
  Object.assign(form.value, res.data);
  // 加载成绩明细
  const scoresRes = await getExamScores(row.id);
  form.value.scores = scoresRes.data || [];
  dialog.title = '编辑考试';
  dialog.visible = true;
};

/** 查看成绩 */
const handleViewScores = async (row: ExamVO) => {
  scoreDialog.exam = row;
  scoreDialog.scores = [];
  scoreDialog.visible = true;
  scoreDialog.loading = true;
  try {
    const res = await getExamScores(row.id);
    scoreDialog.scores = res.data || [];
  } finally {
    scoreDialog.loading = false;
  }
};

/** 提交表单 */
const submitForm = async () => {
  await formRef.value?.validate();
  if (form.value.id) {
    await updateExam(form.value);
    proxy?.$modal.msgSuccess('修改成功');
  } else {
    await addExam(form.value);
    proxy?.$modal.msgSuccess('新增成功');
  }
  dialog.visible = false;
  await getList();
};

/** 删除 */
const handleDelete = async (row?: ExamVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的考试记录？');
  await delExam(delIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(() => {
  loadStudents();
  getList();
});
</script>
