IntelligentExamController.php 49 KB

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