IntelligentExamController.php 51 KB

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