IntelligentExamController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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 Illuminate\Http\JsonResponse;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Facades\Http;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\URL;
  15. class IntelligentExamController extends Controller
  16. {
  17. private LearningAnalyticsService $learningAnalyticsService;
  18. private QuestionBankService $questionBankService;
  19. private ExamPdfExportService $pdfExportService;
  20. private PaperPayloadService $paperPayloadService;
  21. public function __construct(
  22. LearningAnalyticsService $learningAnalyticsService,
  23. QuestionBankService $questionBankService,
  24. ExamPdfExportService $pdfExportService,
  25. PaperPayloadService $paperPayloadService
  26. ) {
  27. $this->learningAnalyticsService = $learningAnalyticsService;
  28. $this->questionBankService = $questionBankService;
  29. $this->pdfExportService = $pdfExportService;
  30. $this->paperPayloadService = $paperPayloadService;
  31. }
  32. /**
  33. * 外部API:生成智能试卷(异步模式)
  34. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  35. */
  36. public function store(Request $request): JsonResponse
  37. {
  38. $normalized = $this->normalizePayload($request->all());
  39. $validator = validator($normalized, [
  40. 'student_id' => 'required|string',
  41. 'teacher_id' => 'required|string',
  42. 'paper_name' => 'nullable|string|max:255',
  43. 'grade' => 'nullable|string|max:50',
  44. 'total_questions' => 'required|integer|min:6|max:100',
  45. 'difficulty_category' => 'nullable|string',
  46. 'kp_codes' => 'nullable|array',
  47. 'kp_codes.*' => 'string',
  48. 'skills' => 'array',
  49. 'skills.*' => 'string',
  50. 'question_type_ratio' => 'array',
  51. 'difficulty_ratio' => 'array',
  52. 'total_score' => 'nullable|numeric|min:1|max:1000',
  53. ]);
  54. if ($validator->fails()) {
  55. return response()->json([
  56. 'success' => false,
  57. 'message' => '参数错误',
  58. 'errors' => $validator->errors()->toArray(),
  59. ], 422);
  60. }
  61. $data = $validator->validated();
  62. // 确保 kp_codes 是数组,如果为空则设置为空数组
  63. $data['kp_codes'] = $data['kp_codes'] ?? [];
  64. if (!is_array($data['kp_codes'])) {
  65. $data['kp_codes'] = [];
  66. }
  67. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  68. $difficultyRatio = $this->normalizeDifficultyRatio($data['difficulty_ratio'] ?? []);
  69. $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
  70. $difficultyCategory = $this->normalizeDifficultyCategory($data['difficulty_category'] ?? null);
  71. try {
  72. // 第一步:生成智能试卷(同步)
  73. $result = $this->learningAnalyticsService->generateIntelligentExam([
  74. 'student_id' => $data['student_id'],
  75. 'grade' => $data['grade'] ?? null,
  76. 'total_questions' => $data['total_questions'],
  77. 'kp_codes' => $data['kp_codes'],
  78. 'skills' => $data['skills'] ?? [],
  79. 'question_type_ratio' => $questionTypeRatio,
  80. 'difficulty_ratio' => $difficultyRatio,
  81. ]);
  82. if (empty($result['success'])) {
  83. return response()->json([
  84. 'success' => false,
  85. 'message' => $result['message'] ?? '智能出卷失败',
  86. ], 400);
  87. }
  88. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  89. if (empty($questions)) {
  90. return response()->json([
  91. 'success' => false,
  92. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  93. ], 400);
  94. }
  95. $totalScore = array_sum(array_column($questions, 'score'));
  96. // 第二步:保存试卷到数据库(同步)
  97. $paperId = $this->questionBankService->saveExamToDatabase([
  98. 'paper_name' => $paperName,
  99. 'student_id' => $data['student_id'],
  100. 'teacher_id' => $data['teacher_id'],
  101. 'difficulty_category' => $difficultyCategory,
  102. 'total_score' => $data['total_score'] ?? $totalScore,
  103. 'questions' => $questions,
  104. ]);
  105. if (!$paperId) {
  106. return response()->json([
  107. 'success' => false,
  108. 'message' => '试卷保存失败',
  109. ], 500);
  110. }
  111. // 第三步:创建异步任务(异步)
  112. $taskId = $this->createAsyncTask($paperId, $data);
  113. // 生成识别码
  114. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  115. // 立即返回完整的试卷数据(不等待PDF生成)
  116. $paperModel = Paper::with('questions')->find($paperId);
  117. $examContent = $paperModel
  118. ? $this->paperPayloadService->buildExamContent($paperModel)
  119. : [];
  120. $payload = [
  121. 'success' => true,
  122. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  123. 'data' => [
  124. 'task_id' => $taskId,
  125. 'paper_id' => $paperId,
  126. 'status' => 'processing',
  127. // 识别码
  128. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  129. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  130. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  131. 'exam_content' => $examContent,
  132. 'urls' => [
  133. // 通过paper_id获取HTML预览
  134. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  135. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  136. ],
  137. 'pdfs' => [
  138. // PDF生成完成后通过状态查询获取
  139. 'exam_paper_pdf' => null,
  140. 'grading_pdf' => null,
  141. ],
  142. 'stats' => $result['stats'] ?? null,
  143. 'created_at' => now()->toISOString(),
  144. ],
  145. ];
  146. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  147. } catch (\Exception $e) {
  148. Log::error('Intelligent exam API failed', [
  149. 'error' => $e->getMessage(),
  150. 'trace' => $e->getTraceAsString(),
  151. ]);
  152. return response()->json([
  153. 'success' => false,
  154. 'message' => '服务异常,请稍后重试',
  155. ], 500);
  156. }
  157. }
  158. /**
  159. * 轮询任务状态
  160. */
  161. public function status(string $taskId): JsonResponse
  162. {
  163. try {
  164. $task = $this->getTaskStatus($taskId);
  165. if (!$task) {
  166. return response()->json([
  167. 'success' => false,
  168. 'message' => '任务不存在',
  169. ], 404);
  170. }
  171. return response()->json([
  172. 'success' => true,
  173. 'data' => $task,
  174. ]);
  175. } catch (\Exception $e) {
  176. Log::error('查询任务状态失败', [
  177. 'task_id' => $taskId,
  178. 'error' => $e->getMessage(),
  179. ]);
  180. return response()->json([
  181. 'success' => false,
  182. 'message' => '查询失败,请稍后重试',
  183. ], 500);
  184. }
  185. }
  186. /**
  187. * 创建异步任务
  188. */
  189. private function createAsyncTask(string $paperId, array $data): string
  190. {
  191. $taskId = 'task_' . uniqid() . '_' . substr(md5($paperId . time()), 0, 8);
  192. // 保存任务信息到缓存
  193. $taskData = [
  194. 'task_id' => $taskId,
  195. 'paper_id' => $paperId,
  196. 'status' => 'processing',
  197. 'created_at' => now()->toISOString(),
  198. 'updated_at' => now()->toISOString(),
  199. 'progress' => 0,
  200. 'message' => '正在生成试卷...',
  201. 'data' => $data,
  202. 'callback_url' => $data['callback_url'] ?? null, // 支持回调URL
  203. ];
  204. // 保存到缓存,24小时过期
  205. cache()->put("exam_task:{$taskId}", $taskData, now()->addDay());
  206. // 触发后台处理(在实际项目中,这里应该使用队列)
  207. // dispatch(new GenerateExamPdfJob($taskId, $paperId));
  208. // 目前使用同步调用来模拟异步
  209. $this->processPdfGeneration($taskId, $paperId);
  210. return $taskId;
  211. }
  212. /**
  213. * 获取任务状态
  214. */
  215. private function getTaskStatus(string $taskId): ?array
  216. {
  217. return cache()->get("exam_task:{$taskId}");
  218. }
  219. /**
  220. * 处理PDF生成(模拟后台任务)
  221. * 在实际项目中,这个方法应该在队列worker中执行
  222. */
  223. private function processPdfGeneration(string $taskId, string $paperId): void
  224. {
  225. try {
  226. // 更新任务状态
  227. $this->updateTaskStatus($taskId, [
  228. 'status' => 'processing',
  229. 'progress' => 10,
  230. 'message' => '开始生成试卷PDF...',
  231. ]);
  232. // 生成试卷PDF
  233. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  234. ?? $this->questionBankService->exportExamToPdf($paperId)
  235. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  236. $this->updateTaskStatus($taskId, [
  237. 'progress' => 50,
  238. 'message' => '试卷PDF生成完成,开始生成判卷PDF...',
  239. ]);
  240. // 生成判卷PDF
  241. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  242. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  243. // 构建完整的试卷内容
  244. $paperModel = Paper::with('questions')->find($paperId);
  245. $examContent = $paperModel
  246. ? $this->paperPayloadService->buildExamContent($paperModel)
  247. : [];
  248. // 更新任务状态为完成
  249. $this->updateTaskStatus($taskId, [
  250. 'status' => 'completed',
  251. 'progress' => 100,
  252. 'message' => 'PDF生成完成',
  253. 'exam_content' => $examContent, // 包含完整试卷数据
  254. 'pdfs' => [
  255. 'exam_paper_pdf' => $pdfUrl,
  256. 'grading_pdf' => $gradingPdfUrl,
  257. ],
  258. 'completed_at' => now()->toISOString(),
  259. ]);
  260. Log::info('异步任务完成', [
  261. 'task_id' => $taskId,
  262. 'paper_id' => $paperId,
  263. 'pdf_url' => $pdfUrl,
  264. 'grading_pdf_url' => $gradingPdfUrl,
  265. ]);
  266. // 发送回调通知(如果提供了callback_url)
  267. $this->sendCallbackNotification($taskId);
  268. } catch (\Exception $e) {
  269. Log::error('PDF生成失败', [
  270. 'task_id' => $taskId,
  271. 'paper_id' => $paperId,
  272. 'error' => $e->getMessage(),
  273. ]);
  274. // 更新任务状态为失败
  275. $this->updateTaskStatus($taskId, [
  276. 'status' => 'failed',
  277. 'progress' => 0,
  278. 'message' => 'PDF生成失败: ' . $e->getMessage(),
  279. 'error' => $e->getMessage(),
  280. ]);
  281. }
  282. }
  283. /**
  284. * 更新任务状态
  285. */
  286. private function updateTaskStatus(string $taskId, array $updates): void
  287. {
  288. $task = $this->getTaskStatus($taskId);
  289. if (!$task) {
  290. return;
  291. }
  292. $updatedTask = array_merge($task, $updates, [
  293. 'updated_at' => now()->toISOString(),
  294. ]);
  295. cache()->put("exam_task:{$taskId}", $updatedTask, now()->addDay());
  296. }
  297. /**
  298. * 发送回调通知
  299. */
  300. private function sendCallbackNotification(string $taskId): void
  301. {
  302. $task = $this->getTaskStatus($taskId);
  303. if (!$task || !$task['callback_url']) {
  304. return; // 没有回调URL,不需要发送通知
  305. }
  306. try {
  307. $payload = [
  308. 'task_id' => $task['task_id'],
  309. 'paper_id' => $task['paper_id'],
  310. 'status' => $task['status'],
  311. 'exam_content' => $task['exam_content'] ?? null,
  312. 'pdfs' => $task['pdfs'] ?? null,
  313. 'stats' => $task['stats'] ?? null,
  314. 'completed_at' => $task['completed_at'],
  315. 'callback_type' => 'exam_pdf_generated',
  316. ];
  317. $response = Http::timeout(30)
  318. ->post($task['callback_url'], $payload);
  319. if ($response->successful()) {
  320. Log::info('回调通知发送成功', [
  321. 'task_id' => $taskId,
  322. 'callback_url' => $task['callback_url'],
  323. ]);
  324. } else {
  325. Log::warning('回调通知发送失败', [
  326. 'task_id' => $taskId,
  327. 'callback_url' => $task['callback_url'],
  328. 'status' => $response->status(),
  329. ]);
  330. }
  331. } catch (\Exception $e) {
  332. Log::error('回调通知异常', [
  333. 'task_id' => $taskId,
  334. 'callback_url' => $task['callback_url'] ?? 'unknown',
  335. 'error' => $e->getMessage(),
  336. ]);
  337. }
  338. }
  339. /**
  340. * 兼容字符串/数组入参
  341. */
  342. private function normalizePayload(array $payload): array
  343. {
  344. // 处理 kp_codes:空字符串或null转换为空数组
  345. if (isset($payload['kp_codes'])) {
  346. if (is_string($payload['kp_codes'])) {
  347. $kpCodes = trim($payload['kp_codes']);
  348. if (empty($kpCodes)) {
  349. $payload['kp_codes'] = [];
  350. } else {
  351. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  352. }
  353. } elseif (!is_array($payload['kp_codes'])) {
  354. $payload['kp_codes'] = [];
  355. }
  356. } else {
  357. $payload['kp_codes'] = [];
  358. }
  359. if (isset($payload['skills']) && is_string($payload['skills'])) {
  360. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  361. }
  362. return $payload;
  363. }
  364. private function normalizeQuestionTypeRatio(array $input): array
  365. {
  366. // 默认按 4:2:4
  367. $defaults = [
  368. '选择题' => 40,
  369. '填空题' => 20,
  370. '解答题' => 40,
  371. ];
  372. $normalized = [];
  373. foreach ($input as $key => $value) {
  374. if (!is_numeric($value)) {
  375. continue;
  376. }
  377. $type = $this->normalizeQuestionTypeKey($key);
  378. if ($type) {
  379. $normalized[$type] = (float) $value;
  380. }
  381. }
  382. $merged = array_merge($defaults, $normalized);
  383. // 归一化到 100%
  384. $sum = array_sum($merged);
  385. if ($sum > 0) {
  386. foreach ($merged as $k => $v) {
  387. $merged[$k] = round(($v / $sum) * 100, 2);
  388. }
  389. }
  390. return $merged;
  391. }
  392. private function normalizeQuestionTypeKey(string $key): ?string
  393. {
  394. $key = trim($key);
  395. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice'])) {
  396. return '选择题';
  397. }
  398. if (in_array($key, ['fill', '填空题', 'blank'])) {
  399. return '填空题';
  400. }
  401. if (in_array($key, ['answer', '解答题', '计算题'])) {
  402. return '解答题';
  403. }
  404. return null;
  405. }
  406. private function normalizeDifficultyRatio(array $input): array
  407. {
  408. $defaults = [
  409. '基础' => 50,
  410. '中等' => 35,
  411. '拔高' => 15,
  412. ];
  413. $normalized = [];
  414. foreach ($input as $key => $value) {
  415. if (!is_numeric($value)) {
  416. continue;
  417. }
  418. $label = trim($key);
  419. if (in_array($label, ['基础', 'easy', '简单'])) {
  420. $normalized['基础'] = (float) $value;
  421. } elseif (in_array($label, ['中等', 'medium'])) {
  422. $normalized['中等'] = (float) $value;
  423. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  424. $normalized['拔高'] = (float) $value;
  425. }
  426. }
  427. return array_merge($defaults, $normalized);
  428. }
  429. private function normalizeDifficultyCategory(?string $category): string
  430. {
  431. if (!$category) {
  432. return '基础';
  433. }
  434. $category = trim($category);
  435. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  436. return $category === 'easy' ? '基础' : $category;
  437. }
  438. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  439. return '拔高';
  440. }
  441. return '基础';
  442. }
  443. private function hydrateQuestions(array $questions, array $kpCodes): array
  444. {
  445. $normalized = [];
  446. foreach ($questions as $question) {
  447. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  448. $score = $question['score'] ?? $this->defaultScore($type);
  449. $normalized[] = [
  450. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  451. 'question_id' => $question['question_id'] ?? null,
  452. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  453. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  454. 'content' => $question['content'] ?? $question['stem'] ?? '',
  455. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  456. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  457. 'solution' => $question['solution'] ?? '',
  458. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  459. 'score' => $score,
  460. 'estimated_time' => $question['estimated_time'] ?? 300,
  461. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  462. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  463. ];
  464. }
  465. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  466. }
  467. private function guessType(array $question): string
  468. {
  469. if (!empty($question['options']) && is_array($question['options'])) {
  470. return '选择题';
  471. }
  472. $content = $question['stem'] ?? $question['content'] ?? '';
  473. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  474. return '填空题';
  475. }
  476. return '解答题';
  477. }
  478. private function defaultScore(string $type): int
  479. {
  480. if ($type === '选择题' || $type === '填空题') {
  481. return 5;
  482. }
  483. return 10;
  484. }
  485. /**
  486. * 构建完整的试卷信息(包含所有题目详情)
  487. */
  488. private function buildCompleteExamContent(string $paperId): array
  489. {
  490. $paper = Paper::with('questions')->find($paperId);
  491. if (!$paper) {
  492. return [];
  493. }
  494. return $this->paperPayloadService->buildExamContent($paper);
  495. }
  496. /**
  497. * 获取题型中文标签
  498. */
  499. private function getQuestionTypeLabel(string $type): string
  500. {
  501. return match($type) {
  502. 'choice' => '选择题',
  503. 'fill' => '填空题',
  504. 'answer' => '解答题',
  505. default => '未知题型'
  506. };
  507. }
  508. /**
  509. * 获取难度中文标签
  510. */
  511. private function getDifficultyLabel(?float $difficulty): string
  512. {
  513. if ($difficulty === null) return '未知';
  514. if ($difficulty <= 0.4) return '基础';
  515. if ($difficulty <= 0.7) return '中等';
  516. return '拔高';
  517. }
  518. /**
  519. * 获取题型分布
  520. */
  521. private function getTypeDistribution($questions): array
  522. {
  523. $distribution = [];
  524. foreach ($questions as $q) {
  525. $type = $q->question_type;
  526. $distribution[$type] = ($distribution[$type] ?? 0) + 1;
  527. }
  528. return $distribution;
  529. }
  530. /**
  531. * 获取难度分布
  532. */
  533. private function getDifficultyDistribution($questions): array
  534. {
  535. $distribution = [];
  536. foreach ($questions as $q) {
  537. $label = $this->getDifficultyLabel($q->difficulty);
  538. $distribution[$label] = ($distribution[$label] ?? 0) + 1;
  539. }
  540. return $distribution;
  541. }
  542. /**
  543. * 获取知识点分布
  544. */
  545. private function getKnowledgePointDistribution($questions): array
  546. {
  547. $distribution = [];
  548. foreach ($questions as $q) {
  549. $kp = $q->knowledge_point;
  550. if ($kp) {
  551. $distribution[$kp] = ($distribution[$kp] ?? 0) + 1;
  552. }
  553. }
  554. return $distribution;
  555. }
  556. /**
  557. * 从题目中提取技能标签
  558. */
  559. private function extractSkillsFromQuestions($questions): array
  560. {
  561. $skills = [];
  562. // 注意:由于题库在PostgreSQL中,MySQL的questions表可能不存在
  563. // 我们从PaperQuestion的solution或metadata中提取技能信息
  564. foreach ($questions as $q) {
  565. // 从解题过程中提取技能关键词
  566. $solution = $q->solution ?? '';
  567. if ($solution) {
  568. // 简单的技能提取(基于常见关键词)
  569. $skillKeywords = ['代入法', '配方法', '因式分解', '换元法', '判别式', '求根公式', '韦达定理'];
  570. foreach ($skillKeywords as $keyword) {
  571. if (strpos($solution, $keyword) !== false) {
  572. $skills[] = $keyword;
  573. }
  574. }
  575. }
  576. // 从题目文本中提取技能标签(如果存在)
  577. $stem = $q->question_text ?? '';
  578. if ($stem) {
  579. // 尝试从题干中提取技能信息(格式如:{技能1,技能2})
  580. preg_match_all('/\{([^}]+)\}/', $stem, $matches);
  581. foreach ($matches[1] as $match) {
  582. $skillList = array_map('trim', explode(',', $match));
  583. $skills = array_merge($skills, $skillList);
  584. }
  585. }
  586. }
  587. return array_unique(array_filter($skills));
  588. }
  589. /**
  590. * 生成试卷识别码
  591. * 格式:试卷码 = 1 + 12位数字,判卷码 = 2 + 12位数字
  592. */
  593. private function generatePaperCodes(string $paperId): array
  594. {
  595. // 从 paper_id 提取12位数字部分(格式: paper_xxxxxxxxxxxx)
  596. if (preg_match('/paper_(\d{12})/', $paperId, $matches)) {
  597. $paperIdNum = $matches[1];
  598. } else {
  599. // 兼容旧格式,取数字部分或生成哈希
  600. $paperIdNum = preg_replace('/[^0-9]/', '', $paperId);
  601. $paperIdNum = str_pad(substr($paperIdNum, 0, 12), 12, '0', STR_PAD_LEFT);
  602. }
  603. return [
  604. 'paper_id_num' => $paperIdNum,
  605. 'exam_code' => '1' . $paperIdNum, // 试卷识别码:1 + 12位数字
  606. 'grading_code' => '2' . $paperIdNum, // 判卷识别码:2 + 12位数字
  607. ];
  608. }
  609. }