ExamAnswerAnalysisService.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Collection;
  6. /**
  7. * 考试答题分析服务(步骤级分析)
  8. * 基于卷子分析思考文档的思路实现
  9. *
  10. * 核心流程:
  11. * 1. 接收卷子ID和每道题的对错、简答题的分步骤对错
  12. * 2. 将原子信息映射到知识点/技能
  13. * 3. 计算知识点掌握度向量
  14. * 4. 生成详细分析报告
  15. * 5. 提供智能出卷推荐依据
  16. */
  17. class ExamAnswerAnalysisService
  18. {
  19. public function __construct(
  20. private readonly MasteryCalculator $masteryCalculator,
  21. private readonly KnowledgeMasteryService $knowledgeMasteryService,
  22. private readonly LocalAIAnalysisService $aiAnalysisService,
  23. private readonly MistakeBookService $mistakeBookService
  24. ) {}
  25. /**
  26. * 分析考试答题数据
  27. *
  28. * @param array $examData 考试数据
  29. * @return array 分析结果
  30. */
  31. public function analyzeExamAnswers(array $examData): array
  32. {
  33. Log::info('开始分析考试答题', [
  34. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  35. 'student_id' => $examData['student_id'] ?? 'unknown',
  36. 'question_count' => count($examData['questions'] ?? [])
  37. ]);
  38. $studentId = $examData['student_id'];
  39. $paperId = $examData['paper_id'] ?? '';
  40. $questions = $examData['questions'] ?? [];
  41. // 0. 自动计算分数并补充未提交的题目
  42. $questions = $this->autoCalculateScores($questions, $paperId);
  43. // 更新 examData 中的 questions(包含补充的题目)
  44. $examData['questions'] = $questions;
  45. // 【公司要求】1. 获取学案基准难度(取自学案的difficulty_category)
  46. $examBaseDifficulty = $this->getExamBaseDifficulty($examData['paper_id'] ?? '');
  47. // 2. 保存答题记录到数据库
  48. $this->saveExamAnswerRecords($examData);
  49. // 3. 获取题目知识点映射
  50. $questionMappings = $this->getQuestionKnowledgeMappings($questions);
  51. // 【公司要求】4. 计算每个知识点的加权掌握度(传入学案基准难度)
  52. // 核心算法:难度映射 → 权重计算 → 数值更新(newMastery = oldMastery + change)
  53. $knowledgeMasteryVector = $this->calculateKnowledgeMasteryVector($questions, $questionMappings, $examBaseDifficulty, $studentId);
  54. // 【公司要求】5. 更新学生掌握度(包含多级父节点掌握度计算)
  55. $updatedMastery = $this->updateStudentMastery($studentId, $knowledgeMasteryVector);
  56. // 5. 生成题目维度分析
  57. $questionAnalysis = $this->analyzeQuestions($questions, $questionMappings);
  58. // 6. 生成知识点维度分析
  59. $knowledgePointAnalysis = $this->analyzeKnowledgePoints($knowledgeMasteryVector, $questionMappings);
  60. // 7. 生成整体掌握度总结
  61. $overallSummary = $this->generateOverallSummary($updatedMastery);
  62. // 8. 生成智能出卷推荐依据
  63. $smartQuizRecommendation = $this->generateSmartQuizRecommendation($updatedMastery);
  64. // 9. 保存分析结果
  65. $analysisResult = [
  66. 'paper_id' => $examData['paper_id'],
  67. 'student_id' => $studentId,
  68. 'timestamp' => now()->toISOString(),
  69. 'question_analysis' => $questionAnalysis,
  70. 'knowledge_point_analysis' => $knowledgePointAnalysis,
  71. 'overall_summary' => $overallSummary,
  72. 'smart_quiz_recommendation' => $smartQuizRecommendation,
  73. 'mastery_vector' => $updatedMastery,
  74. ];
  75. $this->saveAnalysisResult($studentId, $examData['paper_id'], $analysisResult);
  76. Log::info('考试答题分析完成', [
  77. 'student_id' => $studentId,
  78. 'paper_id' => $examData['paper_id'],
  79. 'analyzed_knowledge_points' => count($knowledgeMasteryVector)
  80. ]);
  81. return $analysisResult;
  82. }
  83. /**
  84. * 【公司要求】获取学案基准难度(取自学案的difficulty_category)
  85. *
  86. * 公司要求:
  87. * 入参需要增加 {学案基准难度}(取自学案的 difficulty_category)
  88. * @param string $paperId 试卷ID
  89. * @return int|null 学案基准难度(1-4级),失败返回null
  90. */
  91. private function getExamBaseDifficulty(string $paperId): ?int
  92. {
  93. if (empty($paperId)) {
  94. return null;
  95. }
  96. try {
  97. // 【公司要求】入参需要增加 {学案基准难度}(取自学案的 difficulty_category)
  98. // 从试卷表获取difficulty_category
  99. $paper = DB::table('papers')
  100. ->where('paper_id', $paperId)
  101. ->first();
  102. if (!$paper) {
  103. Log::warning('未找到试卷,尝试从缓存获取', ['paper_id' => $paperId]);
  104. return 2;
  105. }
  106. return $paper->difficulty_category ?? 2;
  107. } catch (\Exception $e) {
  108. Log::warning('获取学案基准难度失败,使用默认2级', [
  109. 'paper_id' => $paperId,
  110. 'error' => $e->getMessage(),
  111. ]);
  112. return 2; // 默认中等难度
  113. }
  114. }
  115. /**
  116. * 获取题目知识点映射
  117. * 【优化】优先使用批量查询,失败时降级到单条查询
  118. */
  119. private function getQuestionKnowledgeMappings(array $questions): array
  120. {
  121. $mappings = [];
  122. $failedQuestions = [];
  123. // 收集所有题目ID
  124. $questionIds = [];
  125. foreach ($questions as $question) {
  126. $questionId = $question['question_id'] ?? null;
  127. if ($questionId) {
  128. $questionIds[] = $questionId;
  129. }
  130. }
  131. // 【优化】尝试批量查询
  132. $batchResult = [];
  133. if (!empty($questionIds)) {
  134. $batchResult = $this->batchGetQuestionKnowledgePoints($questionIds);
  135. }
  136. // 遍历题目,优先使用批量结果,否则降级到单条查询
  137. foreach ($questions as $question) {
  138. $questionId = $question['question_id'] ?? null;
  139. if (!$questionId) continue;
  140. $kpMapping = [];
  141. // 优先使用批量查询结果
  142. if (isset($batchResult[$questionId])) {
  143. $kpMapping = $batchResult[$questionId];
  144. Log::debug('使用批量查询结果', [
  145. 'question_id' => $questionId,
  146. 'kp_count' => count($kpMapping)
  147. ]);
  148. } else {
  149. // 降级:使用单条查询(批量查询可能遗漏的题目)
  150. $dbKpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  151. if (!empty($dbKpMappings)) {
  152. $kpMapping = $dbKpMappings;
  153. Log::debug('降级到单条查询', [
  154. 'question_id' => $questionId,
  155. 'kp_count' => count($dbKpMappings)
  156. ]);
  157. }
  158. }
  159. // 如果仍然没有知识点信息,跳过该题目
  160. if (empty($kpMapping)) {
  161. $failedQuestions[] = $questionId;
  162. Log::warning('跳过无法获取知识点的题目', [
  163. 'question_id' => $questionId
  164. ]);
  165. continue;
  166. }
  167. $mappings[$questionId] = [
  168. 'question_id' => $questionId,
  169. 'kp_mapping' => $kpMapping
  170. ];
  171. }
  172. if (!empty($failedQuestions)) {
  173. Log::warning('部分题目无法获取知识点信息', [
  174. 'failed_questions' => $failedQuestions,
  175. 'total_questions' => count($questions),
  176. 'mapped_questions' => count($mappings)
  177. ]);
  178. }
  179. Log::info('题目知识点映射构建完成', [
  180. 'total_questions' => count($questions),
  181. 'mapped_questions' => count($mappings),
  182. 'failed_questions' => count($failedQuestions),
  183. 'batch_hit_count' => count($batchResult)
  184. ]);
  185. return $mappings;
  186. }
  187. /**
  188. * 从数据库获取题目的知识点信息(支持多知识点)
  189. * 如果题目没有直接的知识点,通过目录ID匹配知识点
  190. */
  191. private function getQuestionKnowledgePointsFromDb(string $questionId): array
  192. {
  193. $allKpMappings = [];
  194. try {
  195. // 【第一步】从 questions 表直接获取知识点字段(可能有多个)
  196. $question = DB::connection('mysql')
  197. ->table('questions')
  198. ->where('id', $questionId)
  199. ->orWhere('question_code', $questionId)
  200. ->first();
  201. if ($question) {
  202. // 检查题目的直接知识点字段
  203. $directKpCodes = [];
  204. $kpCode1 = $question->kp_code;
  205. if ($kpCode1) $directKpCodes[] = $kpCode1;
  206. // 获取每个知识点的详细信息
  207. foreach ($directKpCodes as $kpCode) {
  208. $kpInfo = DB::connection('mysql')
  209. ->table('knowledge_points')
  210. ->where('kp_code', $kpCode)
  211. ->first();
  212. if ($kpInfo) {
  213. $allKpMappings[] = [
  214. 'kp_id' => $kpCode,
  215. 'kp_name' => $kpInfo->name,
  216. 'weight' => 1.0
  217. ];
  218. } else {
  219. // 如果knowledge_points表中没有记录,仍然添加
  220. $allKpMappings[] = [
  221. 'kp_id' => $kpCode,
  222. 'kp_name' => $kpCode,
  223. 'weight' => 1.0
  224. ];
  225. }
  226. }
  227. if (!empty($directKpCodes)) {
  228. Log::debug('从题目直接字段获取知识点', [
  229. 'question_id' => $questionId,
  230. 'kp_codes' => $directKpCodes,
  231. 'mapped_count' => count($allKpMappings)
  232. ]);
  233. }
  234. }
  235. // 【第二步】如果题目没有直接的知识点,通过目录ID匹配知识点
  236. if (empty($allKpMappings) && $question) {
  237. $catalogKpMappings = $this->findKpCodesByCatalog($question);
  238. if (!empty($catalogKpMappings)) {
  239. $allKpMappings = $catalogKpMappings;
  240. Log::debug('通过目录ID匹配到知识点', [
  241. 'question_id' => $questionId,
  242. 'matched_kp_codes' => array_column($catalogKpMappings, 'kp_id'),
  243. 'matched_count' => count($catalogKpMappings)
  244. ]);
  245. }
  246. }
  247. if (empty($allKpMappings)) {
  248. Log::warning('未找到题目的知识点信息', [
  249. 'question_id' => $questionId
  250. ]);
  251. }
  252. } catch (\Exception $e) {
  253. Log::error('获取题目知识点信息失败', [
  254. 'question_id' => $questionId,
  255. 'error' => $e->getMessage()
  256. ]);
  257. }
  258. return $allKpMappings;
  259. }
  260. /**
  261. * 通过题目的目录信息匹配知识点
  262. * 使用 textbook_catalog_nodes_id -> textbook_chapter_knowledge_relation 表查询
  263. */
  264. private function findKpCodesByCatalog(object $question): array
  265. {
  266. $kpMappings = [];
  267. try {
  268. // 获取题目的教材目录节点ID
  269. $catalogNodesId = $question->textbook_catalog_nodes_id;
  270. if (!$catalogNodesId) {
  271. Log::debug('题目没有关联的教材目录节点', [
  272. 'question_id' => $question->id
  273. ]);
  274. return $kpMappings;
  275. }
  276. // 通过 catalog_chapter_id 查询关联的知识点
  277. $relations = DB::connection('mysql')
  278. ->table('textbook_chapter_knowledge_relation')
  279. ->where('catalog_chapter_id', $catalogNodesId)
  280. ->where('is_deleted', 0) // 只查询未删除的关联
  281. ->get();
  282. if ($relations->isNotEmpty()) {
  283. foreach ($relations as $relation) {
  284. $kpCode = $relation->kp_code;
  285. $kpInfo = DB::connection('mysql')
  286. ->table('knowledge_points')
  287. ->where('kp_code', $kpCode)
  288. ->first();
  289. $kpMappings[] = [
  290. 'kp_id' => $kpCode,
  291. 'kp_name' => $kpInfo->name ?? $kpCode,
  292. 'weight' => 1.0
  293. ];
  294. }
  295. Log::debug('通过教材目录节点匹配到知识点', [
  296. 'question_id' => $question->id,
  297. 'catalog_nodes_id' => $catalogNodesId,
  298. 'matched_kp_count' => count($kpMappings),
  299. 'matched_kp_codes' => array_column($kpMappings, 'kp_id')
  300. ]);
  301. } else {
  302. Log::debug('教材目录节点没有关联的知识点', [
  303. 'question_id' => $question->id,
  304. 'catalog_nodes_id' => $catalogNodesId
  305. ]);
  306. }
  307. } catch (\Exception $e) {
  308. Log::error('通过目录匹配知识点失败', [
  309. 'question_id' => $question->id,
  310. 'error' => $e->getMessage()
  311. ]);
  312. }
  313. return $kpMappings;
  314. }
  315. /**
  316. * 保留原有方法用于向后兼容,但标记为废弃
  317. */
  318. private function getQuestionKnowledgePointFromDb(string $questionId): ?array
  319. {
  320. $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  321. return !empty($kpMappings) ? $kpMappings[0] : null;
  322. }
  323. /**
  324. * 【优化】批量获取题目的知识点信息
  325. * 将 N+1 查询优化为 2-3 次批量查询
  326. *
  327. * @param array $questionIds 题目ID数组
  328. * @return array [questionId => [kpMappings...]] 映射
  329. */
  330. private function batchGetQuestionKnowledgePoints(array $questionIds): array
  331. {
  332. if (empty($questionIds)) {
  333. return [];
  334. }
  335. $result = [];
  336. $questionsNeedCatalogLookup = []; // 需要通过目录查找知识点的题目
  337. try {
  338. // 【第1步】批量查询 questions 表(1次查询)
  339. $questionsData = DB::connection('mysql')
  340. ->table('questions')
  341. ->whereIn('id', $questionIds)
  342. ->orWhereIn('question_code', $questionIds)
  343. ->get();
  344. // 建立 ID 到题目数据的映射
  345. $questionMap = [];
  346. foreach ($questionsData as $q) {
  347. $questionMap[$q->id] = $q;
  348. if ($q->question_code) {
  349. $questionMap[$q->question_code] = $q;
  350. }
  351. }
  352. // 【第2步】收集所有直接关联的 kp_code
  353. $allKpCodes = [];
  354. foreach ($questionsData as $q) {
  355. if (!empty($q->kp_code)) {
  356. $allKpCodes[] = $q->kp_code;
  357. }
  358. }
  359. // 【第3步】批量查询 knowledge_points 表(1次查询)
  360. $kpInfoMap = [];
  361. if (!empty($allKpCodes)) {
  362. $kpInfos = DB::connection('mysql')
  363. ->table('knowledge_points')
  364. ->whereIn('kp_code', array_unique($allKpCodes))
  365. ->get();
  366. foreach ($kpInfos as $kp) {
  367. $kpInfoMap[$kp->kp_code] = $kp;
  368. }
  369. }
  370. // 【第4步】收集需要通过目录查找的题目
  371. $catalogNodeIds = [];
  372. foreach ($questionsData as $q) {
  373. if (empty($q->kp_code) && !empty($q->textbook_catalog_nodes_id)) {
  374. $catalogNodeIds[] = $q->textbook_catalog_nodes_id;
  375. $questionsNeedCatalogLookup[$q->id] = $q;
  376. }
  377. }
  378. // 【第5步】批量查询目录-知识点关系(1次查询)
  379. $catalogKpMap = [];
  380. if (!empty($catalogNodeIds)) {
  381. $catalogRelations = DB::connection('mysql')
  382. ->table('textbook_chapter_knowledge_relation')
  383. ->whereIn('catalog_chapter_id', array_unique($catalogNodeIds))
  384. ->where('is_deleted', 0)
  385. ->get();
  386. // 收集目录关联的 kp_code
  387. $catalogKpCodes = [];
  388. foreach ($catalogRelations as $rel) {
  389. $catalogKpCodes[] = $rel->kp_code;
  390. if (!isset($catalogKpMap[$rel->catalog_chapter_id])) {
  391. $catalogKpMap[$rel->catalog_chapter_id] = [];
  392. }
  393. $catalogKpMap[$rel->catalog_chapter_id][] = $rel->kp_code;
  394. }
  395. // 批量查询这些知识点的信息
  396. if (!empty($catalogKpCodes)) {
  397. $catalogKpInfos = DB::connection('mysql')
  398. ->table('knowledge_points')
  399. ->whereIn('kp_code', array_unique($catalogKpCodes))
  400. ->get();
  401. foreach ($catalogKpInfos as $kp) {
  402. $kpInfoMap[$kp->kp_code] = $kp;
  403. }
  404. }
  405. }
  406. // 【第6步】组装结果
  407. foreach ($questionIds as $questionId) {
  408. $qData = $questionMap[$questionId] ?? null;
  409. if (!$qData) {
  410. Log::debug('批量查询未找到题目', ['question_id' => $questionId]);
  411. continue;
  412. }
  413. $kpMappings = [];
  414. // 方式1:直接从 kp_code 字段获取
  415. if (!empty($qData->kp_code)) {
  416. $kpCode = $qData->kp_code;
  417. $kpInfo = $kpInfoMap[$kpCode] ?? null;
  418. $kpMappings[] = [
  419. 'kp_id' => $kpCode,
  420. 'kp_name' => $kpInfo->name ?? $kpCode,
  421. 'weight' => 1.0
  422. ];
  423. }
  424. // 方式2:通过目录关系获取
  425. elseif (!empty($qData->textbook_catalog_nodes_id)) {
  426. $catalogId = $qData->textbook_catalog_nodes_id;
  427. $catalogKpCodes = $catalogKpMap[$catalogId] ?? [];
  428. foreach ($catalogKpCodes as $kpCode) {
  429. $kpInfo = $kpInfoMap[$kpCode] ?? null;
  430. $kpMappings[] = [
  431. 'kp_id' => $kpCode,
  432. 'kp_name' => $kpInfo->name ?? $kpCode,
  433. 'weight' => 1.0
  434. ];
  435. }
  436. }
  437. if (!empty($kpMappings)) {
  438. $result[$questionId] = $kpMappings;
  439. }
  440. }
  441. Log::info('批量获取题目知识点完成', [
  442. 'input_count' => count($questionIds),
  443. 'output_count' => count($result),
  444. 'query_count' => '2-4次(优化后)'
  445. ]);
  446. } catch (\Exception $e) {
  447. Log::error('批量获取题目知识点失败,将降级到单条查询', [
  448. 'question_ids' => $questionIds,
  449. 'error' => $e->getMessage()
  450. ]);
  451. // 降级:返回空,让调用方使用单条查询
  452. return [];
  453. }
  454. return $result;
  455. }
  456. /**
  457. * 从 QuestionBank API 获取题目信息
  458. */
  459. private function getQuestionFromQuestionBank(string $questionId): ?array
  460. {
  461. try {
  462. $baseUrl = config('services.question_bank_api.base_url', 'http://question-bank-api:5015');
  463. $response = Http::timeout(10)->get($baseUrl . '/questions/' . $questionId);
  464. if ($response->successful()) {
  465. $data = $response->json();
  466. return $data['data'] ?? null;
  467. }
  468. return null;
  469. } catch (\Exception $e) {
  470. Log::warning('从QuestionBank获取题目信息失败', [
  471. 'question_id' => $questionId,
  472. 'error' => $e->getMessage()
  473. ]);
  474. return null;
  475. }
  476. }
  477. /**
  478. * 批量获取题目难度
  479. *
  480. * @param array $questionIds 题目ID数组
  481. * @return array [questionId => difficulty] 映射
  482. */
  483. private function batchGetQuestionDifficulties(array $questionIds): array
  484. {
  485. if (empty($questionIds)) {
  486. return [];
  487. }
  488. $difficulties = [];
  489. try {
  490. $questions = DB::connection('mysql')
  491. ->table('questions')
  492. ->whereIn('id', $questionIds)
  493. ->orWhereIn('question_code', $questionIds)
  494. ->select(['id', 'question_code', 'difficulty'])
  495. ->get();
  496. foreach ($questions as $question) {
  497. $difficulty = $question->difficulty !== null ? floatval($question->difficulty) : 0.6;
  498. // 同时用 id 和 question_code 作为键,确保能匹配到
  499. $difficulties[$question->id] = $difficulty;
  500. if ($question->question_code) {
  501. $difficulties[$question->question_code] = $difficulty;
  502. }
  503. }
  504. } catch (\Exception $e) {
  505. Log::warning('批量获取题目难度失败', [
  506. 'question_ids' => $questionIds,
  507. 'error' => $e->getMessage()
  508. ]);
  509. }
  510. return $difficulties;
  511. }
  512. /**
  513. * 【公司要求】计算知识点掌握度向量
  514. *
  515. * 公司要求的核心算法:
  516. * 1. 难度映射:将题目中0.0-1.0的浮点数难度映射为 1-4 等级
  517. * 2. 权重计算:
  518. * - 越级(Question > {学案基准难度}):对 +0.15 / 错 -0.05
  519. * - 适应(Question = {学案基准难度}):对 +0.10 / 错 -0.10
  520. * - 降级(Question < {学案基准难度}):对 +0.05 / 错 -0.15
  521. * 3. 数值更新:newMastery = oldMastery + change,并做 0.0 ~ 1.0 的边界限制
  522. *
  523. * 核心算法说明:
  524. * 1. 从考试答题中提取每个知识点的答题记录
  525. * 2. 调用MasteryCalculator计算掌握度(包含:难度映射、权重计算、数值更新)
  526. * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
  527. *
  528. * @param array $questions 题目列表
  529. * @param array $questionMappings 题目知识点映射
  530. * @param int|null $examBaseDifficulty 学案基准难度(1-4级)
  531. * @param string|null $studentId 学生ID
  532. * @return array 知识点掌握度向量
  533. */
  534. private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array
  535. {
  536. // 按知识点聚合答题记录
  537. $knowledgeAttempts = [];
  538. // 批量获取所有题目的难度(减少数据库查询次数)
  539. $questionIds = array_filter(array_map(fn($q) => $q['question_id'] ?? $q['question_bank_id'] ?? null, $questions));
  540. $questionDifficulties = $this->batchGetQuestionDifficulties($questionIds);
  541. foreach ($questions as $question) {
  542. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  543. if (empty($questionId)) {
  544. Log::warning('calculateKnowledgeMasteryVector: 题目缺少ID', ['question' => $question]);
  545. continue;
  546. }
  547. $score = floatval($question['score_obtained'] ?? 0);
  548. $maxScore = floatval($question['score'] ?? $score);
  549. // is_correct 是数组,如 [0,1,1],表示每个步骤的正误
  550. $isCorrectArray = $question['is_correct'] ?? [];
  551. if (!is_array($isCorrectArray)) {
  552. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  553. }
  554. $mapping = $questionMappings[$questionId] ?? null;
  555. if (!$mapping || !isset($mapping['kp_mapping'])) {
  556. Log::debug('calculateKnowledgeMasteryVector: 题目无知识点映射', ['question_id' => $questionId]);
  557. continue;
  558. }
  559. // 从批量查询结果获取题目难度
  560. $questionDifficulty = $questionDifficulties[$questionId] ?? 0.6;
  561. $stepCount = count($isCorrectArray);
  562. $scorePerStep = $maxScore / max($stepCount, 1);
  563. // 根据 is_correct 数组生成步骤级答题记录
  564. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  565. $isCorrectBool = (int) $isCorrect === 1;
  566. // 为该题目关联的每个知识点创建答题记录
  567. foreach ($mapping['kp_mapping'] as $kpMapping) {
  568. $kpId = $kpMapping['kp_id'];
  569. if (!isset($knowledgeAttempts[$kpId])) {
  570. $knowledgeAttempts[$kpId] = [
  571. 'attempts' => [],
  572. 'step_details' => [],
  573. ];
  574. }
  575. // 构建答题记录(用于MasteryCalculator)
  576. $attemptRecord = [
  577. 'question_id' => $questionId,
  578. 'is_correct' => $isCorrectBool,
  579. 'step_index' => $stepIndex,
  580. 'question_difficulty' => $questionDifficulty,
  581. 'created_at' => now()->toISOString(),
  582. ];
  583. $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
  584. $knowledgeAttempts[$kpId]['step_details'][] = [
  585. 'question_id' => $questionId,
  586. 'step_index' => $stepIndex,
  587. 'score' => $isCorrectBool ? $scorePerStep : 0,
  588. 'max_score' => $scorePerStep,
  589. 'is_correct' => $isCorrectBool,
  590. ];
  591. }
  592. }
  593. }
  594. // 【公司要求】【核心】使用MasteryCalculator计算每个知识点的掌握度
  595. $masteryVector = [];
  596. foreach ($knowledgeAttempts as $kpId => $data) {
  597. $attempts = $data['attempts'];
  598. // 如果没有学案基准难度,使用默认值2(提分)
  599. $baseDifficulty = $examBaseDifficulty ?? 2;
  600. // 【公司要求】调用MasteryCalculator的核心算法(传入学案基准难度)
  601. // 该算法包含:难度映射、权重计算、数值更新(newMastery = oldMastery + change)
  602. $masteryResult = $this->masteryCalculator->calculateMasteryLevel(
  603. $studentId ?? '', // 传递学生ID,用于保存掌握度到数据库
  604. $kpId,
  605. $attempts,
  606. $baseDifficulty
  607. );
  608. // 【公司要求】只保留核心掌握度数据
  609. $masteryVector[$kpId] = [
  610. 'kp_id' => $kpId,
  611. 'mastery' => $masteryResult['mastery'],
  612. 'total_attempts' => $masteryResult['total_attempts'],
  613. 'correct_attempts' => $masteryResult['correct_attempts'],
  614. 'accuracy_rate' => $masteryResult['accuracy_rate'],
  615. 'step_details' => $data['step_details'],
  616. // 计算细节(用于调试和分析)
  617. 'calculation_details' => $masteryResult['details'] ?? [],
  618. ];
  619. }
  620. Log::info('知识点掌握度向量计算完成', [
  621. 'knowledge_points_count' => count($masteryVector),
  622. 'sample' => array_slice($masteryVector, 0, 3, true),
  623. ]);
  624. return $masteryVector;
  625. }
  626. /**
  627. * 更新学生掌握度(与历史数据合并)
  628. */
  629. private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
  630. {
  631. $updatedMastery = [];
  632. foreach ($knowledgeMasteryVector as $kpId => $data) {
  633. // 获取历史掌握度
  634. $historyMastery = DB::connection('mysql')
  635. ->table('student_knowledge_mastery')
  636. ->where('student_id', $studentId)
  637. ->where('kp_code', $kpId)
  638. ->first();
  639. $historyMasteryLevel = $historyMastery->mastery_level ?? 0.0;
  640. // 【公司要求】保存到数据库(只保存核心掌握度数据)
  641. DB::connection('mysql')
  642. ->table('student_knowledge_mastery')
  643. ->updateOrInsert(
  644. ['student_id' => $studentId, 'kp_code' => $kpId],
  645. [
  646. 'mastery_level' => $data['mastery'],
  647. 'confidence_level' => 0.0, // 不再保存置信度
  648. 'total_attempts' => ($historyMastery->total_attempts ?? 0) + 1,
  649. 'correct_attempts' => ($historyMastery->correct_attempts ?? 0) + intval($data['correct_attempts'] > 0),
  650. 'mastery_trend' => 'stable', // 不再判断趋势,统一设为stable
  651. 'last_mastery_update' => now(),
  652. 'updated_at' => now(),
  653. ]
  654. );
  655. // 【公司要求】返回值:只返回核心掌握度数据
  656. $updatedMastery[$kpId] = [
  657. 'kp_id' => $kpId,
  658. 'current_mastery' => $data['mastery'],
  659. 'previous_mastery' => $historyMasteryLevel,
  660. 'change' => $data['mastery'] - $historyMasteryLevel,
  661. 'weight' => 1,
  662. 'is_parent' => false
  663. ];
  664. }
  665. // 【修复】计算并更新父节点掌握度,同时添加到返回数组中
  666. $parentMasteryData = $this->updateParentMasteryLevels($studentId, array_keys($knowledgeMasteryVector));
  667. // 合并父节点数据到返回数组
  668. $updatedMastery = array_merge($updatedMastery, $parentMasteryData);
  669. return $updatedMastery;
  670. }
  671. /**
  672. * 【公司要求】计算并更新父节点掌握度(支持多级递归)
  673. *
  674. * 公司要求:
  675. * 1. 查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code)
  676. * 2. 平均值计算:如果一个知识点是父节点,它的掌握度不再从数据库直接读,
  677. * 而是实时计算其下所有子节点掌握度的算术平均数
  678. * 3. 多级递归:支持多级结构,能够从最底层逐级向上求平均
  679. *
  680. * 递归计算流程:
  681. * - 从最底层节点开始,逐级向上递归计算父节点掌握度
  682. * - 父节点掌握度 = 所有子节点掌握度的算术平均数
  683. * - 支持任意层级结构,递归深度限制为10级
  684. *
  685. * @param string $studentId 学生ID
  686. * @param array $childKpCodes 当前层的子节点编码列表
  687. * @param int $maxDepth 最大递归深度(防止无限递归,默认10级)
  688. * @return array 返回所有层级的父节点掌握度数据
  689. */
  690. private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array
  691. {
  692. $allParentMasteryData = [];
  693. $currentLevelChildCodes = $childKpCodes;
  694. $processedNodes = new \ArrayObject(); // 防止重复处理
  695. try {
  696. // 【公司要求】多级递归:逐级向上递归计算,支持多级结构
  697. for ($level = 0; $level < $maxDepth; $level++) {
  698. if (empty($currentLevelChildCodes)) {
  699. break; // 没有更多父节点,退出循环
  700. }
  701. // 【公司要求】查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code)
  702. // 获取当前层子节点的直接父节点
  703. $parentKpCodes = DB::connection('mysql')
  704. ->table('knowledge_points')
  705. ->whereIn('kp_code', $currentLevelChildCodes)
  706. ->whereNotNull('parent_kp_code')
  707. ->distinct()
  708. ->pluck('parent_kp_code')
  709. ->toArray();
  710. if (empty($parentKpCodes)) {
  711. Log::debug("第{$level}层没有更多父节点,递归结束");
  712. break;
  713. }
  714. $currentLevelParentData = [];
  715. foreach ($parentKpCodes as $parentKpCode) {
  716. // 防止重复处理同一节点
  717. if (isset($processedNodes[$parentKpCode])) {
  718. continue;
  719. }
  720. $processedNodes[$parentKpCode] = true;
  721. // 【公司要求】平均值计算:使用MasteryCalculator计算父节点掌握度(实时计算)
  722. // 父节点掌握度 = 所有子节点掌握度的算术平均数
  723. $parentMastery = $this->masteryCalculator->calculateParentMastery($studentId, $parentKpCode);
  724. // 获取父节点历史数据
  725. $historyParentMastery = DB::connection('mysql')
  726. ->table('student_knowledge_mastery')
  727. ->where('student_id', $studentId)
  728. ->where('kp_code', $parentKpCode)
  729. ->first();
  730. $previousMastery = $historyParentMastery->mastery_level ?? 0.0;
  731. // 【自己要求】保存父节点掌握度到数据库(只保存核心数据)
  732. DB::connection('mysql')
  733. ->table('student_knowledge_mastery')
  734. ->updateOrInsert(
  735. ['student_id' => $studentId, 'kp_code' => $parentKpCode],
  736. [
  737. 'mastery_level' => $parentMastery,
  738. 'confidence_level' => 0.0, // 不再保存置信度
  739. 'total_attempts' => 1, // 父节点不记录答题次数
  740. 'correct_attempts' => 0, // 父节点不记录正确次数
  741. 'mastery_trend' => 'stable', // 统一设为stable
  742. 'last_mastery_update' => now(),
  743. 'updated_at' => now(),
  744. ]
  745. );
  746. // 【公司要求】记录当前层级数据(移除置信度)
  747. $currentLevelParentData[$parentKpCode] = [
  748. 'kp_id' => $parentKpCode,
  749. 'current_mastery' => $parentMastery,
  750. 'previous_mastery' => $previousMastery,
  751. 'change' => $parentMastery - $previousMastery,
  752. 'weight' => 1,
  753. 'is_parent' => true,
  754. 'level' => $level + 1 // 记录层级深度
  755. ];
  756. Log::debug("第" . ($level + 1) . "层父节点掌握度已更新", [
  757. 'student_id' => $studentId,
  758. 'parent_kp_code' => $parentKpCode,
  759. 'parent_mastery' => $parentMastery,
  760. 'child_nodes_count' => count($currentLevelChildCodes)
  761. ]);
  762. }
  763. // 合并到总结果中
  764. $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData);
  765. // 【公司要求】多级递归:准备下一轮递归,从最底层逐级向上求平均
  766. // 当前层的父节点作为下一层的子节点
  767. $currentLevelChildCodes = $parentKpCodes;
  768. }
  769. if (!empty($allParentMasteryData)) {
  770. $totalParentCount = count($allParentMasteryData);
  771. $maxLevel = 0;
  772. foreach ($allParentMasteryData as $data) {
  773. $maxLevel = max($maxLevel, $data['level']);
  774. }
  775. Log::info('多级父节点掌握度计算完成', [
  776. 'student_id' => $studentId,
  777. 'child_count' => count($childKpCodes),
  778. 'total_parent_count' => $totalParentCount,
  779. 'max_level' => $maxLevel,
  780. 'all_parent_kp_codes' => array_keys($allParentMasteryData)
  781. ]);
  782. }
  783. } catch (\Exception $e) {
  784. Log::error('计算多级父节点掌握度失败', [
  785. 'student_id' => $studentId,
  786. 'child_kp_codes' => $childKpCodes,
  787. 'current_level' => $currentLevelChildCodes,
  788. 'error' => $e->getMessage(),
  789. 'trace' => $e->getTraceAsString()
  790. ]);
  791. }
  792. return $allParentMasteryData;
  793. }
  794. /**
  795. * 生成题目维度分析(包含AI分析和解题思路)
  796. */
  797. private function analyzeQuestions(array $questions, array $questionMappings): array
  798. {
  799. $analysis = [];
  800. foreach ($questions as $question) {
  801. $questionId = $question['question_id'];
  802. $score = floatval($question['score_obtained'] ?? 0);
  803. $maxScore = floatval($question['score'] ?? $score);
  804. $steps = $question['steps'] ?? [];
  805. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  806. $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
  807. if (empty($mapping['kp_mapping'])) {
  808. Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]);
  809. continue;
  810. }
  811. $kpCode = $mapping['kp_mapping'][0]['kp_id'];
  812. // 步骤分析
  813. $stepAnalysis = [];
  814. if (!empty($steps)) {
  815. foreach ($steps as $step) {
  816. $kpId = $step['kp_id'];
  817. if (empty($kpId)) {
  818. Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
  819. 'question_id' => $questionId,
  820. 'step_index' => $step['step_index'] ?? 'unknown'
  821. ]);
  822. continue;
  823. }
  824. $stepAnalysis[] = [
  825. 'step_index' => $step['step_index'],
  826. 'is_correct' => $step['is_correct'],
  827. 'kp_id' => $kpId,
  828. 'description' => $step['description'] ?? ''
  829. ];
  830. }
  831. }
  832. // 知识点关联
  833. $knowledgePoints = array_map(function($kp) {
  834. return [
  835. 'kp_id' => $kp['kp_id'],
  836. 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
  837. 'weight' => $kp['weight'] ?? 1.0
  838. ];
  839. }, $mapping['kp_mapping']);
  840. // 【集成】调用AI分析服务,获取解题思路和错误分析
  841. $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);
  842. $analysis[] = [
  843. 'question_id' => $questionId,
  844. 'score_obtained' => $score,
  845. 'max_score' => $maxScore,
  846. 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
  847. 'is_correct' => $isCorrect,
  848. 'step_analysis' => $stepAnalysis,
  849. 'knowledge_points' => $knowledgePoints,
  850. 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
  851. // 【新增】解题思路和错误分析
  852. 'solution_process' => $aiAnalysis['solution_process'] ?? '',
  853. 'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
  854. 'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
  855. 'suggestions' => $aiAnalysis['suggestions'] ?? '',
  856. 'next_steps' => $aiAnalysis['next_steps'] ?? [],
  857. ];
  858. }
  859. return $analysis;
  860. }
  861. /**
  862. * 获取题目的AI分析(解题思路、错误分析)
  863. */
  864. private function getQuestionAIAnalysis(array $question, array $mapping): array
  865. {
  866. $isCorrect = $question['is_correct'] ?? false;
  867. $score = floatval($question['score_obtained'] ?? 0);
  868. $maxScore = floatval($question['score'] ?? 10);
  869. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null;
  870. if (empty($kpCode)) {
  871. Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [
  872. 'question_id' => $question['question_id'] ?? 'unknown',
  873. 'mapping' => $mapping
  874. ]);
  875. $kpCode = 'UNKNOWN_KP';
  876. }
  877. // 调用LocalAIAnalysisService进行分析
  878. try {
  879. $analysisResult = $this->aiAnalysisService->analyzeAnswer([
  880. 'question_id' => $question['question_id'],
  881. 'question_text' => $question['question_text'] ?? '',
  882. 'student_answer' => $question['student_answer'] ?? '',
  883. 'correct_answer' => $question['correct_answer'] ?? '',
  884. 'score' => $score,
  885. 'max_score' => $maxScore,
  886. 'kp_code' => $kpCode,
  887. ]);
  888. $data = $analysisResult['data'] ?? [];
  889. // 根据正确性生成不同的解题思路
  890. if ($isCorrect) {
  891. return [
  892. 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰',
  893. 'error_analysis' => '',
  894. 'mistake_type' => '',
  895. 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
  896. 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
  897. ];
  898. }
  899. // 错误题目:返回详细分析
  900. return [
  901. 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
  902. 'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
  903. 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
  904. 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
  905. 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
  906. ];
  907. } catch (\Exception $e) {
  908. Log::warning('AI分析失败,使用默认分析', [
  909. 'question_id' => $question['question_id'],
  910. 'error' => $e->getMessage(),
  911. ]);
  912. // 回退到基础分析
  913. return $this->getFallbackAnalysis($question, $isCorrect);
  914. }
  915. }
  916. /**
  917. * 回退分析(当AI分析失败时)
  918. */
  919. private function getFallbackAnalysis(array $question, bool $isCorrect): array
  920. {
  921. if ($isCorrect) {
  922. return [
  923. 'solution_process' => '该题作答正确',
  924. 'error_analysis' => '',
  925. 'mistake_type' => '',
  926. 'suggestions' => '继续保持',
  927. 'next_steps' => ['尝试更高难度的题目'],
  928. ];
  929. }
  930. $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);
  931. return [
  932. 'solution_process' => '请参考标准答案和解题步骤',
  933. 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
  934. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
  935. 'suggestions' => '建议复习相关知识点,加强练习',
  936. 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
  937. ];
  938. }
  939. /**
  940. * 生成知识点维度分析
  941. */
  942. private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
  943. {
  944. $analysis = [];
  945. foreach ($knowledgeMasteryVector as $kpId => $data) {
  946. // 【公司要求】移除置信度,只保留核心掌握度分析
  947. $analysis[] = [
  948. 'kp_id' => $kpId,
  949. 'mastery_level' => $data['mastery'],
  950. 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
  951. 'evidence_count' => count($data['step_details']),
  952. 'step_evidence' => $data['step_details'],
  953. 'recommendation' => $this->generateKnowledgePointRecommendation($data)
  954. ];
  955. }
  956. return $analysis;
  957. }
  958. /**
  959. * 生成整体掌握度总结
  960. */
  961. private function generateOverallSummary(array $updatedMastery): array
  962. {
  963. $knowledgePoints = array_values($updatedMastery);
  964. if (empty($knowledgePoints)) {
  965. return [
  966. 'total_knowledge_points' => 0,
  967. 'average_mastery' => 0,
  968. 'mastery_distribution' => [
  969. 'mastered' => 0,
  970. 'good' => 0,
  971. 'weak' => 0
  972. ],
  973. 'top_strengths' => [],
  974. 'top_weaknesses' => []
  975. ];
  976. }
  977. // 计算平均掌握度(只计算子节点,不包括父节点)
  978. $childNodes = array_filter($knowledgePoints, fn($kp) => !($kp['is_parent'] ?? false));
  979. $totalChildNodes = count($childNodes);
  980. if ($totalChildNodes === 0) {
  981. // 如果没有子节点,只计算所有节点
  982. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  983. } else {
  984. // 计算所有节点的平均掌握度(包括父节点)
  985. $allMastery = array_column($knowledgePoints, 'current_mastery');
  986. $averageMastery = array_sum($allMastery) / count($allMastery);
  987. }
  988. // 掌握度分布(只统计子节点)
  989. $mastered = array_filter($childNodes, fn($kp) => $kp['current_mastery'] >= 0.85);
  990. $good = array_filter($childNodes, fn($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  991. $weak = array_filter($childNodes, fn($kp) => $kp['current_mastery'] < 0.70);
  992. // 排序找出优势和薄弱点(只包括子节点)
  993. usort($childNodes, fn($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  994. $topStrengths = array_slice($childNodes, 0, 3);
  995. $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);
  996. // 统计父子节点数量
  997. $childCount = count(array_filter($knowledgePoints, fn($kp) => !($kp['is_parent'] ?? false)));
  998. $parentCount = count(array_filter($knowledgePoints, fn($kp) => $kp['is_parent'] ?? false));
  999. return [
  1000. 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
  1001. 'child_nodes_count' => $childCount,
  1002. 'parent_nodes_count' => $parentCount,
  1003. 'average_mastery' => round($averageMastery, 4),
  1004. 'mastery_distribution' => [
  1005. 'mastered' => count($mastered),
  1006. 'good' => count($good),
  1007. 'weak' => count($weak)
  1008. ],
  1009. 'top_strengths' => $topStrengths,
  1010. 'top_weaknesses' => $topWeaknesses,
  1011. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery)
  1012. ];
  1013. }
  1014. /**
  1015. * 生成智能出卷推荐依据
  1016. * 基于文档中的推荐优先级算法
  1017. */
  1018. private function generateSmartQuizRecommendation(array $updatedMastery): array
  1019. {
  1020. $recommendations = [];
  1021. // 只对子节点生成推荐,忽略父节点
  1022. foreach ($updatedMastery as $kpId => $data) {
  1023. // 跳过父节点
  1024. if ($data['is_parent'] ?? false) {
  1025. continue;
  1026. }
  1027. $mastery = $data['current_mastery'];
  1028. // 【公司要求】移除置信度,只使用掌握度计算推荐
  1029. $weight = $data['weight'];
  1030. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  1031. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  1032. $importance = 1.0;
  1033. // 覆盖需求:最近没考过或考得少,值大
  1034. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  1035. $priority = (1 - $mastery) * $importance * $coverageNeed;
  1036. $recommendations[] = [
  1037. 'kp_id' => $kpId,
  1038. 'current_mastery' => $mastery,
  1039. 'priority' => $priority,
  1040. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  1041. 'focus_type' => $this->determineFocusType($mastery)
  1042. ];
  1043. }
  1044. // 按优先级排序
  1045. usort($recommendations, fn($a, $b) => $b['priority'] <=> $a['priority']);
  1046. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  1047. $totalRecommendations = count($recommendations);
  1048. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  1049. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  1050. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  1051. return [
  1052. 'priority_list' => $recommendations,
  1053. 'quiz_structure' => [
  1054. 'consolidation_type' => $consolidation,
  1055. 'remediation_type' => $remediation,
  1056. 'challenge_type' => $challenge
  1057. ],
  1058. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions'))
  1059. ];
  1060. }
  1061. /**
  1062. * 保存考试答题记录
  1063. *
  1064. * 入参格式示例:
  1065. * {
  1066. * "question_bank_id": "12979",
  1067. * "student_answer": "C",
  1068. * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确
  1069. * "teacher_comment": null
  1070. * }
  1071. *
  1072. * is_correct 数组说明:
  1073. * - 单选题:[1] 或 [0],长度为1
  1074. * - 填空题:[1, 0, 1],每个空一个元素
  1075. * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素
  1076. */
  1077. /**
  1078. * 保存错题记录
  1079. *
  1080. * @param string $studentId 学生ID
  1081. * @param string $questionId 题目ID
  1082. * @param string $examId 考试ID
  1083. * @param array $question 题目数据
  1084. * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null)
  1085. */
  1086. private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
  1087. {
  1088. try {
  1089. // 如果 $kpMapping 是数组,说明是多个 kp_id
  1090. // 如果是关联数组,说明是单个 kpMapping(兼容旧调用)
  1091. $kpIds = null;
  1092. if (is_array($kpMapping)) {
  1093. // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping)
  1094. if (isset($kpMapping[0])) {
  1095. // 数组的数组:[[kp_id: '...'], [kp_id: '...']]
  1096. $kpIds = array_column($kpMapping, 'kp_id');
  1097. } else {
  1098. // 关联数组:[kp_id: '...']
  1099. $kpIds = [$kpMapping['kp_id']];
  1100. }
  1101. }
  1102. $payload = [
  1103. 'student_id' => $studentId,
  1104. 'question_id' => $questionId,
  1105. 'paper_id' => $examId,
  1106. 'my_answer' => $question['student_answer'] ?? null,
  1107. 'correct_answer' => null, // 可以从题目表获取
  1108. 'question_text' => null, // 可以从题目表获取
  1109. 'knowledge_point' => null, // 不保存name,只保存kp_ids
  1110. 'kp_ids' => $kpIds, // 保存为数组格式
  1111. 'source' => $examId, // 来源标记使用卷子ID
  1112. 'happened_at' => now(),
  1113. ];
  1114. $result = $this->mistakeBookService->createMistake($payload);
  1115. if (($result['duplicate'] ?? false) === false) {
  1116. Log::debug('错题记录保存成功', [
  1117. 'student_id' => $studentId,
  1118. 'question_id' => $questionId,
  1119. 'mistake_id' => $result['mistake_id'] ?? null
  1120. ]);
  1121. }
  1122. } catch (\Exception $e) {
  1123. Log::warning('错题记录保存失败(不中断主流程)', [
  1124. 'student_id' => $studentId,
  1125. 'question_id' => $questionId,
  1126. 'exam_id' => $examId,
  1127. 'error' => $e->getMessage()
  1128. ]);
  1129. }
  1130. }
  1131. private function saveExamAnswerRecords(array $examData): void
  1132. {
  1133. $studentId = $examData['student_id'];
  1134. $examId = $examData['paper_id'];
  1135. // 先清理该考试的所有答题记录(支持重复提交)
  1136. // delete() 方法即使没有匹配数据也不会报错,返回0
  1137. try {
  1138. DB::connection('mysql')->table('student_answer_questions')
  1139. ->where('student_id', $studentId)
  1140. ->where('exam_id', $examId)
  1141. ->delete();
  1142. DB::connection('mysql')->table('student_answer_steps')
  1143. ->where('student_id', $studentId)
  1144. ->where('exam_id', $examId)
  1145. ->delete();
  1146. } catch (\Exception $e) {
  1147. Log::warning('清理旧答题记录时出错(可忽略)', [
  1148. 'student_id' => $studentId,
  1149. 'exam_id' => $examId,
  1150. 'error' => $e->getMessage(),
  1151. ]);
  1152. }
  1153. $stepsSavedCount = 0;
  1154. $questionsSavedCount = 0;
  1155. foreach ($examData['questions'] as $question) {
  1156. // 兼容两种字段名:question_id 或 question_bank_id
  1157. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1158. if (empty($questionId)) {
  1159. Log::warning('题目缺少ID,跳过保存', ['question' => $question]);
  1160. continue;
  1161. }
  1162. // 从 is_correct 数组确定步骤数量
  1163. $isCorrectArray = $question['is_correct'] ?? [];
  1164. if (!is_array($isCorrectArray)) {
  1165. // 兼容非数组情况,转换为数组
  1166. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1167. }
  1168. $stepCount = count($isCorrectArray);
  1169. // 获取该题目关联的知识点(可能多个)
  1170. $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  1171. if ($stepCount > 1 || !empty($kpMappings)) {
  1172. // 多步骤题目:保存步骤级记录
  1173. // 每个步骤对应 is_correct 数组中的一个元素,先使用平均分来代替
  1174. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1175. // 【优化】先收集错误知识点,避免重复调用 saveMistakeRecord
  1176. $hasMistake = false;
  1177. $allErrorKpCodes = [];
  1178. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1179. $isCorrectBool = (int) $isCorrect === 1;
  1180. // 如果有知识点映射,为每个知识点保存记录
  1181. if (!empty($kpMappings)) {
  1182. foreach ($kpMappings as $kpMapping) {
  1183. try {
  1184. // 【修复】先检查记录是否已存在,避免重复键错误
  1185. $exists = DB::connection('mysql')->table('student_answer_steps')
  1186. ->where('student_id', $studentId)
  1187. ->where('exam_id', $examId)
  1188. ->where('question_id', $questionId)
  1189. ->where('step_index', $stepIndex)
  1190. ->where('kp_id', $kpMapping['kp_id'])
  1191. ->exists();
  1192. if (!$exists) {
  1193. DB::connection('mysql')->table('student_answer_steps')->insert([
  1194. 'student_id' => $studentId,
  1195. 'exam_id' => $examId,
  1196. 'question_id' => $questionId,
  1197. 'step_index' => $stepIndex,
  1198. 'kp_id' => $kpMapping['kp_id'],
  1199. 'is_correct' => $isCorrectBool ? 1 : 0,
  1200. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1201. 'created_at' => now(),
  1202. 'updated_at' => now(),
  1203. ]);
  1204. $stepsSavedCount++;
  1205. Log::debug('步骤记录保存成功', [
  1206. 'student_id' => $studentId,
  1207. 'question_id' => $questionId,
  1208. 'step_index' => $stepIndex,
  1209. 'kp_id' => $kpMapping['kp_id'],
  1210. ]);
  1211. } else {
  1212. Log::debug('步骤记录已存在,跳过保存', [
  1213. 'student_id' => $studentId,
  1214. 'question_id' => $questionId,
  1215. 'step_index' => $stepIndex,
  1216. 'kp_id' => $kpMapping['kp_id'],
  1217. ]);
  1218. }
  1219. // 收集错误知识点(不重复调用 saveMistakeRecord)
  1220. if (!$isCorrectBool) {
  1221. $hasMistake = true;
  1222. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1223. }
  1224. } catch (\Exception $e) {
  1225. Log::warning('保存步骤记录失败', [
  1226. 'student_id' => $studentId,
  1227. 'question_id' => $questionId,
  1228. 'step_index' => $stepIndex,
  1229. 'kp_id' => $kpMapping['kp_id'],
  1230. 'error' => $e->getMessage(),
  1231. ]);
  1232. }
  1233. }
  1234. } else {
  1235. // 没有知识点映射,仍保存步骤但 kp_id 为空
  1236. try {
  1237. DB::connection('mysql')->table('student_answer_steps')->insert([
  1238. 'student_id' => $studentId,
  1239. 'exam_id' => $examId,
  1240. 'question_id' => $questionId,
  1241. 'step_index' => $stepIndex,
  1242. 'kp_id' => null,
  1243. 'is_correct' => $isCorrectBool ? 1 : 0,
  1244. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1245. 'created_at' => now(),
  1246. 'updated_at' => now(),
  1247. ]);
  1248. $stepsSavedCount++;
  1249. // 标记有错误(无知识点映射)
  1250. if (!$isCorrectBool) {
  1251. $hasMistake = true;
  1252. }
  1253. } catch (\Exception $e) {
  1254. Log::warning('保存步骤记录失败(无知识点)', [
  1255. 'student_id' => $studentId,
  1256. 'question_id' => $questionId,
  1257. 'step_index' => $stepIndex,
  1258. 'error' => $e->getMessage(),
  1259. ]);
  1260. }
  1261. }
  1262. }
  1263. // 【错题本】一次性保存错题记录(合并所有错误知识点)
  1264. if ($hasMistake) {
  1265. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1266. // 转换为 kpMapping 数组格式:[[kp_id: '...'], [kp_id: '...']]
  1267. $kpMappingArray = array_map(fn($code) => ['kp_id' => $code], $uniqueKpCodes);
  1268. $this->saveMistakeRecord($studentId, $questionId, $examId, $question, $kpMappingArray);
  1269. }
  1270. } else {
  1271. // 单步骤题目:保存题目级记录
  1272. $isQuestionCorrect = (($question['score_obtained'] ?? 0) > 0);
  1273. try {
  1274. DB::connection('mysql')->table('student_answer_questions')->insert([
  1275. 'student_id' => $studentId,
  1276. 'exam_id' => $examId,
  1277. 'question_id' => $questionId,
  1278. 'score_obtained' => $question['score_obtained'] ?? 0,
  1279. 'max_score' => $question['score'] ?? 0,
  1280. 'created_at' => now(),
  1281. 'updated_at' => now(),
  1282. ]);
  1283. $questionsSavedCount++;
  1284. // 【错题本】保存错题记录(题目级错误)
  1285. if (!$isQuestionCorrect) {
  1286. // 收集所有知识点,转换为数组格式
  1287. $kpMappingArray = !empty($kpMappings)
  1288. ? array_map(fn($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1289. : null;
  1290. $this->saveMistakeRecord($studentId, $questionId, $examId, $question, $kpMappingArray);
  1291. }
  1292. } catch (\Exception $e) {
  1293. Log::warning('保存题目级记录失败', [
  1294. 'student_id' => $studentId,
  1295. 'exam_id' => $examId,
  1296. 'question_id' => $questionId,
  1297. 'error' => $e->getMessage(),
  1298. ]);
  1299. }
  1300. }
  1301. }
  1302. Log::info('答题记录保存完成', [
  1303. 'student_id' => $studentId,
  1304. 'exam_id' => $examId,
  1305. 'total_questions' => count($examData['questions']),
  1306. 'steps_saved' => $stepsSavedCount,
  1307. 'questions_saved' => $questionsSavedCount,
  1308. ]);
  1309. }
  1310. /**
  1311. * 保存分析结果并创建掌握度快照
  1312. */
  1313. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  1314. {
  1315. // 【修复】支持重复分析:先删除旧的分析结果
  1316. DB::connection('mysql')->table('exam_analysis_results')
  1317. ->where('student_id', $studentId)
  1318. ->where('paper_id', $paperId)
  1319. ->delete();
  1320. // 插入新的分析结果
  1321. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1322. 'student_id' => $studentId,
  1323. 'paper_id' => $paperId,
  1324. 'analysis_data' => json_encode($result),
  1325. 'created_at' => now(),
  1326. 'updated_at' => now(),
  1327. ]);
  1328. Log::info('分析结果保存完成', [
  1329. 'student_id' => $studentId,
  1330. 'paper_id' => $paperId,
  1331. 'data_size' => strlen(json_encode($result)),
  1332. ]);
  1333. // 【集成】创建知识点掌握度快照
  1334. $this->createMasterySnapshot($studentId, $paperId, $result);
  1335. // 【新增】异步生成学情分析PDF
  1336. try {
  1337. Log::info('开始异步生成学情分析PDF', [
  1338. 'student_id' => $studentId,
  1339. 'paper_id' => $paperId,
  1340. ]);
  1341. // 使用队列异步生成PDF,避免阻塞主流程
  1342. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1343. Log::info('PDF生成任务已加入队列', [
  1344. 'student_id' => $studentId,
  1345. 'paper_id' => $paperId,
  1346. ]);
  1347. } catch (\Exception $e) {
  1348. Log::error('PDF生成任务加入队列失败', [
  1349. 'student_id' => $studentId,
  1350. 'paper_id' => $paperId,
  1351. 'error' => $e->getMessage(),
  1352. ]);
  1353. }
  1354. }
  1355. /**
  1356. * 创建知识点掌握度快照
  1357. * 【集成】使用LocalAIAnalysisService的快照功能
  1358. *
  1359. * 快照用途:
  1360. * 1. 追踪学生掌握度变化趋势
  1361. * 2. 生成学情报告时对比历史数据
  1362. * 3. 为智能出卷提供决策依据
  1363. */
  1364. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): void
  1365. {
  1366. try {
  1367. // 计算快照数据
  1368. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1369. $overallMastery = 0;
  1370. $weakCount = 0;
  1371. $strongCount = 0;
  1372. foreach ($masteryVector as $kpData) {
  1373. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1374. $overallMastery += $mastery;
  1375. if ($mastery < 0.6) {
  1376. $weakCount++;
  1377. } elseif ($mastery >= 0.85) {
  1378. $strongCount++;
  1379. }
  1380. }
  1381. $kpCount = count($masteryVector);
  1382. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1383. // 生成快照ID
  1384. $snapshotId = 'snap_' . $paperId . '_' . now()->format('YmdHis');
  1385. // 保存到快照表
  1386. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1387. 'snapshot_id' => $snapshotId,
  1388. 'student_id' => $studentId,
  1389. 'paper_id' => $paperId,
  1390. 'answer_record_id' => null,
  1391. 'mastery_data' => json_encode($masteryVector),
  1392. 'overall_mastery' => $overallMastery,
  1393. 'weak_knowledge_points_count' => $weakCount,
  1394. 'strong_knowledge_points_count' => $strongCount,
  1395. 'snapshot_time' => now(),
  1396. 'analysis_id' => null,
  1397. 'created_at' => now(),
  1398. 'updated_at' => now(),
  1399. ]);
  1400. Log::info('掌握度快照创建成功', [
  1401. 'snapshot_id' => $snapshotId,
  1402. 'student_id' => $studentId,
  1403. 'paper_id' => $paperId,
  1404. 'overall_mastery' => $overallMastery,
  1405. 'weak_count' => $weakCount,
  1406. 'strong_count' => $strongCount,
  1407. ]);
  1408. } catch (\Exception $e) {
  1409. // 快照创建失败不影响主流程
  1410. Log::warning('掌握度快照创建失败', [
  1411. 'student_id' => $studentId,
  1412. 'paper_id' => $paperId,
  1413. 'error' => $e->getMessage(),
  1414. ]);
  1415. }
  1416. }
  1417. /**
  1418. * 判断掌握度趋势
  1419. */
  1420. /**
  1421. * 评估表现水平
  1422. */
  1423. private function evaluatePerformanceLevel(float $mastery): string
  1424. {
  1425. if ($mastery >= 0.85) {
  1426. return 'excellent';
  1427. } elseif ($mastery >= 0.70) {
  1428. return 'good';
  1429. } elseif ($mastery >= 0.50) {
  1430. return 'fair';
  1431. } else {
  1432. return 'poor';
  1433. }
  1434. }
  1435. /**
  1436. * 生成题目表现总结
  1437. */
  1438. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1439. {
  1440. if (empty($stepAnalysis)) {
  1441. return '整题作答';
  1442. }
  1443. $correctSteps = count(array_filter($stepAnalysis, fn($s) => $s['is_correct']));
  1444. $totalSteps = count($stepAnalysis);
  1445. if ($correctSteps === $totalSteps) {
  1446. return '所有步骤正确';
  1447. } elseif ($correctSteps > 0) {
  1448. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1449. } else {
  1450. return '所有步骤错误';
  1451. }
  1452. }
  1453. /**
  1454. * 生成知识点建议
  1455. */
  1456. private function generateKnowledgePointRecommendation(array $data): string
  1457. {
  1458. $mastery = $data['mastery'];
  1459. if ($mastery >= 0.85) {
  1460. return '掌握良好,可安排综合练习';
  1461. } elseif ($mastery >= 0.70) {
  1462. return '基本掌握,建议加强练习';
  1463. } elseif ($mastery >= 0.50) {
  1464. return '需要重点练习,建议安排专项训练';
  1465. } else {
  1466. return '薄弱知识点,建议系统学习和大量练习';
  1467. }
  1468. }
  1469. /**
  1470. * 评估整体表现
  1471. */
  1472. private function evaluateOverallPerformance(float $averageMastery): string
  1473. {
  1474. if ($averageMastery >= 0.85) {
  1475. return '优秀';
  1476. } elseif ($averageMastery >= 0.70) {
  1477. return '良好';
  1478. } elseif ($averageMastery >= 0.50) {
  1479. return '一般';
  1480. } else {
  1481. return '需加强';
  1482. }
  1483. }
  1484. /**
  1485. * 计算推荐题目数量
  1486. */
  1487. private function calculateRecommendedQuestions(float $mastery): int
  1488. {
  1489. if ($mastery >= 0.85) {
  1490. return 1; // 巩固型:1题
  1491. } elseif ($mastery >= 0.50) {
  1492. return 2; // 修补型:2题
  1493. } else {
  1494. return 3; // 挑战型:3题
  1495. }
  1496. }
  1497. /**
  1498. * 确定重点类型
  1499. */
  1500. private function determineFocusType(float $mastery): string
  1501. {
  1502. if ($mastery >= 0.70 && $mastery < 0.85) {
  1503. return 'consolidation'; // 巩固型
  1504. } elseif ($mastery < 0.70) {
  1505. return 'remediation'; // 修补型
  1506. } else {
  1507. return 'challenge'; // 挑战型
  1508. }
  1509. }
  1510. /**
  1511. * 自动计算题目分数并补充未提交的题目
  1512. *
  1513. * 功能:
  1514. * 1. 从 paper_questions 表获取卷子的所有题目
  1515. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1516. * 3. 自动计算 score 和 score_obtained
  1517. *
  1518. * @param array $questions 用户提交的题目列表
  1519. * @param string $paperId 卷子ID
  1520. * @return array 完整的题目列表(包含未提交的题目)
  1521. */
  1522. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1523. {
  1524. // 获取已提交题目的ID集合
  1525. $submittedQuestionIds = [];
  1526. foreach ($questions as $question) {
  1527. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1528. if ($qid) {
  1529. $submittedQuestionIds[$qid] = true;
  1530. }
  1531. }
  1532. // 从 paper_questions 表获取卷子的所有题目
  1533. if (!empty($paperId)) {
  1534. try {
  1535. $paperQuestions = DB::connection('mysql')
  1536. ->table('paper_questions')
  1537. ->where('paper_id', $paperId)
  1538. ->get();
  1539. foreach ($paperQuestions as $pq) {
  1540. // 优先用 question_bank_id,其次用 question_id
  1541. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1542. if (empty($questionId)) {
  1543. continue;
  1544. }
  1545. // 如果该题目未提交,补充进去
  1546. if (!isset($submittedQuestionIds[$questionId])) {
  1547. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1548. $questions[] = [
  1549. 'question_id' => $questionId,
  1550. 'student_answer' => null,
  1551. 'is_correct' => [1], // 未提交默认为正确
  1552. 'teacher_comment' => null,
  1553. 'score' => $defaultScore,
  1554. 'score_obtained' => $defaultScore, // 正确则得满分
  1555. ];
  1556. Log::debug('补充未提交的题目', [
  1557. 'paper_id' => $paperId,
  1558. 'question_id' => $questionId,
  1559. 'default_score' => $pq->score ?? 2.0
  1560. ]);
  1561. }
  1562. }
  1563. } catch (\Exception $e) {
  1564. Log::warning('获取卷子题目列表失败', [
  1565. 'paper_id' => $paperId,
  1566. 'error' => $e->getMessage()
  1567. ]);
  1568. }
  1569. }
  1570. // 为已提交的题目计算分数
  1571. foreach ($questions as &$question) {
  1572. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1573. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1574. if (!isset($question['score'])) {
  1575. $question['score'] = $this->getQuestionDefaultScore($questionId);
  1576. }
  1577. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1578. if (!isset($question['score_obtained'])) {
  1579. $question['score_obtained'] = $this->calculateScoreObtained(
  1580. $question['score'] ?? 0,
  1581. $question['is_correct'] ?? []
  1582. );
  1583. }
  1584. Log::debug('自动计算分数', [
  1585. 'question_id' => $questionId,
  1586. 'default_score' => $question['score'],
  1587. 'score_obtained' => $question['score_obtained'],
  1588. 'is_correct' => $question['is_correct'] ?? []
  1589. ]);
  1590. }
  1591. return $questions;
  1592. }
  1593. /**
  1594. * 获取题目默认分数
  1595. */
  1596. private function getQuestionDefaultScore(string $questionId): float
  1597. {
  1598. if (empty($questionId)) {
  1599. return 2.0; // 默认分数
  1600. }
  1601. try {
  1602. // 尝试从题库获取题目分数
  1603. $question = DB::connection('mysql')
  1604. ->table('questions')
  1605. ->where('id', $questionId)
  1606. ->orWhere('question_code', $questionId)
  1607. ->first();
  1608. if ($question && isset($question->score)) {
  1609. return (float) $question->score;
  1610. }
  1611. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1612. // 这里可以根据需要调整默认分数逻辑
  1613. return 2.0;
  1614. } catch (\Exception $e) {
  1615. Log::warning('获取题目默认分数失败,使用默认值', [
  1616. 'question_id' => $questionId,
  1617. 'error' => $e->getMessage()
  1618. ]);
  1619. return 2.0;
  1620. }
  1621. }
  1622. /**
  1623. * 根据 is_correct 数组计算得分
  1624. *
  1625. * @param float $totalScore 总分
  1626. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1627. * @return float 得分
  1628. */
  1629. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1630. {
  1631. if (empty($isCorrect)) {
  1632. return 0.0;
  1633. }
  1634. $correctCount = array_sum($isCorrect);
  1635. $totalCount = count($isCorrect);
  1636. if ($totalCount === 0) {
  1637. return 0.0;
  1638. }
  1639. // 按正确率计算得分
  1640. $scoreRatio = $correctCount / $totalCount;
  1641. return round($totalScore * $scoreRatio, 2);
  1642. }
  1643. }