IntelligentExamController.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\MistakeRecord;
  5. use App\Models\Paper;
  6. use App\Models\Student;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\ExternalIdService;
  9. use App\Services\LearningAnalyticsService;
  10. use App\Services\PaperPayloadService;
  11. use App\Services\QuestionBankService;
  12. use App\Services\TaskManager;
  13. use Illuminate\Http\JsonResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. class IntelligentExamController extends Controller
  18. {
  19. private LearningAnalyticsService $learningAnalyticsService;
  20. private QuestionBankService $questionBankService;
  21. private ExamPdfExportService $pdfExportService;
  22. private PaperPayloadService $paperPayloadService;
  23. private TaskManager $taskManager;
  24. private ExternalIdService $externalIdService;
  25. public function __construct(
  26. LearningAnalyticsService $learningAnalyticsService,
  27. QuestionBankService $questionBankService,
  28. ExamPdfExportService $pdfExportService,
  29. PaperPayloadService $paperPayloadService,
  30. TaskManager $taskManager,
  31. ExternalIdService $externalIdService
  32. ) {
  33. $this->learningAnalyticsService = $learningAnalyticsService;
  34. $this->questionBankService = $questionBankService;
  35. $this->pdfExportService = $pdfExportService;
  36. $this->paperPayloadService = $paperPayloadService;
  37. $this->taskManager = $taskManager;
  38. $this->externalIdService = $externalIdService;
  39. }
  40. /**
  41. * 外部API:生成智能试卷(异步模式)
  42. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  43. */
  44. public function store(Request $request): JsonResponse
  45. {
  46. // 优先从body获取数据,不使用query params
  47. $payload = $request->json()->all();
  48. if (empty($payload)) {
  49. $payload = $request->all();
  50. }
  51. $normalized = $this->normalizePayload($payload);
  52. $validator = validator($normalized, [
  53. 'student_id' => 'required|string|min:1|regex:/^\\d+$/', // 接受字符串或数字类型,如"1764913638"或1764913638
  54. 'teacher_id' => 'required|string|min:1|regex:/^\\d+$/',
  55. 'paper_name' => 'nullable|string|max:255',
  56. 'grade' => 'required|integer|min:1|max:12', // 支持小学1-6、初中7-9、高中10-12
  57. 'student_name' => 'required|string|max:50',
  58. 'teacher_name' => 'required|string|max:50',
  59. 'total_questions' => 'nullable|integer|min:1|max:100',
  60. 'difficulty_category' => 'nullable|integer|in:0,1,2,3,4',
  61. 'kp_codes' => 'nullable|array',
  62. 'kp_codes.*' => 'string',
  63. 'skills' => 'nullable|array',
  64. 'skills.*' => 'string',
  65. 'question_type_ratio' => 'nullable|array',
  66. // 'difficulty_ratio' 参数已废弃,使用 difficulty_category 控制难度分布
  67. 'total_score' => 'nullable|numeric|min:1|max:1000',
  68. 'mistake_ids' => 'nullable|array',
  69. 'mistake_ids.*' => 'string',
  70. 'mistake_question_ids' => 'nullable|array',
  71. 'mistake_question_ids.*' => 'string',
  72. 'callback_url' => 'nullable|url', // 异步完成后推送通知的URL
  73. // 新增:组卷类型
  74. 'assemble_type' => 'nullable|integer|in:0,1,2,3,4,5,8,9',
  75. 'exam_type' => 'nullable|string|in:general,diagnostic,practice,mistake,textbook,knowledge,knowledge_points',
  76. // 错题本类型专用参数
  77. 'paper_ids' => 'nullable|array',
  78. 'paper_ids.*' => 'string',
  79. // 修改:使用series_id + semester_code + grade替代textbook_id
  80. 'series_id' => 'nullable|integer|min:1', // 教材系列ID(替代textbook_id)
  81. 'semester_code' => 'nullable|integer|in:1,2', // 上下册:1=上册,2=下册
  82. // 新增:各组卷类型的专用参数
  83. 'chapter_id_list' => 'nullable|array', // 教材组卷专用
  84. 'chapter_id_list.*' => 'integer|min:1',
  85. 'kp_code_list' => 'nullable|array', // 知识点组卷专用
  86. 'kp_code_list.*' => 'string',
  87. 'end_catalog_id' => 'nullable|integer|min:1', // 摸底专用:截止章节ID
  88. // 新增:专项练习选项
  89. 'practice_options' => 'nullable|array',
  90. 'practice_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  91. 'practice_options.intensity' => 'nullable|string|in:low,medium,high',
  92. 'practice_options.include_new_questions' => 'nullable|boolean',
  93. 'practice_options.focus_weaknesses' => 'nullable|boolean',
  94. // 新增:错题选项
  95. 'mistake_options' => 'nullable|array',
  96. 'mistake_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  97. 'mistake_options.review_mistakes' => 'nullable|boolean',
  98. 'mistake_options.intensity' => 'nullable|string|in:low,medium,high',
  99. 'mistake_options.include_new_questions' => 'nullable|boolean',
  100. 'mistake_options.focus_weaknesses' => 'nullable|boolean',
  101. // 新增:按知识点组卷选项
  102. 'knowledge_points_options' => 'nullable|array',
  103. 'knowledge_points_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  104. 'knowledge_points_options.intensity' => 'nullable|string|in:low,medium,high',
  105. 'knowledge_points_options.focus_weaknesses' => 'nullable|boolean',
  106. ]);
  107. if ($validator->fails()) {
  108. return response()->json([
  109. 'success' => false,
  110. 'message' => '参数错误',
  111. 'errors' => $validator->errors()->toArray(),
  112. ], 422);
  113. }
  114. $data = $validator->validated();
  115. $assembleType = (int) ($data['assemble_type'] ?? 4);
  116. $defaultQuestions = in_array($assembleType, [1, 8]) ? 10 : 20;
  117. $data['total_questions'] = $data['total_questions'] ?? $defaultQuestions;
  118. $this->ensureStudentTeacherRelation($data);
  119. // 【修改】使用series_id、semester_code和grade获取textbook_id
  120. $textbookId = $this->resolveTextbookId($data);
  121. if ($textbookId) {
  122. $data['textbook_id'] = $textbookId;
  123. }
  124. // 确保 kp_codes 是数组
  125. $data['kp_codes'] = $data['kp_codes'] ?? [];
  126. if (! is_array($data['kp_codes'])) {
  127. $data['kp_codes'] = [];
  128. }
  129. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  130. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  131. $paperName = $data['paper_name'] ?? ('智能试卷_'.now()->format('Ymd_His'));
  132. $difficultyCategory = $data['difficulty_category'] ?? 1; // 直接使用数字,不转换
  133. $mistakeIds = $data['mistake_ids'] ?? [];
  134. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  135. $paperIds = $data['paper_ids'] ?? [];
  136. $assembleType = $data['assemble_type'] ?? 4; // 默认为通用类型(4)
  137. try {
  138. $questions = [];
  139. $result = null;
  140. // 【新增】初始化章节摸底和智能组卷的关键字段
  141. $diagnosticChapterId = null;
  142. $explanationKpCodes = null;
  143. if (! empty($mistakeIds) || ! empty($mistakeQuestionIds)) {
  144. $questionIds = $this->resolveMistakeQuestionIds(
  145. $data['student_id'],
  146. $mistakeIds,
  147. $mistakeQuestionIds
  148. );
  149. if (empty($questionIds)) {
  150. return response()->json([
  151. 'success' => false,
  152. 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
  153. ], 400);
  154. }
  155. $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  156. if (empty($bankQuestions)) {
  157. return response()->json([
  158. 'success' => false,
  159. 'message' => '错题对应的题库题目不存在或不可用',
  160. ], 400);
  161. }
  162. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
  163. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  164. $paperName = $data['paper_name'] ?? ('错题复习_'.$data['student_id'].'_'.now()->format('Ymd_His'));
  165. } else {
  166. // 第一步:生成智能试卷(同步)
  167. $params = [
  168. 'student_id' => $data['student_id'],
  169. 'grade' => $data['grade'] ?? null,
  170. 'total_questions' => $data['total_questions'],
  171. // 【修复】教材组卷时不使用用户传入的kp_codes,只使用章节关联的知识点
  172. 'kp_codes' => $assembleType == 3 ? null : ($data['kp_codes'] ?? null),
  173. 'skills' => $data['skills'] ?? [],
  174. 'question_type_ratio' => $questionTypeRatio,
  175. 'difficulty_category' => $difficultyCategory, // 传递难度分类(数字)
  176. 'assemble_type' => $assembleType, // 新版组卷类型
  177. 'exam_type' => $data['exam_type'] ?? 'general', // 兼容旧版参数
  178. 'paper_ids' => $paperIds, // 错题本类型专用参数
  179. 'textbook_id' => $data['textbook_id'] ?? null, // 摸底和智能组卷专用
  180. 'end_catalog_id' => $data['end_catalog_id'] ?? null, // 摸底专用:截止章节ID
  181. 'chapter_id_list' => $data['chapter_id_list'] ?? null, // 教材组卷专用
  182. 'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []), // 知识点组卷专用
  183. 'practice_options' => $data['practice_options'] ?? null, // 传递专项练习选项
  184. 'mistake_options' => $data['mistake_options'] ?? null, // 传递错题选项
  185. ];
  186. $result = $this->learningAnalyticsService->generateIntelligentExam($params);
  187. if (empty($result['success'])) {
  188. $errorMsg = $result['message'] ?? '智能出卷失败';
  189. Log::error('智能出卷失败', [
  190. 'student_id' => $data['student_id'],
  191. 'error' => $result,
  192. ]);
  193. // 提供更详细的错误信息
  194. if (strpos($errorMsg, '超时') !== false) {
  195. $errorMsg = '服务响应超时,请稍后重试';
  196. } elseif (strpos($errorMsg, '连接') !== false) {
  197. $errorMsg = '依赖服务连接失败,请检查服务状态';
  198. }
  199. return response()->json([
  200. 'success' => false,
  201. 'message' => $errorMsg,
  202. 'details' => $result['details'] ?? null,
  203. ], 400);
  204. }
  205. if (isset($result['stats']['difficulty_category'])) {
  206. $difficultyCategory = $result['stats']['difficulty_category'];
  207. }
  208. // 【新增】提取章节摸底和智能组卷的关键字段
  209. $diagnosticChapterId = $result['diagnostic_chapter_id'] ?? null;
  210. $explanationKpCodes = $result['explanation_kp_codes'] ?? null;
  211. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  212. }
  213. if (empty($questions)) {
  214. return response()->json([
  215. 'success' => false,
  216. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  217. ], 400);
  218. }
  219. // 错题本类型不需要限制题目数量,由错题数量决定
  220. if ($assembleType === 5) {
  221. // 错题本:使用所有错题,不限制数量
  222. Log::info('错题本类型,使用所有错题', [
  223. 'assemble_type' => $assembleType,
  224. 'question_count' => count($questions),
  225. ]);
  226. } else {
  227. // 其他类型:限制题目数量
  228. $totalQuestions = min($data['total_questions'], count($questions));
  229. $questions = array_slice($questions, 0, $totalQuestions);
  230. }
  231. // 调整题目分值
  232. if (($data['total_questions'] ?? 20) == 20) {
  233. // 20题:沿用动态凑整算法,目标总分100
  234. $targetTotalScore = $data['total_score'] ?? 100.0;
  235. $questions = $this->adjustQuestionScores($questions, $targetTotalScore);
  236. } else {
  237. // 非20题:固定题型分值(选择5、填空5、解答10)
  238. $questions = $this->applyFixedScores($questions);
  239. $targetTotalScore = array_sum(array_column($questions, 'score'));
  240. }
  241. // 计算总分
  242. $totalScore = array_sum(array_column($questions, 'score'));
  243. // 第二步:保存试卷到数据库(同步)
  244. // 【修复】策略可能修改assembleType(如章节智能组卷检测到全部掌握后转为下一章节摸底)
  245. $finalAssembleType = ($result !== null && isset($result['assemble_type'])) ? $result['assemble_type'] : $assembleType;
  246. $paperId = $this->questionBankService->saveExamToDatabase([
  247. 'paper_name' => $paperName,
  248. 'student_id' => $data['student_id'],
  249. 'teacher_id' => $data['teacher_id'] ?? null,
  250. 'assembleType' => $finalAssembleType,
  251. 'difficulty_category' => $difficultyCategory,
  252. 'total_score' => $totalScore, // 使用计算后的实际总分
  253. 'questions' => $questions,
  254. // 【新增】章节摸底和智能组卷的关键字段
  255. 'diagnostic_chapter_id' => $diagnosticChapterId ?? null,
  256. 'explanation_kp_codes' => $explanationKpCodes ?? null,
  257. ]);
  258. if (! $paperId) {
  259. return response()->json([
  260. 'success' => false,
  261. 'message' => '试卷保存失败',
  262. ], 500);
  263. }
  264. // 第三步:创建异步任务(使用TaskManager)
  265. // 注意:callback_url会在TaskManager中被提取并保存
  266. $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
  267. // 生成识别码
  268. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  269. // 立即返回完整的试卷数据(不等待PDF生成)
  270. $paperModel = Paper::with('questions')->find($paperId);
  271. $examContent = $paperModel
  272. ? $this->paperPayloadService->buildExamContent($paperModel)
  273. : [];
  274. $finalStats = $result['stats'] ?? [
  275. 'total_selected' => count($questions),
  276. 'mistake_based' => ! empty($mistakeIds) || ! empty($mistakeQuestionIds),
  277. ];
  278. if (! isset($finalStats['difficulty_category'])) {
  279. $finalStats['difficulty_category'] = $difficultyCategory;
  280. }
  281. if (! isset($finalStats['final_distribution'])) {
  282. $distributionService = app(\App\Services\DifficultyDistributionService::class);
  283. $finalBuckets = $distributionService->groupQuestionsByDifficultyRange($questions, (int) $difficultyCategory);
  284. $finalTotal = max(1, count($questions));
  285. $finalStats['final_distribution'] = array_map(static function ($bucket) use ($finalTotal) {
  286. $count = count($bucket);
  287. return [
  288. 'count' => $count,
  289. 'ratio' => round(($count / $finalTotal) * 100, 2),
  290. ];
  291. }, $finalBuckets);
  292. }
  293. if (! isset($finalStats['final_distribution_shortage'])) {
  294. $distributionService = app(\App\Services\DifficultyDistributionService::class);
  295. $distribution = $distributionService->calculateDistribution((int) $difficultyCategory, (int) ($data['total_questions'] ?? count($questions)));
  296. $buckets = $distributionService->groupQuestionsByDifficultyRange($questions, (int) $difficultyCategory);
  297. $expected = [
  298. 'primary_low' => 0,
  299. 'primary_medium' => 0,
  300. 'primary_high' => 0,
  301. 'secondary' => 0,
  302. 'other' => 0,
  303. ];
  304. foreach ($distribution as $level => $config) {
  305. $bucketKey = $distributionService->mapDifficultyLevelToRangeKey($level, (int) $difficultyCategory);
  306. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  307. }
  308. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  309. $finalStats['final_distribution_shortage'] = array_map(static function ($count, $bucketKey) use ($actual) {
  310. $actualCount = $actual[$bucketKey] ?? 0;
  311. return [
  312. 'expected' => $count,
  313. 'actual' => $actualCount,
  314. 'short' => max(0, $count - $actualCount),
  315. ];
  316. }, $expected, array_keys($expected));
  317. }
  318. $this->taskManager->updateTaskStatus($taskId, [
  319. 'stats' => $finalStats,
  320. ]);
  321. // 触发后台PDF生成
  322. $this->triggerPdfGeneration($taskId, $paperId);
  323. $payload = [
  324. 'success' => true,
  325. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  326. 'data' => [
  327. 'task_id' => $taskId,
  328. 'paper_id' => $paperId,
  329. 'status' => 'processing',
  330. // 识别码
  331. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  332. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  333. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  334. 'exam_content' => $examContent,
  335. 'urls' => [
  336. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  337. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  338. 'knowledge_explanation_url' => route('filament.admin.auth.intelligent-exam.knowledge-explanation', ['paper_id' => $paperId]),
  339. ],
  340. 'pdfs' => [
  341. 'exam_paper_pdf' => null,
  342. 'grading_pdf' => null,
  343. ],
  344. 'stats' => $finalStats,
  345. 'created_at' => now()->toISOString(),
  346. ],
  347. ];
  348. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  349. } catch (\Exception $e) {
  350. Log::error('Intelligent exam API failed', [
  351. 'error' => $e->getMessage(),
  352. 'trace' => $e->getTraceAsString(),
  353. ]);
  354. // 返回更具体的错误信息
  355. $errorMessage = $e->getMessage();
  356. if (strpos($errorMessage, 'Connection') !== false || strpos($errorMessage, 'connection') !== false) {
  357. $errorMessage = '依赖服务连接失败,请检查服务状态';
  358. } elseif (strpos($errorMessage, 'timeout') !== false || strpos($errorMessage, '超时') !== false) {
  359. $errorMessage = '服务响应超时,请稍后重试';
  360. } elseif (strpos($errorMessage, 'not found') !== false || strpos($errorMessage, '未找到') !== false) {
  361. $errorMessage = '请求的资源不存在';
  362. } elseif (strpos($errorMessage, 'invalid') !== false || strpos($errorMessage, '无效') !== false) {
  363. $errorMessage = '请求参数无效';
  364. }
  365. return response()->json([
  366. 'success' => false,
  367. 'message' => $errorMessage ?: '服务异常,请稍后重试',
  368. ], 500);
  369. }
  370. }
  371. /**
  372. * 轮询任务状态
  373. */
  374. public function status(string $taskId): JsonResponse
  375. {
  376. try {
  377. $task = $this->taskManager->getTaskStatus($taskId);
  378. if (! $task) {
  379. return response()->json([
  380. 'success' => false,
  381. 'message' => '任务不存在',
  382. ], 404);
  383. }
  384. return response()->json([
  385. 'success' => true,
  386. 'data' => $task,
  387. ]);
  388. } catch (\Exception $e) {
  389. Log::error('查询任务状态失败', [
  390. 'task_id' => $taskId,
  391. 'error' => $e->getMessage(),
  392. ]);
  393. return response()->json([
  394. 'success' => false,
  395. 'message' => '查询失败,请稍后重试',
  396. ], 500);
  397. }
  398. }
  399. /**
  400. * 触发PDF生成
  401. * 使用队列进行异步处理
  402. */
  403. private function triggerPdfGeneration(string $taskId, string $paperId): void
  404. {
  405. // 异步处理PDF生成 - 将任务放入队列
  406. try {
  407. dispatch(new \App\Jobs\GenerateExamPdfJob($taskId, $paperId));
  408. Log::info('PDF生成任务已加入队列', [
  409. 'task_id' => $taskId,
  410. 'paper_id' => $paperId,
  411. ]);
  412. } catch (\Exception $e) {
  413. Log::error('PDF生成任务队列失败,不回退到同步处理', [
  414. 'task_id' => $taskId,
  415. 'paper_id' => $paperId,
  416. 'error' => $e->getMessage(),
  417. 'note' => '依赖队列重试机制,不进行同步处理以避免并发冲突',
  418. ]);
  419. // 【优化】不回退到同步处理,避免与队列任务并发冲突
  420. // 队列系统有重试机制,会自动处理失败情况
  421. // $this->processPdfGeneration($taskId, $paperId);
  422. }
  423. }
  424. /**
  425. * 处理PDF生成(模拟后台任务)
  426. * 在实际项目中,这个方法应该在队列worker中执行
  427. */
  428. private function processPdfGeneration(string $taskId, string $paperId): void
  429. {
  430. try {
  431. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  432. // 生成试卷PDF
  433. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  434. ?? $this->questionBankService->exportExamToPdf($paperId)
  435. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  436. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  437. // 生成判卷PDF
  438. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  439. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  440. // 构建完整的试卷内容
  441. $paperModel = Paper::with('questions')->find($paperId);
  442. $examContent = $paperModel
  443. ? $this->paperPayloadService->buildExamContent($paperModel)
  444. : [];
  445. // 标记任务完成
  446. $this->taskManager->markTaskCompleted($taskId, [
  447. 'exam_content' => $examContent,
  448. 'pdfs' => [
  449. 'exam_paper_pdf' => $pdfUrl,
  450. 'grading_pdf' => $gradingPdfUrl,
  451. ],
  452. ]);
  453. Log::info('异步任务完成', [
  454. 'task_id' => $taskId,
  455. 'paper_id' => $paperId,
  456. 'pdf_url' => $pdfUrl,
  457. 'grading_pdf_url' => $gradingPdfUrl,
  458. ]);
  459. // 发送回调通知
  460. $this->taskManager->sendCallback($taskId);
  461. } catch (\Exception $e) {
  462. Log::error('PDF生成失败', [
  463. 'task_id' => $taskId,
  464. 'paper_id' => $paperId,
  465. 'error' => $e->getMessage(),
  466. ]);
  467. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  468. }
  469. }
  470. /**
  471. * 兼容字符串/数组入参
  472. */
  473. private function normalizePayload(array $payload): array
  474. {
  475. // 处理 question_count 参数:转换为 total_questions
  476. if (isset($payload['question_count']) && ! isset($payload['total_questions'])) {
  477. $payload['total_questions'] = $payload['question_count'];
  478. unset($payload['question_count']);
  479. }
  480. // 将student_id转换为字符串(支持数字和字符串输入)
  481. if (isset($payload['student_id'])) {
  482. $payload['student_id'] = (string) $payload['student_id'];
  483. }
  484. if (isset($payload['teacher_id'])) {
  485. $payload['teacher_id'] = (string) $payload['teacher_id'];
  486. }
  487. if (isset($payload['grade'])) {
  488. $payload['grade'] = (string) $payload['grade'];
  489. }
  490. // 处理 kp_codes:空字符串或null转换为空数组
  491. if (isset($payload['kp_codes'])) {
  492. if (is_string($payload['kp_codes'])) {
  493. $kpCodes = trim($payload['kp_codes']);
  494. if (empty($kpCodes)) {
  495. $payload['kp_codes'] = [];
  496. } else {
  497. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  498. }
  499. } elseif (! is_array($payload['kp_codes'])) {
  500. $payload['kp_codes'] = [];
  501. }
  502. } else {
  503. $payload['kp_codes'] = [];
  504. }
  505. if (isset($payload['skills']) && is_string($payload['skills'])) {
  506. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  507. }
  508. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  509. if (isset($payload[$key])) {
  510. if (is_string($payload[$key])) {
  511. $raw = trim($payload[$key]);
  512. $payload[$key] = $raw === ''
  513. ? []
  514. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  515. } elseif (! is_array($payload[$key])) {
  516. $payload[$key] = [];
  517. }
  518. }
  519. }
  520. // 新增:处理组卷专用参数
  521. foreach (['chapter_id_list', 'kp_code_list'] as $key) {
  522. if (isset($payload[$key])) {
  523. if (is_string($payload[$key])) {
  524. $raw = trim($payload[$key]);
  525. $payload[$key] = $raw === ''
  526. ? []
  527. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  528. } elseif (! is_array($payload[$key])) {
  529. $payload[$key] = [];
  530. }
  531. } else {
  532. $payload[$key] = [];
  533. }
  534. }
  535. // 【修改】处理series_id:字符串转换为整数
  536. if (isset($payload['series_id'])) {
  537. if (is_string($payload['series_id'])) {
  538. $payload['series_id'] = (int) trim($payload['series_id']);
  539. if ($payload['series_id'] <= 0) {
  540. unset($payload['series_id']);
  541. }
  542. } elseif (! is_int($payload['series_id']) || $payload['series_id'] <= 0) {
  543. unset($payload['series_id']);
  544. }
  545. }
  546. // 【新增】处理semester_code:确保是1或2
  547. if (isset($payload['semester_code'])) {
  548. if (is_string($payload['semester_code'])) {
  549. $payload['semester_code'] = (int) trim($payload['semester_code']);
  550. }
  551. // 只保留1或2,其他值都移除
  552. if (! in_array($payload['semester_code'], [1, 2], true)) {
  553. unset($payload['semester_code']);
  554. }
  555. }
  556. // 新增:处理组卷类型,默认值为 general
  557. if (! isset($payload['exam_type'])) {
  558. $payload['exam_type'] = 'general';
  559. }
  560. // 新增:处理专项练习选项
  561. if (isset($payload['practice_options'])) {
  562. if (is_string($payload['practice_options'])) {
  563. $decoded = json_decode($payload['practice_options'], true);
  564. $payload['practice_options'] = is_array($decoded) ? $decoded : [];
  565. } elseif (! is_array($payload['practice_options'])) {
  566. $payload['practice_options'] = [];
  567. }
  568. // 设置默认值
  569. $payload['practice_options'] = array_merge([
  570. 'weakness_threshold' => 0.7,
  571. 'intensity' => 'medium',
  572. 'include_new_questions' => true,
  573. 'focus_weaknesses' => true,
  574. ], $payload['practice_options']);
  575. } else {
  576. // 如果没有提供 practice_options,创建默认值
  577. $payload['practice_options'] = [
  578. 'weakness_threshold' => 0.7,
  579. 'intensity' => 'medium',
  580. 'include_new_questions' => true,
  581. 'focus_weaknesses' => true,
  582. ];
  583. }
  584. // 新增:处理错题选项
  585. if (isset($payload['mistake_options'])) {
  586. if (is_string($payload['mistake_options'])) {
  587. $decoded = json_decode($payload['mistake_options'], true);
  588. $payload['mistake_options'] = is_array($decoded) ? $decoded : [];
  589. } elseif (! is_array($payload['mistake_options'])) {
  590. $payload['mistake_options'] = [];
  591. }
  592. // 设置默认值
  593. $payload['mistake_options'] = array_merge([
  594. 'weakness_threshold' => 0.7,
  595. 'review_mistakes' => true,
  596. 'intensity' => 'medium',
  597. 'include_new_questions' => true,
  598. 'focus_weaknesses' => true,
  599. ], $payload['mistake_options']);
  600. } else {
  601. // 如果没有提供 mistake_options,创建默认值
  602. $payload['mistake_options'] = [
  603. 'weakness_threshold' => 0.7,
  604. 'review_mistakes' => true,
  605. 'intensity' => 'medium',
  606. 'include_new_questions' => true,
  607. 'focus_weaknesses' => true,
  608. ];
  609. }
  610. // 新增:处理按知识点组卷选项
  611. if (isset($payload['knowledge_points_options'])) {
  612. if (is_string($payload['knowledge_points_options'])) {
  613. $decoded = json_decode($payload['knowledge_points_options'], true);
  614. $payload['knowledge_points_options'] = is_array($decoded) ? $decoded : [];
  615. } elseif (! is_array($payload['knowledge_points_options'])) {
  616. $payload['knowledge_points_options'] = [];
  617. }
  618. // 设置默认值
  619. $payload['knowledge_points_options'] = array_merge([
  620. 'weakness_threshold' => 0.7,
  621. 'intensity' => 'medium',
  622. 'focus_weaknesses' => true,
  623. ], $payload['knowledge_points_options']);
  624. } else {
  625. // 如果没有提供 knowledge_points_options,创建默认值
  626. $payload['knowledge_points_options'] = [
  627. 'weakness_threshold' => 0.7,
  628. 'intensity' => 'medium',
  629. 'focus_weaknesses' => true,
  630. ];
  631. }
  632. return $payload;
  633. }
  634. private function ensureStudentTeacherRelation(array $data): void
  635. {
  636. $studentId = (int) $data['student_id'];
  637. $teacherId = (int) $data['teacher_id'];
  638. $studentName = (string) ($data['student_name'] ?? '未知学生');
  639. $teacherName = (string) ($data['teacher_name'] ?? '未知教师');
  640. $grade = (string) ($data['grade'] ?? '未知年级');
  641. $teacher = $this->externalIdService->handleTeacherExternalId($teacherId, [
  642. 'name' => $teacherName,
  643. 'subject' => '数学',
  644. ]);
  645. $student = Student::where('student_id', $studentId)->first();
  646. if ($student) {
  647. $updates = [];
  648. if ($studentName !== '' && $student->name !== $studentName) {
  649. $updates['name'] = $studentName;
  650. }
  651. if ($grade !== '' && $student->grade !== $grade) {
  652. $updates['grade'] = $grade;
  653. }
  654. if ($teacherId > 0 && (int) $student->teacher_id !== $teacherId) {
  655. $updates['teacher_id'] = $teacherId;
  656. }
  657. if (! empty($updates)) {
  658. $student->update($updates);
  659. }
  660. return;
  661. }
  662. $this->externalIdService->handleStudentExternalId($studentId, [
  663. 'name' => $studentName,
  664. 'grade' => $grade,
  665. 'teacher_id' => $teacherId,
  666. ]);
  667. }
  668. private function normalizeQuestionTypeRatio(array $input): array
  669. {
  670. // 默认按 4:2:4
  671. $defaults = [
  672. '选择题' => 40,
  673. '填空题' => 20,
  674. '解答题' => 40,
  675. ];
  676. $normalized = [];
  677. foreach ($input as $key => $value) {
  678. if (! is_numeric($value)) {
  679. continue;
  680. }
  681. $type = $this->normalizeQuestionTypeKey($key);
  682. if ($type) {
  683. $normalized[$type] = (float) $value;
  684. }
  685. }
  686. $merged = array_merge($defaults, $normalized);
  687. // 归一化到 100%
  688. $sum = array_sum($merged);
  689. if ($sum > 0) {
  690. foreach ($merged as $k => $v) {
  691. $merged[$k] = round(($v / $sum) * 100, 2);
  692. }
  693. }
  694. return $merged;
  695. }
  696. private function normalizeQuestionTypeKey(string $key): ?string
  697. {
  698. $key = trim($key);
  699. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  700. return '选择题';
  701. }
  702. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  703. return '填空题';
  704. }
  705. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  706. return '解答题';
  707. }
  708. return null;
  709. }
  710. private function normalizeDifficultyRatio(array $input): array
  711. {
  712. $defaults = [
  713. '基础' => 50,
  714. '中等' => 35,
  715. '拔高' => 15,
  716. ];
  717. $normalized = [];
  718. foreach ($input as $key => $value) {
  719. if (! is_numeric($value)) {
  720. continue;
  721. }
  722. $label = trim($key);
  723. if (in_array($label, ['基础', 'easy', '简单'])) {
  724. $normalized['基础'] = (float) $value;
  725. } elseif (in_array($label, ['中等', 'medium'])) {
  726. $normalized['中等'] = (float) $value;
  727. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  728. $normalized['拔高'] = (float) $value;
  729. }
  730. }
  731. return array_merge($defaults, $normalized);
  732. }
  733. private function hydrateQuestions(array $questions, array $kpCodes): array
  734. {
  735. $normalized = [];
  736. foreach ($questions as $question) {
  737. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  738. $score = $question['score'] ?? $this->defaultScore($type);
  739. $normalized[] = [
  740. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  741. 'question_id' => $question['question_id'] ?? null,
  742. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  743. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  744. 'content' => $question['content'] ?? $question['stem'] ?? '',
  745. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  746. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  747. 'solution' => $question['solution'] ?? '',
  748. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  749. 'score' => $score,
  750. 'estimated_time' => $question['estimated_time'] ?? 300,
  751. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  752. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  753. ];
  754. }
  755. return array_values(array_filter($normalized, fn ($q) => ! empty($q['id'])));
  756. }
  757. private function guessType(array $question): string
  758. {
  759. if (! empty($question['options']) && is_array($question['options'])) {
  760. return '选择题';
  761. }
  762. $content = $question['stem'] ?? $question['content'] ?? '';
  763. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  764. return '填空题';
  765. }
  766. return '解答题';
  767. }
  768. /**
  769. * 根据题目类型获取默认分值(中国中学卷子标准)
  770. * 选择题:5分/题,填空题:5分/题,解答题:10分/题
  771. */
  772. private function defaultScore(string $type): int
  773. {
  774. return match ($type) {
  775. '选择题' => 5,
  776. '填空题' => 5,
  777. '解答题' => 10,
  778. default => 5,
  779. };
  780. }
  781. /**
  782. * 非20题时使用固定题型分值
  783. * 选择题:5分,填空题:5分,解答题:10分
  784. */
  785. private function applyFixedScores(array $questions): array
  786. {
  787. foreach ($questions as &$question) {
  788. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  789. $question['score'] = match ($type) {
  790. 'choice' => 5,
  791. 'fill' => 5,
  792. 'answer' => 10,
  793. default => 5,
  794. };
  795. }
  796. unset($question);
  797. return $questions;
  798. }
  799. /**
  800. * 计算试卷总分并调整各题目分值,确保总分接近目标分数
  801. * 符合中国中学卷子标准:
  802. * - 选择题:约40%总分(每题4-6分,整数分值)
  803. * - 填空题:约25%总分(每题4-6分,整数分值)
  804. * - 解答题:约35%总分(每题8-12分,整数分值)
  805. * 使用组合优化算法确保:
  806. * 1. 所有分值都是整数(无小数点)
  807. * 2. 同类型题目分值均匀
  808. * 3. 总分精确匹配目标分数(或最接近)
  809. */
  810. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  811. {
  812. if (empty($questions)) {
  813. return $questions;
  814. }
  815. // 第一步:按题型排序
  816. $sortedQuestions = [];
  817. $choiceQuestions = [];
  818. $fillQuestions = [];
  819. $answerQuestions = [];
  820. foreach ($questions as $question) {
  821. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  822. if ($type === 'choice') {
  823. $choiceQuestions[] = $question;
  824. } elseif ($type === 'fill') {
  825. $fillQuestions[] = $question;
  826. } else {
  827. $answerQuestions[] = $question;
  828. }
  829. }
  830. $sortedQuestions = array_merge($choiceQuestions, $fillQuestions, $answerQuestions);
  831. // 调试日志
  832. \Illuminate\Support\Facades\Log::info('adjustQuestionScores 开始', [
  833. 'choice_count' => count($choiceQuestions),
  834. 'fill_count' => count($fillQuestions),
  835. 'answer_count' => count($answerQuestions),
  836. ]);
  837. // 重新编号
  838. foreach ($sortedQuestions as $idx => &$question) {
  839. $question['question_number'] = $idx + 1;
  840. }
  841. unset($question);
  842. // 各题型数量
  843. $typeCounts = [
  844. 'choice' => count($choiceQuestions),
  845. 'fill' => count($fillQuestions),
  846. 'answer' => count($answerQuestions),
  847. ];
  848. // 记录各题型索引
  849. $typeIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  850. foreach ($sortedQuestions as $index => $question) {
  851. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  852. $typeIndexes[$type][] = $index;
  853. }
  854. // 第二步:分配分值
  855. $questionScores = [];
  856. $totalQuestions = $typeCounts['choice'] + $typeCounts['fill'] + $typeCounts['answer'];
  857. $globalBaseScore = floor($targetTotalScore / $totalQuestions);
  858. $globalBaseScore = max(1, $globalBaseScore);
  859. // 确定题型处理顺序(基于 sortedQuestions 中的顺序)
  860. $typeOrder = [];
  861. foreach ($sortedQuestions as $question) {
  862. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  863. if (! in_array($type, $typeOrder)) {
  864. $typeOrder[] = $type;
  865. }
  866. }
  867. // 记录当前剩余预算
  868. $remainingBudget = $targetTotalScore;
  869. // 按顺序处理每种题型
  870. foreach ($typeOrder as $typeIndex => $type) {
  871. $count = $typeCounts[$type];
  872. if ($count === 0) {
  873. continue;
  874. }
  875. if ($typeIndex === 0) {
  876. // 第一个题型:拿平均分,然后都-1
  877. $thisBase = $globalBaseScore;
  878. foreach ($typeIndexes[$type] as $idx) {
  879. $questionScores[$idx] = $thisBase;
  880. }
  881. // 都-1
  882. foreach ($typeIndexes[$type] as $idx) {
  883. $questionScores[$idx] = max(1, $questionScores[$idx] - 1);
  884. }
  885. // 计算已分配的分数
  886. $allocated = 0;
  887. foreach ($typeIndexes[$type] as $idx) {
  888. $allocated += $questionScores[$idx];
  889. }
  890. $remainingBudget -= $allocated;
  891. } elseif ($typeIndex === count($typeOrder) - 1) {
  892. // 最后一个题型:用剩余分数分配
  893. $thisBase = floor($remainingBudget / $count);
  894. $thisBase = max(1, $thisBase);
  895. foreach ($typeIndexes[$type] as $idx) {
  896. $questionScores[$idx] = $thisBase;
  897. }
  898. // 余数补偿:分散到多道题,从后往前各+1
  899. $total = $thisBase * $count;
  900. $remainder = $remainingBudget - $total;
  901. if ($remainder > 0) {
  902. // 从最后一道题开始,往前 $remainder 道题各+1
  903. $answerIndexes = array_values($typeIndexes[$type]);
  904. $startIdx = max(0, count($answerIndexes) - $remainder);
  905. for ($i = $startIdx; $i < count($answerIndexes); $i++) {
  906. $questionScores[$answerIndexes[$i]] += 1;
  907. }
  908. }
  909. } else {
  910. // 中间的题型:直接用全局平均分(不减)
  911. $thisBase = $globalBaseScore;
  912. foreach ($typeIndexes[$type] as $idx) {
  913. $questionScores[$idx] = $thisBase;
  914. }
  915. // 计算已分配的分数
  916. $allocated = 0;
  917. foreach ($typeIndexes[$type] as $idx) {
  918. $allocated += $questionScores[$idx];
  919. }
  920. $remainingBudget -= $allocated;
  921. }
  922. }
  923. // 第三步:确保最后一类题型分数 > 前面所有题型
  924. if (count($typeOrder) > 1) {
  925. $lastType = end($typeOrder);
  926. $otherTypes = array_slice($typeOrder, 0, -1);
  927. // 前面题型的最高分
  928. $maxOtherScore = 0;
  929. foreach ($otherTypes as $type) {
  930. foreach ($typeIndexes[$type] as $idx) {
  931. $maxOtherScore = max($maxOtherScore, $questionScores[$idx]);
  932. }
  933. }
  934. // 最后一类题型的最低分
  935. $minLastScore = PHP_INT_MAX;
  936. foreach ($typeIndexes[$lastType] as $idx) {
  937. $minLastScore = min($minLastScore, $questionScores[$idx]);
  938. }
  939. // 如果最后一类不够高,从前面扣分
  940. if ($minLastScore <= $maxOtherScore) {
  941. $diff = $maxOtherScore - $minLastScore + 1;
  942. // 从前面题型扣分(每道最多扣2分)
  943. $reductionPerQuestion = min($diff, 2);
  944. foreach ($otherTypes as $type) {
  945. foreach ($typeIndexes[$type] as $idx) {
  946. $questionScores[$idx] = max(1, $questionScores[$idx] - $reductionPerQuestion);
  947. }
  948. }
  949. // 重新计算剩余给最后一类
  950. $reallocated = $targetTotalScore;
  951. foreach ($typeIndexes[$lastType] as $idx) {
  952. $reallocated -= $questionScores[$idx];
  953. }
  954. foreach ($otherTypes as $type) {
  955. foreach ($typeIndexes[$type] as $idx) {
  956. $reallocated -= $questionScores[$idx];
  957. }
  958. }
  959. if ($reallocated > 0) {
  960. $newBase = floor($reallocated / $typeCounts[$lastType]);
  961. foreach ($typeIndexes[$lastType] as $idx) {
  962. $questionScores[$idx] = $newBase;
  963. }
  964. $total = $newBase * $typeCounts[$lastType];
  965. $remainder = $reallocated - $total;
  966. if ($remainder > 0) {
  967. // 余数分散到多道题,从后往前各+1
  968. $lastIndexes = array_values($typeIndexes[$lastType]);
  969. $startIdx = max(0, count($lastIndexes) - $remainder);
  970. for ($i = $startIdx; $i < count($lastIndexes); $i++) {
  971. $questionScores[$lastIndexes[$i]] += 1;
  972. }
  973. }
  974. }
  975. }
  976. }
  977. // 第三步:构建结果
  978. $adjustedQuestions = [];
  979. foreach ($sortedQuestions as $index => $question) {
  980. $adjustedQuestions[$index] = $question;
  981. $adjustedQuestions[$index]['score'] = $questionScores[$index] ?? 5;
  982. }
  983. $total = array_sum(array_column($adjustedQuestions, 'score'));
  984. $diff = (int) $targetTotalScore - (int) $total;
  985. if ($diff !== 0 && ! empty($adjustedQuestions)) {
  986. $count = count($adjustedQuestions);
  987. $i = $count - 1;
  988. while ($diff !== 0) {
  989. $score = $adjustedQuestions[$i]['score'];
  990. if ($diff > 0) {
  991. $adjustedQuestions[$i]['score'] = $score + 1;
  992. $diff--;
  993. } else {
  994. if ($score > 1) {
  995. $adjustedQuestions[$i]['score'] = $score - 1;
  996. $diff++;
  997. }
  998. }
  999. $i--;
  1000. if ($i < 0) {
  1001. $i = $count - 1;
  1002. if ($diff < 0) {
  1003. $minScore = min(array_column($adjustedQuestions, 'score'));
  1004. if ($minScore <= 1) {
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. }
  1011. return $adjustedQuestions;
  1012. }
  1013. /**
  1014. * 标准化题目类型
  1015. */
  1016. private function normalizeQuestionType(string $type): string
  1017. {
  1018. $type = strtolower(trim($type));
  1019. if (in_array($type, ['choice', 'single_choice', 'multiple_choice', '选择题', '单选', '多选'], true)) {
  1020. return 'choice';
  1021. }
  1022. if (in_array($type, ['fill', 'fill_in_the_blank', 'blank', '填空题', '填空'], true)) {
  1023. return 'fill';
  1024. }
  1025. return 'answer';
  1026. }
  1027. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  1028. {
  1029. $questionIds = [];
  1030. if (! empty($mistakeQuestionIds)) {
  1031. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  1032. }
  1033. if (! empty($mistakeIds)) {
  1034. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  1035. ->where('student_id', $studentId)
  1036. ->whereIn('id', $mistakeIds)
  1037. ->pluck('question_id')
  1038. ->filter()
  1039. ->values()
  1040. ->all();
  1041. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  1042. }
  1043. $questionIds = array_values(array_unique(array_filter($questionIds)));
  1044. return $questionIds;
  1045. }
  1046. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  1047. {
  1048. if (empty($requestedIds)) {
  1049. return $questions;
  1050. }
  1051. $order = array_flip($requestedIds);
  1052. usort($questions, function ($a, $b) use ($order) {
  1053. $aId = (string) ($a['id'] ?? '');
  1054. $bId = (string) ($b['id'] ?? '');
  1055. $aPos = $order[$aId] ?? PHP_INT_MAX;
  1056. $bPos = $order[$bId] ?? PHP_INT_MAX;
  1057. return $aPos <=> $bPos;
  1058. });
  1059. return $questions;
  1060. }
  1061. /**
  1062. * 【新增】根据series_id、semester_code和grade获取textbook_id
  1063. * 替代原来直接传入textbook_id的方式
  1064. */
  1065. private function resolveTextbookId(array $data): ?int
  1066. {
  1067. // 如果提供了series_id和semester_code,则查询textbook_id
  1068. $seriesId = $data['series_id'] ?? null;
  1069. $semesterCode = $data['semester_code'] ?? null;
  1070. $grade = $data['grade'] ?? null;
  1071. // 如果没有提供series_id或semester_code,则不设置textbook_id
  1072. if (! $seriesId || ! $semesterCode) {
  1073. return null;
  1074. }
  1075. try {
  1076. // 根据series_id、semester_code和grade查询textbooks表
  1077. $query = DB::connection('mysql')
  1078. ->table('textbooks')
  1079. ->where('series_id', $seriesId)
  1080. ->where('semester', $semesterCode);
  1081. // 如果提供了grade,可以作为额外筛选条件
  1082. if ($grade) {
  1083. $query->where('grade', $grade);
  1084. }
  1085. $textbook = $query->first();
  1086. if ($textbook) {
  1087. Log::info('成功解析textbook_id', [
  1088. 'series_id' => $seriesId,
  1089. 'semester_code' => $semesterCode,
  1090. 'grade' => $grade,
  1091. 'textbook_id' => $textbook->id,
  1092. ]);
  1093. return (int) $textbook->id;
  1094. }
  1095. Log::warning('未找到匹配的教材', [
  1096. 'series_id' => $seriesId,
  1097. 'semester_code' => $semesterCode,
  1098. 'grade' => $grade,
  1099. ]);
  1100. return null;
  1101. } catch (\Exception $e) {
  1102. Log::error('查询textbook_id失败', [
  1103. 'series_id' => $seriesId,
  1104. 'semester_code' => $semesterCode,
  1105. 'grade' => $grade,
  1106. 'error' => $e->getMessage(),
  1107. ]);
  1108. return null;
  1109. }
  1110. }
  1111. }