IntelligentExamController.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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"或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. // 将student_id转换为字符串(支持数字和字符串输入)
  342. if (isset($payload['student_id'])) {
  343. $payload['student_id'] = (string) $payload['student_id'];
  344. }
  345. // 处理 kp_codes:空字符串或null转换为空数组
  346. if (isset($payload['kp_codes'])) {
  347. if (is_string($payload['kp_codes'])) {
  348. $kpCodes = trim($payload['kp_codes']);
  349. if (empty($kpCodes)) {
  350. $payload['kp_codes'] = [];
  351. } else {
  352. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  353. }
  354. } elseif (!is_array($payload['kp_codes'])) {
  355. $payload['kp_codes'] = [];
  356. }
  357. } else {
  358. $payload['kp_codes'] = [];
  359. }
  360. if (isset($payload['skills']) && is_string($payload['skills'])) {
  361. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  362. }
  363. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  364. if (isset($payload[$key])) {
  365. if (is_string($payload[$key])) {
  366. $raw = trim($payload[$key]);
  367. $payload[$key] = $raw === ''
  368. ? []
  369. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  370. } elseif (!is_array($payload[$key])) {
  371. $payload[$key] = [];
  372. }
  373. }
  374. }
  375. return $payload;
  376. }
  377. private function normalizeQuestionTypeRatio(array $input): array
  378. {
  379. // 默认按 4:2:4
  380. $defaults = [
  381. '选择题' => 40,
  382. '填空题' => 20,
  383. '解答题' => 40,
  384. ];
  385. $normalized = [];
  386. foreach ($input as $key => $value) {
  387. if (!is_numeric($value)) {
  388. continue;
  389. }
  390. $type = $this->normalizeQuestionTypeKey($key);
  391. if ($type) {
  392. $normalized[$type] = (float) $value;
  393. }
  394. }
  395. $merged = array_merge($defaults, $normalized);
  396. // 归一化到 100%
  397. $sum = array_sum($merged);
  398. if ($sum > 0) {
  399. foreach ($merged as $k => $v) {
  400. $merged[$k] = round(($v / $sum) * 100, 2);
  401. }
  402. }
  403. return $merged;
  404. }
  405. private function normalizeQuestionTypeKey(string $key): ?string
  406. {
  407. $key = trim($key);
  408. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  409. return '选择题';
  410. }
  411. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  412. return '填空题';
  413. }
  414. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  415. return '解答题';
  416. }
  417. return null;
  418. }
  419. private function normalizeDifficultyRatio(array $input): array
  420. {
  421. $defaults = [
  422. '基础' => 50,
  423. '中等' => 35,
  424. '拔高' => 15,
  425. ];
  426. $normalized = [];
  427. foreach ($input as $key => $value) {
  428. if (!is_numeric($value)) {
  429. continue;
  430. }
  431. $label = trim($key);
  432. if (in_array($label, ['基础', 'easy', '简单'])) {
  433. $normalized['基础'] = (float) $value;
  434. } elseif (in_array($label, ['中等', 'medium'])) {
  435. $normalized['中等'] = (float) $value;
  436. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  437. $normalized['拔高'] = (float) $value;
  438. }
  439. }
  440. return array_merge($defaults, $normalized);
  441. }
  442. private function normalizeDifficultyCategory(?string $category): string
  443. {
  444. if (!$category) {
  445. return '基础';
  446. }
  447. $category = trim($category);
  448. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  449. return $category === 'easy' ? '基础' : $category;
  450. }
  451. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  452. return '拔高';
  453. }
  454. return '基础';
  455. }
  456. private function hydrateQuestions(array $questions, array $kpCodes): array
  457. {
  458. $normalized = [];
  459. foreach ($questions as $question) {
  460. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  461. $score = $question['score'] ?? $this->defaultScore($type);
  462. $normalized[] = [
  463. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  464. 'question_id' => $question['question_id'] ?? null,
  465. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  466. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  467. 'content' => $question['content'] ?? $question['stem'] ?? '',
  468. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  469. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  470. 'solution' => $question['solution'] ?? '',
  471. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  472. 'score' => $score,
  473. 'estimated_time' => $question['estimated_time'] ?? 300,
  474. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  475. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  476. ];
  477. }
  478. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  479. }
  480. private function guessType(array $question): string
  481. {
  482. if (!empty($question['options']) && is_array($question['options'])) {
  483. return '选择题';
  484. }
  485. $content = $question['stem'] ?? $question['content'] ?? '';
  486. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  487. return '填空题';
  488. }
  489. return '解答题';
  490. }
  491. /**
  492. * 根据题目类型获取默认分值(中国中学卷子标准)
  493. * 选择题:5分/题,填空题:5分/题,解答题:10分/题
  494. */
  495. private function defaultScore(string $type): int
  496. {
  497. return match ($type) {
  498. '选择题' => 5,
  499. '填空题' => 5,
  500. '解答题' => 10,
  501. default => 5,
  502. };
  503. }
  504. /**
  505. * 计算试卷总分并调整各题目分值,确保总分接近目标分数
  506. * 符合中国中学卷子标准:
  507. * - 选择题:约40%总分(每题4-6分,整数分值)
  508. * - 填空题:约25%总分(每题4-6分,整数分值)
  509. * - 解答题:约35%总分(每题8-12分,整数分值)
  510. * 使用组合优化算法确保:
  511. * 1. 所有分值都是整数(无小数点)
  512. * 2. 同类型题目分值均匀
  513. * 3. 总分精确匹配目标分数(或最接近)
  514. */
  515. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  516. {
  517. if (empty($questions)) {
  518. return $questions;
  519. }
  520. // 统计各类型题目数量
  521. $typeCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  522. foreach ($questions as $question) {
  523. $type = $question['question_type'] ?? 'answer';
  524. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  525. $type = 'choice';
  526. } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
  527. $type = 'fill';
  528. } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
  529. $type = 'answer';
  530. }
  531. if (isset($typeCounts[$type])) {
  532. $typeCounts[$type]++;
  533. }
  534. }
  535. // 标准分值范围
  536. $standardScoreRanges = [
  537. 'choice' => ['min' => 4, 'max' => 6],
  538. 'fill' => ['min' => 4, 'max' => 6],
  539. 'answer' => ['min' => 8, 'max' => 12],
  540. ];
  541. // 目标比例
  542. $typeRatios = ['choice' => 0.40, 'fill' => 0.25, 'answer' => 0.35];
  543. // 检查可用题型
  544. $availableTypes = array_filter($typeCounts, fn($count) => $count > 0);
  545. $availableTypeCount = count($availableTypes);
  546. $isPartialTypes = $availableTypeCount < 3 && $availableTypeCount > 0;
  547. if ($isPartialTypes) {
  548. $equalRatio = 1.0 / $availableTypeCount;
  549. foreach ($typeCounts as $type => $count) {
  550. if ($count > 0) {
  551. $typeRatios[$type] = $equalRatio;
  552. } else {
  553. $typeRatios[$type] = 0;
  554. }
  555. }
  556. }
  557. $typeQuestionIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  558. // 记录每种题型的题目索引
  559. foreach ($questions as $index => $question) {
  560. $type = $question['question_type'] ?? 'answer';
  561. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  562. $type = 'choice';
  563. } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
  564. $type = 'fill';
  565. } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
  566. $type = 'answer';
  567. }
  568. $typeQuestionIndexes[$type][] = $index;
  569. }
  570. // 生成每种题型的可能分值选项
  571. $typeScoreOptions = [];
  572. foreach ($typeQuestionIndexes as $type => $indexes) {
  573. if (empty($indexes)) {
  574. continue;
  575. }
  576. $typeQuestionCount = count($indexes);
  577. $minScore = $standardScoreRanges[$type]['min'];
  578. $maxScore = $standardScoreRanges[$type]['max'];
  579. $targetTotal = $targetTotalScore * $typeRatios[$type];
  580. $idealPerQuestion = $targetTotal / $typeQuestionCount;
  581. $options = [];
  582. // 添加标准范围内的选项
  583. for ($score = $minScore; $score <= $maxScore; $score++) {
  584. $total = $score * $typeQuestionCount;
  585. $options[] = [
  586. 'score' => $score,
  587. 'total' => $total,
  588. 'difference' => abs($targetTotalScore - $total),
  589. ];
  590. }
  591. // 如果是部分题型,大幅扩展搜索范围
  592. if ($isPartialTypes) {
  593. $idealScore = (int) round($idealPerQuestion);
  594. $searchMin = max($minScore, $idealScore - 10);
  595. $searchMax = $idealScore + 10;
  596. for ($score = $searchMin; $score <= $searchMax; $score++) {
  597. if ($score >= $minScore) {
  598. $total = $score * $typeQuestionCount;
  599. if (!in_array($total, array_column($options, 'total'))) {
  600. $options[] = [
  601. 'score' => $score,
  602. 'total' => $total,
  603. 'difference' => abs($targetTotalScore - $total),
  604. ];
  605. }
  606. }
  607. }
  608. }
  609. $typeScoreOptions[$type] = $options;
  610. }
  611. // 生成所有可能的组合
  612. $types = array_keys(array_filter($typeQuestionIndexes, fn($indexes) => !empty($indexes)));
  613. $allCombinations = [[]];
  614. foreach ($types as $type) {
  615. $newCombinations = [];
  616. foreach ($allCombinations as $combo) {
  617. foreach ($typeScoreOptions[$type] as $option) {
  618. $newCombo = $combo;
  619. $newCombo[$type] = $option;
  620. $newCombinations[] = $newCombo;
  621. }
  622. }
  623. $allCombinations = $newCombinations;
  624. }
  625. // 找到最佳组合(优先精确匹配,其次最接近)
  626. $bestCombination = null;
  627. $bestDifference = PHP_FLOAT_MAX;
  628. $exactMatchFound = false;
  629. foreach ($allCombinations as $combo) {
  630. $totalScore = array_sum(array_column($combo, 'total'));
  631. $difference = abs($targetTotalScore - $totalScore);
  632. if ($difference == 0) {
  633. $bestCombination = $combo;
  634. $exactMatchFound = true;
  635. break;
  636. }
  637. if ($difference < $bestDifference) {
  638. $bestDifference = $difference;
  639. $bestCombination = $combo;
  640. }
  641. }
  642. // 应用最佳组合
  643. $adjustedQuestions = [];
  644. if ($bestCombination) {
  645. foreach ($bestCombination as $type => $option) {
  646. $score = $option['score'];
  647. foreach ($typeQuestionIndexes[$type] as $index) {
  648. $question = $questions[$index];
  649. $question['score'] = $score;
  650. $adjustedQuestions[$index] = $question;
  651. }
  652. }
  653. }
  654. return array_values($adjustedQuestions);
  655. }
  656. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  657. {
  658. $questionIds = [];
  659. if (!empty($mistakeQuestionIds)) {
  660. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  661. }
  662. if (!empty($mistakeIds)) {
  663. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  664. ->where('student_id', $studentId)
  665. ->whereIn('id', $mistakeIds)
  666. ->pluck('question_id')
  667. ->filter()
  668. ->values()
  669. ->all();
  670. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  671. }
  672. $questionIds = array_values(array_unique(array_filter($questionIds)));
  673. return $questionIds;
  674. }
  675. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  676. {
  677. if (empty($requestedIds)) {
  678. return $questions;
  679. }
  680. $order = array_flip($requestedIds);
  681. usort($questions, function ($a, $b) use ($order) {
  682. $aId = (string) ($a['id'] ?? '');
  683. $bId = (string) ($b['id'] ?? '');
  684. $aPos = $order[$aId] ?? PHP_INT_MAX;
  685. $bPos = $order[$bId] ?? PHP_INT_MAX;
  686. return $aPos <=> $bPos;
  687. });
  688. return $questions;
  689. }
  690. }