IntelligentExamController.php 32 KB

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