IntelligentExamController.php 53 KB

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