const Result = require('../models/Result'); const Exam = require('../models/Exam'); // 提交考试结果 exports.submitResult = async (req, res, next) => { try { const { examId, answers, timeTaken } = req.body; // 验证考试 const exam = await Exam.findById(examId); if (!exam) { return res.status(404).json({ message: 'Exam not found' }); } // 计算分数 let totalScore = 0; const answerResults = exam.questions.map(question => { const userAnswer = answers[question._id]; let isCorrect = false; let score = 0; if (question.type === 'text') { // 简答题默认给一半分 if (userAnswer && userAnswer.trim().length > 0) { isCorrect = true; score = question.score / 2; } } else if (Array.isArray(question.answer)) { // 多选题 const correctAnswers = [...question.answer].sort().toString(); const userAns = [...userAnswer].sort().toString(); isCorrect = correctAnswers === userAns; score = isCorrect ? question.score : 0; } else { // 单选题 isCorrect = userAnswer === question.answer; score = isCorrect ? question.score : 0; } totalScore += score; return { questionId: question._id, userAnswer, isCorrect, score }; }); // 保存结果 const result = new Result({ exam: examId, user: req.user.id, answers: answerResults, totalScore, maxScore: exam.questions.reduce((sum, q) => sum + q.score, 0), timeTaken }); await result.save(); res.status(201).json(result); } catch (err) { next(err); } }; // 获取用户成绩 exports.getUserResults = async (req, res, next) => { try { const results = await Result.find({ user: req.user.id }) .populate('exam', 'title description') .sort({ submittedAt: -1 }); res.json(results); } catch (err) { next(err); } }; // 获取考试所有成绩 (教师/管理员) exports.getExamResults = async (req, res, next) => { try { const results = await Result.find({ exam: req.params.id }) .populate('user', 'username') .populate('exam', 'title') .sort({ totalScore: -1 }); res.json(results); } catch (err) { next(err); } };