IntelligentExamController.php 52 KB

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