$examData['paper_id'] ?? 'unknown', 'student_id' => $examData['student_id'] ?? 'unknown', 'question_count' => count($examData['questions'] ?? []) ]); $studentId = $examData['student_id']; $paperId = $examData['paper_id'] ?? ''; $questions = $examData['questions'] ?? []; // 0. 自动计算分数并补充未提交的题目 $questions = $this->autoCalculateScores($questions, $paperId); // 更新 examData 中的 questions(包含补充的题目) $examData['questions'] = $questions; // 【公司要求】1. 获取学案基准难度(取自学案的difficulty_category) $examBaseDifficulty = $this->getExamBaseDifficulty($examData['paper_id'] ?? ''); // 2. 保存答题记录到数据库 $this->saveExamAnswerRecords($examData); // 3. 获取题目知识点映射 $questionMappings = $this->getQuestionKnowledgeMappings($questions); // 【公司要求】4. 计算每个知识点的加权掌握度(传入学案基准难度) // 核心算法:难度映射 → 权重计算 → 数值更新(newMastery = oldMastery + change) $knowledgeMasteryVector = $this->calculateKnowledgeMasteryVector($questions, $questionMappings, $examBaseDifficulty, $studentId); // 【公司要求】5. 更新学生掌握度(包含多级父节点掌握度计算) $updatedMastery = $this->updateStudentMastery($studentId, $knowledgeMasteryVector); // 5. 生成题目维度分析 $questionAnalysis = $this->analyzeQuestions($questions, $questionMappings); // 6. 生成知识点维度分析 $knowledgePointAnalysis = $this->analyzeKnowledgePoints($knowledgeMasteryVector, $questionMappings); // 7. 生成整体掌握度总结 $overallSummary = $this->generateOverallSummary($updatedMastery); // 8. 生成智能出卷推荐依据 $smartQuizRecommendation = $this->generateSmartQuizRecommendation($updatedMastery); // 9. 保存分析结果 $analysisResult = [ 'paper_id' => $examData['paper_id'], 'student_id' => $studentId, 'timestamp' => now()->toISOString(), 'question_analysis' => $questionAnalysis, 'knowledge_point_analysis' => $knowledgePointAnalysis, 'overall_summary' => $overallSummary, 'smart_quiz_recommendation' => $smartQuizRecommendation, 'mastery_vector' => $updatedMastery, ]; $this->saveAnalysisResult($studentId, $examData['paper_id'], $analysisResult); Log::info('考试答题分析完成', [ 'student_id' => $studentId, 'paper_id' => $examData['paper_id'], 'analyzed_knowledge_points' => count($knowledgeMasteryVector) ]); return $analysisResult; } /** * 【公司要求】获取学案基准难度(取自学案的difficulty_category) * * 公司要求: * 入参需要增加 {学案基准难度}(取自学案的 difficulty_category) * @param string $paperId 试卷ID * @return int|null 学案基准难度(1-4级),失败返回null */ private function getExamBaseDifficulty(string $paperId): ?int { if (empty($paperId)) { return null; } try { // 【公司要求】入参需要增加 {学案基准难度}(取自学案的 difficulty_category) // 从试卷表获取difficulty_category $paper = DB::table('papers') ->where('paper_id', $paperId) ->first(); if (!$paper) { Log::warning('未找到试卷,尝试从缓存获取', ['paper_id' => $paperId]); return 2; } return $paper->difficulty_category ?? 2; } catch (\Exception $e) { Log::warning('获取学案基准难度失败,使用默认2级', [ 'paper_id' => $paperId, 'error' => $e->getMessage(), ]); return 2; // 默认中等难度 } } /** * 获取题目知识点映射 */ private function getQuestionKnowledgeMappings(array $questions): array { $mappings = []; $failedQuestions = []; // 直接从题目数据中提取知识点信息(不再调用外部服务) foreach ($questions as $question) { $questionId = $question['question_id'] ?? null; if (!$questionId) continue; // 提取知识点信息(优先使用请求数据中的字段) $kpMapping = []; // 使用新的多知识点获取方法 $dbKpMappings = $this->getQuestionKnowledgePointsFromDb($questionId); if (!empty($dbKpMappings)) { $kpMapping = $dbKpMappings; // 直接使用所有知识点 Log::debug('从数据库获取题目知识点', [ 'question_id' => $questionId, 'kp_count' => count($dbKpMappings), 'kp_codes' => array_column($dbKpMappings, 'kp_id') ]); } // 如果仍然没有知识点信息,跳过该题目 if (empty($kpMapping)) { $failedQuestions[] = $questionId; Log::warning('跳过无法获取知识点的题目', [ 'question_id' => $questionId ]); continue; } $mappings[$questionId] = [ 'question_id' => $questionId, 'kp_mapping' => $kpMapping ]; } if (!empty($failedQuestions)) { Log::warning('部分题目无法获取知识点信息', [ 'failed_questions' => $failedQuestions, 'total_questions' => count($questions), 'mapped_questions' => count($mappings) ]); } Log::info('题目知识点映射构建完成', [ 'total_questions' => count($questions), 'mapped_questions' => count($mappings), 'failed_questions' => count($failedQuestions) ]); return $mappings; } /** * 从数据库获取题目的知识点信息(支持多知识点) * 如果题目没有直接的知识点,通过目录ID匹配知识点 */ private function getQuestionKnowledgePointsFromDb(string $questionId): array { $allKpMappings = []; try { // 【第一步】从 questions 表直接获取知识点字段(可能有多个) $question = DB::connection('mysql') ->table('questions') ->where('id', $questionId) ->orWhere('question_code', $questionId) ->first(); if ($question) { // 检查题目的直接知识点字段 $directKpCodes = []; $kpCode1 = $question->kp_code; if ($kpCode1) $directKpCodes[] = $kpCode1; // 获取每个知识点的详细信息 foreach ($directKpCodes as $kpCode) { $kpInfo = DB::connection('mysql') ->table('knowledge_points') ->where('kp_code', $kpCode) ->first(); if ($kpInfo) { $allKpMappings[] = [ 'kp_id' => $kpCode, 'kp_name' => $kpInfo->name, 'weight' => 1.0 ]; } else { // 如果knowledge_points表中没有记录,仍然添加 $allKpMappings[] = [ 'kp_id' => $kpCode, 'kp_name' => $kpCode, 'weight' => 1.0 ]; } } if (!empty($directKpCodes)) { Log::debug('从题目直接字段获取知识点', [ 'question_id' => $questionId, 'kp_codes' => $directKpCodes, 'mapped_count' => count($allKpMappings) ]); } } // 【第二步】如果题目没有直接的知识点,通过目录ID匹配知识点 if (empty($allKpMappings) && $question) { $catalogKpMappings = $this->findKpCodesByCatalog($question); if (!empty($catalogKpMappings)) { $allKpMappings = $catalogKpMappings; Log::debug('通过目录ID匹配到知识点', [ 'question_id' => $questionId, 'matched_kp_codes' => array_column($catalogKpMappings, 'kp_id'), 'matched_count' => count($catalogKpMappings) ]); } } if (empty($allKpMappings)) { Log::warning('未找到题目的知识点信息', [ 'question_id' => $questionId ]); } } catch (\Exception $e) { Log::error('获取题目知识点信息失败', [ 'question_id' => $questionId, 'error' => $e->getMessage() ]); } return $allKpMappings; } /** * 通过题目的目录信息匹配知识点 * 使用 textbook_catalog_nodes_id -> textbook_chapter_knowledge_relation 表查询 */ private function findKpCodesByCatalog(object $question): array { $kpMappings = []; try { // 获取题目的教材目录节点ID $catalogNodesId = $question->textbook_catalog_nodes_id; if (!$catalogNodesId) { Log::debug('题目没有关联的教材目录节点', [ 'question_id' => $question->id ]); return $kpMappings; } // 通过 catalog_chapter_id 查询关联的知识点 $relations = DB::connection('mysql') ->table('textbook_chapter_knowledge_relation') ->where('catalog_chapter_id', $catalogNodesId) ->where('is_deleted', 0) // 只查询未删除的关联 ->get(); if ($relations->isNotEmpty()) { foreach ($relations as $relation) { $kpCode = $relation->kp_code; $kpInfo = DB::connection('mysql') ->table('knowledge_points') ->where('kp_code', $kpCode) ->first(); $kpMappings[] = [ 'kp_id' => $kpCode, 'kp_name' => $kpInfo->name ?? $kpCode, 'weight' => 1.0 ]; } Log::debug('通过教材目录节点匹配到知识点', [ 'question_id' => $question->id, 'catalog_nodes_id' => $catalogNodesId, 'matched_kp_count' => count($kpMappings), 'matched_kp_codes' => array_column($kpMappings, 'kp_id') ]); } else { Log::debug('教材目录节点没有关联的知识点', [ 'question_id' => $question->id, 'catalog_nodes_id' => $catalogNodesId ]); } } catch (\Exception $e) { Log::error('通过目录匹配知识点失败', [ 'question_id' => $question->id, 'error' => $e->getMessage() ]); } return $kpMappings; } /** * 保留原有方法用于向后兼容,但标记为废弃 */ private function getQuestionKnowledgePointFromDb(string $questionId): ?array { $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId); return !empty($kpMappings) ? $kpMappings[0] : null; } /** * 从 QuestionBank API 获取题目信息 */ private function getQuestionFromQuestionBank(string $questionId): ?array { try { $baseUrl = config('services.question_bank_api.base_url', 'http://question-bank-api:5015'); $response = Http::timeout(10)->get($baseUrl . '/questions/' . $questionId); if ($response->successful()) { $data = $response->json(); return $data['data'] ?? null; } return null; } catch (\Exception $e) { Log::warning('从QuestionBank获取题目信息失败', [ 'question_id' => $questionId, 'error' => $e->getMessage() ]); return null; } } /** * 批量获取题目难度 * * @param array $questionIds 题目ID数组 * @return array [questionId => difficulty] 映射 */ private function batchGetQuestionDifficulties(array $questionIds): array { if (empty($questionIds)) { return []; } $difficulties = []; try { $questions = DB::connection('mysql') ->table('questions') ->whereIn('id', $questionIds) ->orWhereIn('question_code', $questionIds) ->select(['id', 'question_code', 'difficulty']) ->get(); foreach ($questions as $question) { $difficulty = $question->difficulty !== null ? floatval($question->difficulty) : 0.6; // 同时用 id 和 question_code 作为键,确保能匹配到 $difficulties[$question->id] = $difficulty; if ($question->question_code) { $difficulties[$question->question_code] = $difficulty; } } } catch (\Exception $e) { Log::warning('批量获取题目难度失败', [ 'question_ids' => $questionIds, 'error' => $e->getMessage() ]); } return $difficulties; } /** * 【公司要求】计算知识点掌握度向量 * * 公司要求的核心算法: * 1. 难度映射:将题目中0.0-1.0的浮点数难度映射为 1-4 等级 * 2. 权重计算: * - 越级(Question > {学案基准难度}):对 +0.15 / 错 -0.05 * - 适应(Question = {学案基准难度}):对 +0.10 / 错 -0.10 * - 降级(Question < {学案基准难度}):对 +0.05 / 错 -0.15 * 3. 数值更新:newMastery = oldMastery + change,并做 0.0 ~ 1.0 的边界限制 * * 核心算法说明: * 1. 从考试答题中提取每个知识点的答题记录 * 2. 调用MasteryCalculator计算掌握度(包含:难度映射、权重计算、数值更新) * 3. 返回包含掌握度、置信度、趋势等完整信息的向量 * * @param array $questions 题目列表 * @param array $questionMappings 题目知识点映射 * @param int|null $examBaseDifficulty 学案基准难度(1-4级) * @param string|null $studentId 学生ID * @return array 知识点掌握度向量 */ private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array { // 按知识点聚合答题记录 $knowledgeAttempts = []; // 批量获取所有题目的难度(减少数据库查询次数) $questionIds = array_filter(array_map(fn($q) => $q['question_id'] ?? $q['question_bank_id'] ?? null, $questions)); $questionDifficulties = $this->batchGetQuestionDifficulties($questionIds); foreach ($questions as $question) { $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null; if (empty($questionId)) { Log::warning('calculateKnowledgeMasteryVector: 题目缺少ID', ['question' => $question]); continue; } $score = floatval($question['score_obtained'] ?? 0); $maxScore = floatval($question['score'] ?? $score); // is_correct 是数组,如 [0,1,1],表示每个步骤的正误 $isCorrectArray = $question['is_correct'] ?? []; if (!is_array($isCorrectArray)) { $isCorrectArray = [$isCorrectArray ? 1 : 0]; } $mapping = $questionMappings[$questionId] ?? null; if (!$mapping || !isset($mapping['kp_mapping'])) { Log::debug('calculateKnowledgeMasteryVector: 题目无知识点映射', ['question_id' => $questionId]); continue; } // 从批量查询结果获取题目难度 $questionDifficulty = $questionDifficulties[$questionId] ?? 0.6; $stepCount = count($isCorrectArray); $scorePerStep = $maxScore / max($stepCount, 1); // 根据 is_correct 数组生成步骤级答题记录 foreach ($isCorrectArray as $stepIndex => $isCorrect) { $isCorrectBool = (int) $isCorrect === 1; // 为该题目关联的每个知识点创建答题记录 foreach ($mapping['kp_mapping'] as $kpMapping) { $kpId = $kpMapping['kp_id']; if (!isset($knowledgeAttempts[$kpId])) { $knowledgeAttempts[$kpId] = [ 'attempts' => [], 'step_details' => [], ]; } // 构建答题记录(用于MasteryCalculator) $attemptRecord = [ 'question_id' => $questionId, 'is_correct' => $isCorrectBool, 'step_index' => $stepIndex, 'question_difficulty' => $questionDifficulty, 'created_at' => now()->toISOString(), ]; $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord; $knowledgeAttempts[$kpId]['step_details'][] = [ 'question_id' => $questionId, 'step_index' => $stepIndex, 'score' => $isCorrectBool ? $scorePerStep : 0, 'max_score' => $scorePerStep, 'is_correct' => $isCorrectBool, ]; } } } // 【公司要求】【核心】使用MasteryCalculator计算每个知识点的掌握度 $masteryVector = []; foreach ($knowledgeAttempts as $kpId => $data) { $attempts = $data['attempts']; // 如果没有学案基准难度,使用默认值2(提分) $baseDifficulty = $examBaseDifficulty ?? 2; // 【公司要求】调用MasteryCalculator的核心算法(传入学案基准难度) // 该算法包含:难度映射、权重计算、数值更新(newMastery = oldMastery + change) $masteryResult = $this->masteryCalculator->calculateMasteryLevel( $studentId ?? '', // 传递学生ID,用于保存掌握度到数据库 $kpId, $attempts, $baseDifficulty ); // 【公司要求】只保留核心掌握度数据 $masteryVector[$kpId] = [ 'kp_id' => $kpId, 'mastery' => $masteryResult['mastery'], 'total_attempts' => $masteryResult['total_attempts'], 'correct_attempts' => $masteryResult['correct_attempts'], 'accuracy_rate' => $masteryResult['accuracy_rate'], 'step_details' => $data['step_details'], // 计算细节(用于调试和分析) 'calculation_details' => $masteryResult['details'] ?? [], ]; } Log::info('知识点掌握度向量计算完成', [ 'knowledge_points_count' => count($masteryVector), 'sample' => array_slice($masteryVector, 0, 3, true), ]); return $masteryVector; } /** * 更新学生掌握度(与历史数据合并) */ private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array { $updatedMastery = []; foreach ($knowledgeMasteryVector as $kpId => $data) { // 获取历史掌握度 $historyMastery = DB::connection('mysql') ->table('student_knowledge_mastery') ->where('student_id', $studentId) ->where('kp_code', $kpId) ->first(); $historyMasteryLevel = $historyMastery->mastery_level ?? 0.0; // 【公司要求】保存到数据库(只保存核心掌握度数据) DB::connection('mysql') ->table('student_knowledge_mastery') ->updateOrInsert( ['student_id' => $studentId, 'kp_code' => $kpId], [ 'mastery_level' => $data['mastery'], 'confidence_level' => 0.0, // 不再保存置信度 'total_attempts' => ($historyMastery->total_attempts ?? 0) + 1, 'correct_attempts' => ($historyMastery->correct_attempts ?? 0) + intval($data['correct_attempts'] > 0), 'mastery_trend' => 'stable', // 不再判断趋势,统一设为stable 'last_mastery_update' => now(), 'updated_at' => now(), ] ); // 【公司要求】返回值:只返回核心掌握度数据 $updatedMastery[$kpId] = [ 'kp_id' => $kpId, 'current_mastery' => $data['mastery'], 'previous_mastery' => $historyMasteryLevel, 'change' => $data['mastery'] - $historyMasteryLevel, 'weight' => 1, 'is_parent' => false ]; } // 【修复】计算并更新父节点掌握度,同时添加到返回数组中 $parentMasteryData = $this->updateParentMasteryLevels($studentId, array_keys($knowledgeMasteryVector)); // 合并父节点数据到返回数组 $updatedMastery = array_merge($updatedMastery, $parentMasteryData); return $updatedMastery; } /** * 【公司要求】计算并更新父节点掌握度(支持多级递归) * * 公司要求: * 1. 查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code) * 2. 平均值计算:如果一个知识点是父节点,它的掌握度不再从数据库直接读, * 而是实时计算其下所有子节点掌握度的算术平均数 * 3. 多级递归:支持多级结构,能够从最底层逐级向上求平均 * * 递归计算流程: * - 从最底层节点开始,逐级向上递归计算父节点掌握度 * - 父节点掌握度 = 所有子节点掌握度的算术平均数 * - 支持任意层级结构,递归深度限制为10级 * * @param string $studentId 学生ID * @param array $childKpCodes 当前层的子节点编码列表 * @param int $maxDepth 最大递归深度(防止无限递归,默认10级) * @return array 返回所有层级的父节点掌握度数据 */ private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array { $allParentMasteryData = []; $currentLevelChildCodes = $childKpCodes; $processedNodes = new \ArrayObject(); // 防止重复处理 try { // 【公司要求】多级递归:逐级向上递归计算,支持多级结构 for ($level = 0; $level < $maxDepth; $level++) { if (empty($currentLevelChildCodes)) { break; // 没有更多父节点,退出循环 } // 【公司要求】查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code) // 获取当前层子节点的直接父节点 $parentKpCodes = DB::connection('mysql') ->table('knowledge_points') ->whereIn('kp_code', $currentLevelChildCodes) ->whereNotNull('parent_kp_code') ->distinct() ->pluck('parent_kp_code') ->toArray(); if (empty($parentKpCodes)) { Log::debug("第{$level}层没有更多父节点,递归结束"); break; } $currentLevelParentData = []; foreach ($parentKpCodes as $parentKpCode) { // 防止重复处理同一节点 if (isset($processedNodes[$parentKpCode])) { continue; } $processedNodes[$parentKpCode] = true; // 【公司要求】平均值计算:使用MasteryCalculator计算父节点掌握度(实时计算) // 父节点掌握度 = 所有子节点掌握度的算术平均数 $parentMastery = $this->masteryCalculator->calculateParentMastery($studentId, $parentKpCode); // 获取父节点历史数据 $historyParentMastery = DB::connection('mysql') ->table('student_knowledge_mastery') ->where('student_id', $studentId) ->where('kp_code', $parentKpCode) ->first(); $previousMastery = $historyParentMastery->mastery_level ?? 0.0; // 【自己要求】保存父节点掌握度到数据库(只保存核心数据) DB::connection('mysql') ->table('student_knowledge_mastery') ->updateOrInsert( ['student_id' => $studentId, 'kp_code' => $parentKpCode], [ 'mastery_level' => $parentMastery, 'confidence_level' => 0.0, // 不再保存置信度 'total_attempts' => 1, // 父节点不记录答题次数 'correct_attempts' => 0, // 父节点不记录正确次数 'mastery_trend' => 'stable', // 统一设为stable 'last_mastery_update' => now(), 'updated_at' => now(), ] ); // 【公司要求】记录当前层级数据(移除置信度) $currentLevelParentData[$parentKpCode] = [ 'kp_id' => $parentKpCode, 'current_mastery' => $parentMastery, 'previous_mastery' => $previousMastery, 'change' => $parentMastery - $previousMastery, 'weight' => 1, 'is_parent' => true, 'level' => $level + 1 // 记录层级深度 ]; Log::debug("第" . ($level + 1) . "层父节点掌握度已更新", [ 'student_id' => $studentId, 'parent_kp_code' => $parentKpCode, 'parent_mastery' => $parentMastery, 'child_nodes_count' => count($currentLevelChildCodes) ]); } // 合并到总结果中 $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData); // 【公司要求】多级递归:准备下一轮递归,从最底层逐级向上求平均 // 当前层的父节点作为下一层的子节点 $currentLevelChildCodes = $parentKpCodes; } if (!empty($allParentMasteryData)) { $totalParentCount = count($allParentMasteryData); $maxLevel = 0; foreach ($allParentMasteryData as $data) { $maxLevel = max($maxLevel, $data['level']); } Log::info('多级父节点掌握度计算完成', [ 'student_id' => $studentId, 'child_count' => count($childKpCodes), 'total_parent_count' => $totalParentCount, 'max_level' => $maxLevel, 'all_parent_kp_codes' => array_keys($allParentMasteryData) ]); } } catch (\Exception $e) { Log::error('计算多级父节点掌握度失败', [ 'student_id' => $studentId, 'child_kp_codes' => $childKpCodes, 'current_level' => $currentLevelChildCodes, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } return $allParentMasteryData; } /** * 生成题目维度分析(包含AI分析和解题思路) */ private function analyzeQuestions(array $questions, array $questionMappings): array { $analysis = []; foreach ($questions as $question) { $questionId = $question['question_id']; $score = floatval($question['score_obtained'] ?? 0); $maxScore = floatval($question['score'] ?? $score); $steps = $question['steps'] ?? []; $isCorrect = $question['is_correct'] ?? ($score >= $maxScore); $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []]; if (empty($mapping['kp_mapping'])) { Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]); continue; } $kpCode = $mapping['kp_mapping'][0]['kp_id']; // 步骤分析 $stepAnalysis = []; if (!empty($steps)) { foreach ($steps as $step) { $kpId = $step['kp_id']; if (empty($kpId)) { Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [ 'question_id' => $questionId, 'step_index' => $step['step_index'] ?? 'unknown' ]); continue; } $stepAnalysis[] = [ 'step_index' => $step['step_index'], 'is_correct' => $step['is_correct'], 'kp_id' => $kpId, 'description' => $step['description'] ?? '' ]; } } // 知识点关联 $knowledgePoints = array_map(function($kp) { return [ 'kp_id' => $kp['kp_id'], 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'], 'weight' => $kp['weight'] ?? 1.0 ]; }, $mapping['kp_mapping']); // 【集成】调用AI分析服务,获取解题思路和错误分析 $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping); $analysis[] = [ 'question_id' => $questionId, 'score_obtained' => $score, 'max_score' => $maxScore, 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0, 'is_correct' => $isCorrect, 'step_analysis' => $stepAnalysis, 'knowledge_points' => $knowledgePoints, 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis), // 【新增】解题思路和错误分析 'solution_process' => $aiAnalysis['solution_process'] ?? '', 'error_analysis' => $aiAnalysis['error_analysis'] ?? '', 'mistake_type' => $aiAnalysis['mistake_type'] ?? '', 'suggestions' => $aiAnalysis['suggestions'] ?? '', 'next_steps' => $aiAnalysis['next_steps'] ?? [], ]; } return $analysis; } /** * 获取题目的AI分析(解题思路、错误分析) */ private function getQuestionAIAnalysis(array $question, array $mapping): array { $isCorrect = $question['is_correct'] ?? false; $score = floatval($question['score_obtained'] ?? 0); $maxScore = floatval($question['score'] ?? 10); $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null; if (empty($kpCode)) { Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [ 'question_id' => $question['question_id'] ?? 'unknown', 'mapping' => $mapping ]); $kpCode = 'UNKNOWN_KP'; } // 调用LocalAIAnalysisService进行分析 try { $analysisResult = $this->aiAnalysisService->analyzeAnswer([ 'question_id' => $question['question_id'], 'question_text' => $question['question_text'] ?? '', 'student_answer' => $question['student_answer'] ?? '', 'correct_answer' => $question['correct_answer'] ?? '', 'score' => $score, 'max_score' => $maxScore, 'kp_code' => $kpCode, ]); $data = $analysisResult['data'] ?? []; // 根据正确性生成不同的解题思路 if ($isCorrect) { return [ 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰', 'error_analysis' => '', 'mistake_type' => '', 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯', 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'], ]; } // 错误题目:返回详细分析 return [ 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤', 'error_analysis' => $data['reason'] ?? '解题过程中存在错误', 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误', 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习', 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'], ]; } catch (\Exception $e) { Log::warning('AI分析失败,使用默认分析', [ 'question_id' => $question['question_id'], 'error' => $e->getMessage(), ]); // 回退到基础分析 return $this->getFallbackAnalysis($question, $isCorrect); } } /** * 回退分析(当AI分析失败时) */ private function getFallbackAnalysis(array $question, bool $isCorrect): array { if ($isCorrect) { return [ 'solution_process' => '该题作答正确', 'error_analysis' => '', 'mistake_type' => '', 'suggestions' => '继续保持', 'next_steps' => ['尝试更高难度的题目'], ]; } $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1); return [ 'solution_process' => '请参考标准答案和解题步骤', 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误', 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误', 'suggestions' => '建议复习相关知识点,加强练习', 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'], ]; } /** * 生成知识点维度分析 */ private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array { $analysis = []; foreach ($knowledgeMasteryVector as $kpId => $data) { // 【公司要求】移除置信度,只保留核心掌握度分析 $analysis[] = [ 'kp_id' => $kpId, 'mastery_level' => $data['mastery'], 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']), 'evidence_count' => count($data['step_details']), 'step_evidence' => $data['step_details'], 'recommendation' => $this->generateKnowledgePointRecommendation($data) ]; } return $analysis; } /** * 生成整体掌握度总结 */ private function generateOverallSummary(array $updatedMastery): array { $knowledgePoints = array_values($updatedMastery); if (empty($knowledgePoints)) { return [ 'total_knowledge_points' => 0, 'average_mastery' => 0, 'mastery_distribution' => [ 'mastered' => 0, 'good' => 0, 'weak' => 0 ], 'top_strengths' => [], 'top_weaknesses' => [] ]; } // 计算平均掌握度(只计算子节点,不包括父节点) $childNodes = array_filter($knowledgePoints, fn($kp) => !($kp['is_parent'] ?? false)); $totalChildNodes = count($childNodes); if ($totalChildNodes === 0) { // 如果没有子节点,只计算所有节点 $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints); } else { // 计算所有节点的平均掌握度(包括父节点) $allMastery = array_column($knowledgePoints, 'current_mastery'); $averageMastery = array_sum($allMastery) / count($allMastery); } // 掌握度分布(只统计子节点) $mastered = array_filter($childNodes, fn($kp) => $kp['current_mastery'] >= 0.85); $good = array_filter($childNodes, fn($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85); $weak = array_filter($childNodes, fn($kp) => $kp['current_mastery'] < 0.70); // 排序找出优势和薄弱点(只包括子节点) usort($childNodes, fn($a, $b) => $b['current_mastery'] <=> $a['current_mastery']); $topStrengths = array_slice($childNodes, 0, 3); $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3); // 统计父子节点数量 $childCount = count(array_filter($knowledgePoints, fn($kp) => !($kp['is_parent'] ?? false))); $parentCount = count(array_filter($knowledgePoints, fn($kp) => $kp['is_parent'] ?? false)); return [ 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量 'child_nodes_count' => $childCount, 'parent_nodes_count' => $parentCount, 'average_mastery' => round($averageMastery, 4), 'mastery_distribution' => [ 'mastered' => count($mastered), 'good' => count($good), 'weak' => count($weak) ], 'top_strengths' => $topStrengths, 'top_weaknesses' => $topWeaknesses, 'overall_performance' => $this->evaluateOverallPerformance($averageMastery) ]; } /** * 生成智能出卷推荐依据 * 基于文档中的推荐优先级算法 */ private function generateSmartQuizRecommendation(array $updatedMastery): array { $recommendations = []; // 只对子节点生成推荐,忽略父节点 foreach ($updatedMastery as $kpId => $data) { // 跳过父节点 if ($data['is_parent'] ?? false) { continue; } $mastery = $data['current_mastery']; // 【公司要求】移除置信度,只使用掌握度计算推荐 $weight = $data['weight']; // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求 // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0 $importance = 1.0; // 覆盖需求:最近没考过或考得少,值大 $coverageNeed = max(1.0, 1.5 - ($weight / 10)); $priority = (1 - $mastery) * $importance * $coverageNeed; $recommendations[] = [ 'kp_id' => $kpId, 'current_mastery' => $mastery, 'priority' => $priority, 'recommended_questions' => $this->calculateRecommendedQuestions($mastery), 'focus_type' => $this->determineFocusType($mastery) ]; } // 按优先级排序 usort($recommendations, fn($a, $b) => $b['priority'] <=> $a['priority']); // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型 $totalRecommendations = count($recommendations); $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4)); $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4)); $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8)); return [ 'priority_list' => $recommendations, 'quiz_structure' => [ 'consolidation_type' => $consolidation, 'remediation_type' => $remediation, 'challenge_type' => $challenge ], 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions')) ]; } /** * 保存考试答题记录 * * 入参格式示例: * { * "question_bank_id": "12979", * "student_answer": "C", * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确 * "teacher_comment": null * } * * is_correct 数组说明: * - 单选题:[1] 或 [0],长度为1 * - 填空题:[1, 0, 1],每个空一个元素 * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素 */ /** * 保存错题记录 * * @param string $studentId 学生ID * @param string $questionId 题目ID * @param string $examId 考试ID * @param array $question 题目数据 * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null) */ private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void { try { // 如果 $kpMapping 是数组,说明是多个 kp_id // 如果是关联数组,说明是单个 kpMapping(兼容旧调用) $kpIds = null; if (is_array($kpMapping)) { // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping) if (isset($kpMapping[0])) { // 数组的数组:[[kp_id: '...'], [kp_id: '...']] $kpIds = array_column($kpMapping, 'kp_id'); } else { // 关联数组:[kp_id: '...'] $kpIds = [$kpMapping['kp_id']]; } } $payload = [ 'student_id' => $studentId, 'question_id' => $questionId, 'paper_id' => $examId, 'my_answer' => $question['student_answer'] ?? null, 'correct_answer' => null, // 可以从题目表获取 'question_text' => null, // 可以从题目表获取 'knowledge_point' => null, // 不保存name,只保存kp_ids 'kp_ids' => $kpIds, // 保存为数组格式 'source' => $examId, // 来源标记使用卷子ID 'happened_at' => now(), ]; $result = $this->mistakeBookService->createMistake($payload); if (($result['duplicate'] ?? false) === false) { Log::debug('错题记录保存成功', [ 'student_id' => $studentId, 'question_id' => $questionId, 'mistake_id' => $result['mistake_id'] ?? null ]); } } catch (\Exception $e) { Log::warning('错题记录保存失败(不中断主流程)', [ 'student_id' => $studentId, 'question_id' => $questionId, 'exam_id' => $examId, 'error' => $e->getMessage() ]); } } private function saveExamAnswerRecords(array $examData): void { $studentId = $examData['student_id']; $examId = $examData['paper_id']; // 先清理该考试的所有答题记录(支持重复提交) // delete() 方法即使没有匹配数据也不会报错,返回0 try { DB::connection('mysql')->table('student_answer_questions') ->where('student_id', $studentId) ->where('exam_id', $examId) ->delete(); DB::connection('mysql')->table('student_answer_steps') ->where('student_id', $studentId) ->where('exam_id', $examId) ->delete(); } catch (\Exception $e) { Log::warning('清理旧答题记录时出错(可忽略)', [ 'student_id' => $studentId, 'exam_id' => $examId, 'error' => $e->getMessage(), ]); } $stepsSavedCount = 0; $questionsSavedCount = 0; foreach ($examData['questions'] as $question) { // 兼容两种字段名:question_id 或 question_bank_id $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null; if (empty($questionId)) { Log::warning('题目缺少ID,跳过保存', ['question' => $question]); continue; } // 从 is_correct 数组确定步骤数量 $isCorrectArray = $question['is_correct'] ?? []; if (!is_array($isCorrectArray)) { // 兼容非数组情况,转换为数组 $isCorrectArray = [$isCorrectArray ? 1 : 0]; } $stepCount = count($isCorrectArray); // 获取该题目关联的知识点(可能多个) $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId); if ($stepCount > 1 || !empty($kpMappings)) { // 多步骤题目:保存步骤级记录 // 每个步骤对应 is_correct 数组中的一个元素,先使用平均分来代替 $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1); // 【优化】先收集错误知识点,避免重复调用 saveMistakeRecord $hasMistake = false; $allErrorKpCodes = []; foreach ($isCorrectArray as $stepIndex => $isCorrect) { $isCorrectBool = (int) $isCorrect === 1; // 如果有知识点映射,为每个知识点保存记录 if (!empty($kpMappings)) { foreach ($kpMappings as $kpMapping) { try { DB::connection('mysql')->table('student_answer_steps')->insert([ 'student_id' => $studentId, 'exam_id' => $examId, 'question_id' => $questionId, 'step_index' => $stepIndex, 'kp_id' => $kpMapping['kp_id'], 'is_correct' => $isCorrectBool ? 1 : 0, 'step_score' => $isCorrectBool ? $scorePerStep : 0, 'created_at' => now(), 'updated_at' => now(), ]); $stepsSavedCount++; // 收集错误知识点(不重复调用 saveMistakeRecord) if (!$isCorrectBool) { $hasMistake = true; $allErrorKpCodes[] = $kpMapping['kp_id']; } } catch (\Exception $e) { Log::warning('保存步骤记录失败', [ 'student_id' => $studentId, 'question_id' => $questionId, 'step_index' => $stepIndex, 'kp_id' => $kpMapping['kp_id'], 'error' => $e->getMessage(), ]); } } } else { // 没有知识点映射,仍保存步骤但 kp_id 为空 try { DB::connection('mysql')->table('student_answer_steps')->insert([ 'student_id' => $studentId, 'exam_id' => $examId, 'question_id' => $questionId, 'step_index' => $stepIndex, 'kp_id' => null, 'is_correct' => $isCorrectBool ? 1 : 0, 'step_score' => $isCorrectBool ? $scorePerStep : 0, 'created_at' => now(), 'updated_at' => now(), ]); $stepsSavedCount++; // 标记有错误(无知识点映射) if (!$isCorrectBool) { $hasMistake = true; } } catch (\Exception $e) { Log::warning('保存步骤记录失败(无知识点)', [ 'student_id' => $studentId, 'question_id' => $questionId, 'step_index' => $stepIndex, 'error' => $e->getMessage(), ]); } } } // 【错题本】一次性保存错题记录(合并所有错误知识点) if ($hasMistake) { $uniqueKpCodes = array_values(array_unique($allErrorKpCodes)); // 转换为 kpMapping 数组格式:[[kp_id: '...'], [kp_id: '...']] $kpMappingArray = array_map(fn($code) => ['kp_id' => $code], $uniqueKpCodes); $this->saveMistakeRecord($studentId, $questionId, $examId, $question, $kpMappingArray); } } else { // 单步骤题目:保存题目级记录 $isQuestionCorrect = (($question['score_obtained'] ?? 0) > 0); try { DB::connection('mysql')->table('student_answer_questions')->insert([ 'student_id' => $studentId, 'exam_id' => $examId, 'question_id' => $questionId, 'score_obtained' => $question['score_obtained'] ?? 0, 'max_score' => $question['score'] ?? 0, 'created_at' => now(), 'updated_at' => now(), ]); $questionsSavedCount++; // 【错题本】保存错题记录(题目级错误) if (!$isQuestionCorrect) { // 收集所有知识点,转换为数组格式 $kpMappingArray = !empty($kpMappings) ? array_map(fn($m) => ['kp_id' => $m['kp_id']], $kpMappings) : null; $this->saveMistakeRecord($studentId, $questionId, $examId, $question, $kpMappingArray); } } catch (\Exception $e) { Log::warning('保存题目级记录失败', [ 'student_id' => $studentId, 'exam_id' => $examId, 'question_id' => $questionId, 'error' => $e->getMessage(), ]); } } } Log::info('答题记录保存完成', [ 'student_id' => $studentId, 'exam_id' => $examId, 'total_questions' => count($examData['questions']), 'steps_saved' => $stepsSavedCount, 'questions_saved' => $questionsSavedCount, ]); } /** * 保存分析结果并创建掌握度快照 */ private function saveAnalysisResult(string $studentId, string $paperId, array $result): void { // 【修复】支持重复分析:先删除旧的分析结果 DB::connection('mysql')->table('exam_analysis_results') ->where('student_id', $studentId) ->where('paper_id', $paperId) ->delete(); // 插入新的分析结果 DB::connection('mysql')->table('exam_analysis_results')->insert([ 'student_id' => $studentId, 'paper_id' => $paperId, 'analysis_data' => json_encode($result), 'created_at' => now(), 'updated_at' => now(), ]); Log::info('分析结果保存完成', [ 'student_id' => $studentId, 'paper_id' => $paperId, 'data_size' => strlen(json_encode($result)), ]); // 【集成】创建知识点掌握度快照 $this->createMasterySnapshot($studentId, $paperId, $result); // 【新增】异步生成学情分析PDF try { Log::info('开始异步生成学情分析PDF', [ 'student_id' => $studentId, 'paper_id' => $paperId, ]); // 使用队列异步生成PDF,避免阻塞主流程 dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null)); Log::info('PDF生成任务已加入队列', [ 'student_id' => $studentId, 'paper_id' => $paperId, ]); } catch (\Exception $e) { Log::error('PDF生成任务加入队列失败', [ 'student_id' => $studentId, 'paper_id' => $paperId, 'error' => $e->getMessage(), ]); } } /** * 创建知识点掌握度快照 * 【集成】使用LocalAIAnalysisService的快照功能 * * 快照用途: * 1. 追踪学生掌握度变化趋势 * 2. 生成学情报告时对比历史数据 * 3. 为智能出卷提供决策依据 */ private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): void { try { // 计算快照数据 $masteryVector = $analysisResult['mastery_vector'] ?? []; $overallMastery = 0; $weakCount = 0; $strongCount = 0; foreach ($masteryVector as $kpData) { $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0; $overallMastery += $mastery; if ($mastery < 0.6) { $weakCount++; } elseif ($mastery >= 0.85) { $strongCount++; } } $kpCount = count($masteryVector); $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0; // 生成快照ID $snapshotId = 'snap_' . $paperId . '_' . now()->format('YmdHis'); // 保存到快照表 DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([ 'snapshot_id' => $snapshotId, 'student_id' => $studentId, 'paper_id' => $paperId, 'answer_record_id' => null, 'mastery_data' => json_encode($masteryVector), 'overall_mastery' => $overallMastery, 'weak_knowledge_points_count' => $weakCount, 'strong_knowledge_points_count' => $strongCount, 'snapshot_time' => now(), 'analysis_id' => null, 'created_at' => now(), 'updated_at' => now(), ]); Log::info('掌握度快照创建成功', [ 'snapshot_id' => $snapshotId, 'student_id' => $studentId, 'paper_id' => $paperId, 'overall_mastery' => $overallMastery, 'weak_count' => $weakCount, 'strong_count' => $strongCount, ]); } catch (\Exception $e) { // 快照创建失败不影响主流程 Log::warning('掌握度快照创建失败', [ 'student_id' => $studentId, 'paper_id' => $paperId, 'error' => $e->getMessage(), ]); } } /** * 判断掌握度趋势 */ /** * 评估表现水平 */ private function evaluatePerformanceLevel(float $mastery): string { if ($mastery >= 0.85) { return 'excellent'; } elseif ($mastery >= 0.70) { return 'good'; } elseif ($mastery >= 0.50) { return 'fair'; } else { return 'poor'; } } /** * 生成题目表现总结 */ private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string { if (empty($stepAnalysis)) { return '整题作答'; } $correctSteps = count(array_filter($stepAnalysis, fn($s) => $s['is_correct'])); $totalSteps = count($stepAnalysis); if ($correctSteps === $totalSteps) { return '所有步骤正确'; } elseif ($correctSteps > 0) { return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)"; } else { return '所有步骤错误'; } } /** * 生成知识点建议 */ private function generateKnowledgePointRecommendation(array $data): string { $mastery = $data['mastery']; if ($mastery >= 0.85) { return '掌握良好,可安排综合练习'; } elseif ($mastery >= 0.70) { return '基本掌握,建议加强练习'; } elseif ($mastery >= 0.50) { return '需要重点练习,建议安排专项训练'; } else { return '薄弱知识点,建议系统学习和大量练习'; } } /** * 评估整体表现 */ private function evaluateOverallPerformance(float $averageMastery): string { if ($averageMastery >= 0.85) { return '优秀'; } elseif ($averageMastery >= 0.70) { return '良好'; } elseif ($averageMastery >= 0.50) { return '一般'; } else { return '需加强'; } } /** * 计算推荐题目数量 */ private function calculateRecommendedQuestions(float $mastery): int { if ($mastery >= 0.85) { return 1; // 巩固型:1题 } elseif ($mastery >= 0.50) { return 2; // 修补型:2题 } else { return 3; // 挑战型:3题 } } /** * 确定重点类型 */ private function determineFocusType(float $mastery): string { if ($mastery >= 0.70 && $mastery < 0.85) { return 'consolidation'; // 巩固型 } elseif ($mastery < 0.70) { return 'remediation'; // 修补型 } else { return 'challenge'; // 挑战型 } } /** * 自动计算题目分数并补充未提交的题目 * * 功能: * 1. 从 paper_questions 表获取卷子的所有题目 * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误) * 3. 自动计算 score 和 score_obtained * * @param array $questions 用户提交的题目列表 * @param string $paperId 卷子ID * @return array 完整的题目列表(包含未提交的题目) */ private function autoCalculateScores(array $questions, string $paperId = ''): array { // 获取已提交题目的ID集合 $submittedQuestionIds = []; foreach ($questions as $question) { $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null; if ($qid) { $submittedQuestionIds[$qid] = true; } } // 从 paper_questions 表获取卷子的所有题目 if (!empty($paperId)) { try { $paperQuestions = DB::connection('mysql') ->table('paper_questions') ->where('paper_id', $paperId) ->get(); foreach ($paperQuestions as $pq) { // 优先用 question_bank_id,其次用 question_id $questionId = $pq->question_bank_id ?? $pq->question_id ?? null; if (empty($questionId)) { continue; } // 如果该题目未提交,补充进去 if (!isset($submittedQuestionIds[$questionId])) { $defaultScore = $pq->score ? floatval($pq->score) : 2.0; $questions[] = [ 'question_id' => $questionId, 'student_answer' => null, 'is_correct' => [1], // 未提交默认为正确 'teacher_comment' => null, 'score' => $defaultScore, 'score_obtained' => $defaultScore, // 正确则得满分 ]; Log::debug('补充未提交的题目', [ 'paper_id' => $paperId, 'question_id' => $questionId, 'default_score' => $pq->score ?? 2.0 ]); } } } catch (\Exception $e) { Log::warning('获取卷子题目列表失败', [ 'paper_id' => $paperId, 'error' => $e->getMessage() ]); } } // 为已提交的题目计算分数 foreach ($questions as &$question) { $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? ''; // 如果用户没有提供 score,尝试从数据库获取或使用默认值 if (!isset($question['score'])) { $question['score'] = $this->getQuestionDefaultScore($questionId); } // 如果用户没有提供 score_obtained,根据 is_correct 计算 if (!isset($question['score_obtained'])) { $question['score_obtained'] = $this->calculateScoreObtained( $question['score'] ?? 0, $question['is_correct'] ?? [] ); } Log::debug('自动计算分数', [ 'question_id' => $questionId, 'default_score' => $question['score'], 'score_obtained' => $question['score_obtained'], 'is_correct' => $question['is_correct'] ?? [] ]); } return $questions; } /** * 获取题目默认分数 */ private function getQuestionDefaultScore(string $questionId): float { if (empty($questionId)) { return 2.0; // 默认分数 } try { // 尝试从题库获取题目分数 $question = DB::connection('mysql') ->table('questions') ->where('id', $questionId) ->orWhere('question_code', $questionId) ->first(); if ($question && isset($question->score)) { return (float) $question->score; } // 如果没有找到,根据题目ID生成一个合理的默认分数 // 这里可以根据需要调整默认分数逻辑 return 2.0; } catch (\Exception $e) { Log::warning('获取题目默认分数失败,使用默认值', [ 'question_id' => $questionId, 'error' => $e->getMessage() ]); return 2.0; } } /** * 根据 is_correct 数组计算得分 * * @param float $totalScore 总分 * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确 * @return float 得分 */ private function calculateScoreObtained(float $totalScore, array $isCorrect): float { if (empty($isCorrect)) { return 0.0; } $correctCount = array_sum($isCorrect); $totalCount = count($isCorrect); if ($totalCount === 0) { return 0.0; } // 按正确率计算得分 $scoreRatio = $correctCount / $totalCount; return round($totalScore * $scoreRatio, 2); } }