IntelligentExamController.php 30 KB

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