IntelligentExamController.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Services\LearningAnalyticsService;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\QuestionBankService;
  9. use App\Services\PaperPayloadService;
  10. use App\Services\TaskManager;
  11. use App\Models\MistakeRecord;
  12. use Illuminate\Http\JsonResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Support\Facades\Http;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\URL;
  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. public function __construct(
  25. LearningAnalyticsService $learningAnalyticsService,
  26. QuestionBankService $questionBankService,
  27. ExamPdfExportService $pdfExportService,
  28. PaperPayloadService $paperPayloadService,
  29. TaskManager $taskManager
  30. ) {
  31. $this->learningAnalyticsService = $learningAnalyticsService;
  32. $this->questionBankService = $questionBankService;
  33. $this->pdfExportService = $pdfExportService;
  34. $this->paperPayloadService = $paperPayloadService;
  35. $this->taskManager = $taskManager;
  36. }
  37. /**
  38. * 外部API:生成智能试卷(异步模式)
  39. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  40. */
  41. public function store(Request $request): JsonResponse
  42. {
  43. $normalized = $this->normalizePayload($request->all());
  44. $validator = validator($normalized, [
  45. 'student_id' => 'required|string',
  46. 'teacher_id' => 'nullable|string',
  47. 'paper_name' => 'nullable|string|max:255',
  48. 'grade' => 'nullable|string|max:50',
  49. 'total_questions' => 'nullable|integer|min:6|max:100',
  50. 'difficulty_category' => 'nullable|string',
  51. 'kp_codes' => 'nullable|array',
  52. 'kp_codes.*' => 'string',
  53. 'skills' => 'nullable|array',
  54. 'skills.*' => 'string',
  55. 'question_type_ratio' => 'nullable|array',
  56. 'difficulty_ratio' => 'nullable|array',
  57. 'total_score' => 'nullable|numeric|min:1|max:1000',
  58. 'mistake_ids' => 'nullable|array',
  59. 'mistake_ids.*' => 'string',
  60. 'mistake_question_ids' => 'nullable|array',
  61. 'mistake_question_ids.*' => 'string',
  62. ]);
  63. if ($validator->fails()) {
  64. return response()->json([
  65. 'success' => false,
  66. 'message' => '参数错误',
  67. 'errors' => $validator->errors()->toArray(),
  68. ], 422);
  69. }
  70. $data = $validator->validated();
  71. $data['total_questions'] = $data['total_questions'] ?? 20;
  72. // 确保 kp_codes 是数组
  73. $data['kp_codes'] = $data['kp_codes'] ?? [];
  74. if (!is_array($data['kp_codes'])) {
  75. $data['kp_codes'] = [];
  76. }
  77. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  78. $difficultyRatio = $this->normalizeDifficultyRatio($data['difficulty_ratio'] ?? []);
  79. $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
  80. $difficultyCategory = $this->normalizeDifficultyCategory($data['difficulty_category'] ?? null);
  81. $mistakeIds = $data['mistake_ids'] ?? [];
  82. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  83. try {
  84. $questions = [];
  85. $result = null;
  86. if (!empty($mistakeIds) || !empty($mistakeQuestionIds)) {
  87. $questionIds = $this->resolveMistakeQuestionIds(
  88. $data['student_id'],
  89. $mistakeIds,
  90. $mistakeQuestionIds
  91. );
  92. if (empty($questionIds)) {
  93. return response()->json([
  94. 'success' => false,
  95. 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
  96. ], 400);
  97. }
  98. $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  99. if (empty($bankQuestions)) {
  100. return response()->json([
  101. 'success' => false,
  102. 'message' => '错题对应的题库题目不存在或不可用',
  103. ], 400);
  104. }
  105. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
  106. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  107. $paperName = $data['paper_name'] ?? ('错题复习_' . $data['student_id'] . '_' . now()->format('Ymd_His'));
  108. } else {
  109. // 第一步:生成智能试卷(同步)
  110. $result = $this->learningAnalyticsService->generateIntelligentExam([
  111. 'student_id' => $data['student_id'],
  112. 'grade' => $data['grade'] ?? null,
  113. 'total_questions' => $data['total_questions'],
  114. 'kp_codes' => $data['kp_codes'],
  115. 'skills' => $data['skills'] ?? [],
  116. 'question_type_ratio' => $questionTypeRatio,
  117. 'difficulty_ratio' => $difficultyRatio,
  118. ]);
  119. if (empty($result['success'])) {
  120. $errorMsg = $result['message'] ?? '智能出卷失败';
  121. Log::error('智能出卷失败', [
  122. 'student_id' => $data['student_id'],
  123. 'error' => $result
  124. ]);
  125. // 提供更详细的错误信息
  126. if (strpos($errorMsg, '超时') !== false) {
  127. $errorMsg = '服务响应超时,请稍后重试';
  128. } elseif (strpos($errorMsg, '连接') !== false) {
  129. $errorMsg = '依赖服务连接失败,请检查服务状态';
  130. }
  131. return response()->json([
  132. 'success' => false,
  133. 'message' => $errorMsg,
  134. 'details' => $result['details'] ?? null,
  135. ], 400);
  136. }
  137. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  138. }
  139. if (empty($questions)) {
  140. return response()->json([
  141. 'success' => false,
  142. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  143. ], 400);
  144. }
  145. $totalQuestions = min($data['total_questions'], count($questions));
  146. $questions = array_slice($questions, 0, $totalQuestions);
  147. // 调整题目分值,确保符合中国中学卷子标准(总分100分)
  148. $questions = $this->adjustQuestionScores($questions, 100.0);
  149. // 计算总分
  150. $totalScore = array_sum(array_column($questions, 'score'));
  151. // 第二步:保存试卷到数据库(同步)
  152. $paperId = $this->questionBankService->saveExamToDatabase([
  153. 'paper_name' => $paperName,
  154. 'student_id' => $data['student_id'],
  155. 'teacher_id' => $data['teacher_id'] ?? null,
  156. 'difficulty_category' => $difficultyCategory,
  157. 'total_score' => $data['total_score'] ?? 100.0, // 默认100分
  158. 'questions' => $questions,
  159. ]);
  160. if (!$paperId) {
  161. return response()->json([
  162. 'success' => false,
  163. 'message' => '试卷保存失败',
  164. ], 500);
  165. }
  166. // 第三步:创建异步任务(使用TaskManager)
  167. $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
  168. // 生成识别码
  169. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  170. // 立即返回完整的试卷数据(不等待PDF生成)
  171. $paperModel = Paper::with('questions')->find($paperId);
  172. $examContent = $paperModel
  173. ? $this->paperPayloadService->buildExamContent($paperModel)
  174. : [];
  175. // 触发后台PDF生成
  176. $this->triggerPdfGeneration($taskId, $paperId);
  177. $payload = [
  178. 'success' => true,
  179. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  180. 'data' => [
  181. 'task_id' => $taskId,
  182. 'paper_id' => $paperId,
  183. 'status' => 'processing',
  184. // 识别码
  185. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  186. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  187. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  188. 'exam_content' => $examContent,
  189. 'urls' => [
  190. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  191. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  192. ],
  193. 'pdfs' => [
  194. 'exam_paper_pdf' => null,
  195. 'grading_pdf' => null,
  196. ],
  197. 'stats' => $result['stats'] ?? [
  198. 'total_selected' => count($questions),
  199. 'mistake_based' => !empty($mistakeIds) || !empty($mistakeQuestionIds),
  200. ],
  201. 'created_at' => now()->toISOString(),
  202. ],
  203. ];
  204. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  205. } catch (\Exception $e) {
  206. Log::error('Intelligent exam API failed', [
  207. 'error' => $e->getMessage(),
  208. 'trace' => $e->getTraceAsString(),
  209. ]);
  210. // 返回更具体的错误信息
  211. $errorMessage = $e->getMessage();
  212. if (strpos($errorMessage, 'Connection') !== false || strpos($errorMessage, 'connection') !== false) {
  213. $errorMessage = '依赖服务连接失败,请检查服务状态';
  214. } elseif (strpos($errorMessage, 'timeout') !== false || strpos($errorMessage, '超时') !== false) {
  215. $errorMessage = '服务响应超时,请稍后重试';
  216. } elseif (strpos($errorMessage, 'not found') !== false || strpos($errorMessage, '未找到') !== false) {
  217. $errorMessage = '请求的资源不存在';
  218. } elseif (strpos($errorMessage, 'invalid') !== false || strpos($errorMessage, '无效') !== false) {
  219. $errorMessage = '请求参数无效';
  220. }
  221. return response()->json([
  222. 'success' => false,
  223. 'message' => $errorMessage ?: '服务异常,请稍后重试',
  224. ], 500);
  225. }
  226. }
  227. /**
  228. * 轮询任务状态
  229. */
  230. public function status(string $taskId): JsonResponse
  231. {
  232. try {
  233. $task = $this->taskManager->getTaskStatus($taskId);
  234. if (!$task) {
  235. return response()->json([
  236. 'success' => false,
  237. 'message' => '任务不存在',
  238. ], 404);
  239. }
  240. return response()->json([
  241. 'success' => true,
  242. 'data' => $task,
  243. ]);
  244. } catch (\Exception $e) {
  245. Log::error('查询任务状态失败', [
  246. 'task_id' => $taskId,
  247. 'error' => $e->getMessage(),
  248. ]);
  249. return response()->json([
  250. 'success' => false,
  251. 'message' => '查询失败,请稍后重试',
  252. ], 500);
  253. }
  254. }
  255. /**
  256. * 触发PDF生成
  257. * 使用队列进行异步处理
  258. */
  259. private function triggerPdfGeneration(string $taskId, string $paperId): void
  260. {
  261. // 异步处理PDF生成 - 将任务放入队列
  262. try {
  263. dispatch(new \App\Jobs\GenerateExamPdfJob($taskId, $paperId));
  264. Log::info('PDF生成任务已加入队列', [
  265. 'task_id' => $taskId,
  266. 'paper_id' => $paperId
  267. ]);
  268. } catch (\Exception $e) {
  269. Log::error('PDF生成任务队列失败,回退到同步处理', [
  270. 'task_id' => $taskId,
  271. 'paper_id' => $paperId,
  272. 'error' => $e->getMessage()
  273. ]);
  274. // 队列失败时回退到同步处理
  275. $this->processPdfGeneration($taskId, $paperId);
  276. }
  277. }
  278. /**
  279. * 处理PDF生成(模拟后台任务)
  280. * 在实际项目中,这个方法应该在队列worker中执行
  281. */
  282. private function processPdfGeneration(string $taskId, string $paperId): void
  283. {
  284. try {
  285. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  286. // 生成试卷PDF
  287. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  288. ?? $this->questionBankService->exportExamToPdf($paperId)
  289. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  290. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  291. // 生成判卷PDF
  292. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  293. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  294. // 构建完整的试卷内容
  295. $paperModel = Paper::with('questions')->find($paperId);
  296. $examContent = $paperModel
  297. ? $this->paperPayloadService->buildExamContent($paperModel)
  298. : [];
  299. // 标记任务完成
  300. $this->taskManager->markTaskCompleted($taskId, [
  301. 'exam_content' => $examContent,
  302. 'pdfs' => [
  303. 'exam_paper_pdf' => $pdfUrl,
  304. 'grading_pdf' => $gradingPdfUrl,
  305. ],
  306. ]);
  307. Log::info('异步任务完成', [
  308. 'task_id' => $taskId,
  309. 'paper_id' => $paperId,
  310. 'pdf_url' => $pdfUrl,
  311. 'grading_pdf_url' => $gradingPdfUrl,
  312. ]);
  313. // 发送回调通知
  314. $this->taskManager->sendCallback($taskId);
  315. } catch (\Exception $e) {
  316. Log::error('PDF生成失败', [
  317. 'task_id' => $taskId,
  318. 'paper_id' => $paperId,
  319. 'error' => $e->getMessage(),
  320. ]);
  321. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  322. }
  323. }
  324. /**
  325. * 兼容字符串/数组入参
  326. */
  327. private function normalizePayload(array $payload): array
  328. {
  329. // 处理 question_count 参数:转换为 total_questions
  330. if (isset($payload['question_count']) && !isset($payload['total_questions'])) {
  331. $payload['total_questions'] = $payload['question_count'];
  332. unset($payload['question_count']);
  333. }
  334. // 处理 kp_codes:空字符串或null转换为空数组
  335. if (isset($payload['kp_codes'])) {
  336. if (is_string($payload['kp_codes'])) {
  337. $kpCodes = trim($payload['kp_codes']);
  338. if (empty($kpCodes)) {
  339. $payload['kp_codes'] = [];
  340. } else {
  341. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  342. }
  343. } elseif (!is_array($payload['kp_codes'])) {
  344. $payload['kp_codes'] = [];
  345. }
  346. } else {
  347. $payload['kp_codes'] = [];
  348. }
  349. if (isset($payload['skills']) && is_string($payload['skills'])) {
  350. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  351. }
  352. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  353. if (isset($payload[$key])) {
  354. if (is_string($payload[$key])) {
  355. $raw = trim($payload[$key]);
  356. $payload[$key] = $raw === ''
  357. ? []
  358. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  359. } elseif (!is_array($payload[$key])) {
  360. $payload[$key] = [];
  361. }
  362. }
  363. }
  364. return $payload;
  365. }
  366. private function normalizeQuestionTypeRatio(array $input): array
  367. {
  368. // 默认按 4:2:4
  369. $defaults = [
  370. '选择题' => 40,
  371. '填空题' => 20,
  372. '解答题' => 40,
  373. ];
  374. $normalized = [];
  375. foreach ($input as $key => $value) {
  376. if (!is_numeric($value)) {
  377. continue;
  378. }
  379. $type = $this->normalizeQuestionTypeKey($key);
  380. if ($type) {
  381. $normalized[$type] = (float) $value;
  382. }
  383. }
  384. $merged = array_merge($defaults, $normalized);
  385. // 归一化到 100%
  386. $sum = array_sum($merged);
  387. if ($sum > 0) {
  388. foreach ($merged as $k => $v) {
  389. $merged[$k] = round(($v / $sum) * 100, 2);
  390. }
  391. }
  392. return $merged;
  393. }
  394. private function normalizeQuestionTypeKey(string $key): ?string
  395. {
  396. $key = trim($key);
  397. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  398. return '选择题';
  399. }
  400. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  401. return '填空题';
  402. }
  403. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  404. return '解答题';
  405. }
  406. return null;
  407. }
  408. private function normalizeDifficultyRatio(array $input): array
  409. {
  410. $defaults = [
  411. '基础' => 50,
  412. '中等' => 35,
  413. '拔高' => 15,
  414. ];
  415. $normalized = [];
  416. foreach ($input as $key => $value) {
  417. if (!is_numeric($value)) {
  418. continue;
  419. }
  420. $label = trim($key);
  421. if (in_array($label, ['基础', 'easy', '简单'])) {
  422. $normalized['基础'] = (float) $value;
  423. } elseif (in_array($label, ['中等', 'medium'])) {
  424. $normalized['中等'] = (float) $value;
  425. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  426. $normalized['拔高'] = (float) $value;
  427. }
  428. }
  429. return array_merge($defaults, $normalized);
  430. }
  431. private function normalizeDifficultyCategory(?string $category): string
  432. {
  433. if (!$category) {
  434. return '基础';
  435. }
  436. $category = trim($category);
  437. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  438. return $category === 'easy' ? '基础' : $category;
  439. }
  440. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  441. return '拔高';
  442. }
  443. return '基础';
  444. }
  445. private function hydrateQuestions(array $questions, array $kpCodes): array
  446. {
  447. $normalized = [];
  448. foreach ($questions as $question) {
  449. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  450. $score = $question['score'] ?? $this->defaultScore($type);
  451. $normalized[] = [
  452. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  453. 'question_id' => $question['question_id'] ?? null,
  454. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  455. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  456. 'content' => $question['content'] ?? $question['stem'] ?? '',
  457. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  458. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  459. 'solution' => $question['solution'] ?? '',
  460. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  461. 'score' => $score,
  462. 'estimated_time' => $question['estimated_time'] ?? 300,
  463. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  464. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  465. ];
  466. }
  467. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  468. }
  469. private function guessType(array $question): string
  470. {
  471. if (!empty($question['options']) && is_array($question['options'])) {
  472. return '选择题';
  473. }
  474. $content = $question['stem'] ?? $question['content'] ?? '';
  475. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  476. return '填空题';
  477. }
  478. return '解答题';
  479. }
  480. /**
  481. * 根据题目类型获取默认分值(中国中学卷子标准)
  482. * 选择题:5分/题,填空题:5分/题,解答题:10分/题
  483. */
  484. private function defaultScore(string $type): int
  485. {
  486. return match ($type) {
  487. '选择题' => 5,
  488. '填空题' => 5,
  489. '解答题' => 10,
  490. default => 5,
  491. };
  492. }
  493. /**
  494. * 计算试卷总分并调整各题目分值,确保总分接近目标分数
  495. * 符合中国中学卷子标准:
  496. * - 选择题:约40%总分(每题4-6分,整数分值)
  497. * - 填空题:约25%总分(每题4-6分,整数分值)
  498. * - 解答题:约35%总分(每题8-12分,整数分值)
  499. * 使用组合优化算法确保:
  500. * 1. 所有分值都是整数(无小数点)
  501. * 2. 同类型题目分值均匀
  502. * 3. 总分精确匹配目标分数(或最接近)
  503. */
  504. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  505. {
  506. if (empty($questions)) {
  507. return $questions;
  508. }
  509. // 统计各类型题目数量
  510. $typeCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  511. foreach ($questions as $question) {
  512. $type = $question['question_type'] ?? 'answer';
  513. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  514. $type = 'choice';
  515. } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
  516. $type = 'fill';
  517. } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
  518. $type = 'answer';
  519. }
  520. if (isset($typeCounts[$type])) {
  521. $typeCounts[$type]++;
  522. }
  523. }
  524. // 标准分值范围
  525. $standardScoreRanges = [
  526. 'choice' => ['min' => 4, 'max' => 6],
  527. 'fill' => ['min' => 4, 'max' => 6],
  528. 'answer' => ['min' => 8, 'max' => 12],
  529. ];
  530. // 目标比例
  531. $typeRatios = ['choice' => 0.40, 'fill' => 0.25, 'answer' => 0.35];
  532. // 检查可用题型
  533. $availableTypes = array_filter($typeCounts, fn($count) => $count > 0);
  534. $availableTypeCount = count($availableTypes);
  535. $isPartialTypes = $availableTypeCount < 3 && $availableTypeCount > 0;
  536. if ($isPartialTypes) {
  537. $equalRatio = 1.0 / $availableTypeCount;
  538. foreach ($typeCounts as $type => $count) {
  539. if ($count > 0) {
  540. $typeRatios[$type] = $equalRatio;
  541. } else {
  542. $typeRatios[$type] = 0;
  543. }
  544. }
  545. }
  546. $typeQuestionIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  547. // 记录每种题型的题目索引
  548. foreach ($questions as $index => $question) {
  549. $type = $question['question_type'] ?? 'answer';
  550. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  551. $type = 'choice';
  552. } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
  553. $type = 'fill';
  554. } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
  555. $type = 'answer';
  556. }
  557. $typeQuestionIndexes[$type][] = $index;
  558. }
  559. // 生成每种题型的可能分值选项
  560. $typeScoreOptions = [];
  561. foreach ($typeQuestionIndexes as $type => $indexes) {
  562. if (empty($indexes)) {
  563. continue;
  564. }
  565. $typeQuestionCount = count($indexes);
  566. $minScore = $standardScoreRanges[$type]['min'];
  567. $maxScore = $standardScoreRanges[$type]['max'];
  568. $targetTotal = $targetTotalScore * $typeRatios[$type];
  569. $idealPerQuestion = $targetTotal / $typeQuestionCount;
  570. $options = [];
  571. // 添加标准范围内的选项
  572. for ($score = $minScore; $score <= $maxScore; $score++) {
  573. $total = $score * $typeQuestionCount;
  574. $options[] = [
  575. 'score' => $score,
  576. 'total' => $total,
  577. 'difference' => abs($targetTotalScore - $total),
  578. ];
  579. }
  580. // 如果是部分题型,大幅扩展搜索范围
  581. if ($isPartialTypes) {
  582. $idealScore = (int) round($idealPerQuestion);
  583. $searchMin = max($minScore, $idealScore - 10);
  584. $searchMax = $idealScore + 10;
  585. for ($score = $searchMin; $score <= $searchMax; $score++) {
  586. if ($score >= $minScore) {
  587. $total = $score * $typeQuestionCount;
  588. if (!in_array($total, array_column($options, 'total'))) {
  589. $options[] = [
  590. 'score' => $score,
  591. 'total' => $total,
  592. 'difference' => abs($targetTotalScore - $total),
  593. ];
  594. }
  595. }
  596. }
  597. }
  598. $typeScoreOptions[$type] = $options;
  599. }
  600. // 生成所有可能的组合
  601. $types = array_keys(array_filter($typeQuestionIndexes, fn($indexes) => !empty($indexes)));
  602. $allCombinations = [[]];
  603. foreach ($types as $type) {
  604. $newCombinations = [];
  605. foreach ($allCombinations as $combo) {
  606. foreach ($typeScoreOptions[$type] as $option) {
  607. $newCombo = $combo;
  608. $newCombo[$type] = $option;
  609. $newCombinations[] = $newCombo;
  610. }
  611. }
  612. $allCombinations = $newCombinations;
  613. }
  614. // 找到最佳组合(优先精确匹配,其次最接近)
  615. $bestCombination = null;
  616. $bestDifference = PHP_FLOAT_MAX;
  617. $exactMatchFound = false;
  618. foreach ($allCombinations as $combo) {
  619. $totalScore = array_sum(array_column($combo, 'total'));
  620. $difference = abs($targetTotalScore - $totalScore);
  621. if ($difference == 0) {
  622. $bestCombination = $combo;
  623. $exactMatchFound = true;
  624. break;
  625. }
  626. if ($difference < $bestDifference) {
  627. $bestDifference = $difference;
  628. $bestCombination = $combo;
  629. }
  630. }
  631. // 应用最佳组合
  632. $adjustedQuestions = [];
  633. if ($bestCombination) {
  634. foreach ($bestCombination as $type => $option) {
  635. $score = $option['score'];
  636. foreach ($typeQuestionIndexes[$type] as $index) {
  637. $question = $questions[$index];
  638. $question['score'] = $score;
  639. $adjustedQuestions[$index] = $question;
  640. }
  641. }
  642. }
  643. return array_values($adjustedQuestions);
  644. }
  645. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  646. {
  647. $questionIds = [];
  648. if (!empty($mistakeQuestionIds)) {
  649. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  650. }
  651. if (!empty($mistakeIds)) {
  652. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  653. ->where('student_id', $studentId)
  654. ->whereIn('id', $mistakeIds)
  655. ->pluck('question_id')
  656. ->filter()
  657. ->values()
  658. ->all();
  659. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  660. }
  661. $questionIds = array_values(array_unique(array_filter($questionIds)));
  662. return $questionIds;
  663. }
  664. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  665. {
  666. if (empty($requestedIds)) {
  667. return $questions;
  668. }
  669. $order = array_flip($requestedIds);
  670. usort($questions, function ($a, $b) use ($order) {
  671. $aId = (string) ($a['id'] ?? '');
  672. $bId = (string) ($b['id'] ?? '');
  673. $aPos = $order[$aId] ?? PHP_INT_MAX;
  674. $bPos = $order[$bId] ?? PHP_INT_MAX;
  675. return $aPos <=> $bPos;
  676. });
  677. return $questions;
  678. }
  679. }