QuestionBankService.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. class QuestionBankService
  6. {
  7. protected string $baseUrl;
  8. public function __construct()
  9. {
  10. // 从配置文件读取base_url
  11. $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
  12. $this->baseUrl = rtrim($this->baseUrl, '/');
  13. }
  14. /**
  15. * 从题目内容中提取选项
  16. */
  17. private function extractOptions(string $content): array
  18. {
  19. // 匹配 A. B. C. D. 格式的选项
  20. if (preg_match_all('/([A-D])\.\s*(.+?)(?=[A-D]\.|$)/s', $content, $matches, PREG_SET_ORDER)) {
  21. $options = [];
  22. foreach ($matches as $match) {
  23. $optionText = trim($match[2]);
  24. // 移除末尾的换行和空白
  25. $optionText = preg_replace('/\s+$/', '', $optionText);
  26. $options[] = $optionText;
  27. }
  28. return $options;
  29. }
  30. return [];
  31. }
  32. /**
  33. * 分离题干内容和选项
  34. */
  35. private function separateStemAndOptions(string $content): array
  36. {
  37. // 如果没有选项,直接返回
  38. if (!preg_match('/[A-D]\.\s+/m', $content)) {
  39. return [$content, []];
  40. }
  41. // 提取选项
  42. $options = $this->extractOptions($content);
  43. // 提取题干(选项前的部分)
  44. $stem = preg_replace('/[A-D]\.\s+.+?(?=[A-D]\.|$)/s', '', $content);
  45. $stem = trim($stem);
  46. // 移除末尾的括号或空白
  47. $stem = preg_replace('/()\s*$/', '', $stem);
  48. $stem = trim($stem);
  49. return [$stem, $options];
  50. }
  51. /**
  52. * 获取题目列表
  53. */
  54. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  55. {
  56. try {
  57. $response = Http::timeout(10)
  58. ->get($this->baseUrl . '/questions', [
  59. 'page' => $page,
  60. 'per_page' => $perPage,
  61. ...$filters
  62. ]);
  63. if ($response->successful()) {
  64. return $response->json();
  65. }
  66. Log::warning('题库API调用失败', [
  67. 'status' => $response->status()
  68. ]);
  69. } catch (\Exception $e) {
  70. Log::error('获取题目列表失败', [
  71. 'error' => $e->getMessage()
  72. ]);
  73. }
  74. return ['data' => [], 'meta' => ['total' => 0]];
  75. }
  76. /**
  77. * 获取题目详情
  78. */
  79. public function getQuestion(string $questionCode): ?array
  80. {
  81. try {
  82. $response = Http::timeout(10)
  83. ->get($this->baseUrl . "/questions/{$questionCode}");
  84. if ($response->successful()) {
  85. return $response->json();
  86. }
  87. Log::warning('获取题目详情失败', [
  88. 'code' => $questionCode,
  89. 'status' => $response->status()
  90. ]);
  91. } catch (\Exception $e) {
  92. Log::error('获取题目详情异常', [
  93. 'code' => $questionCode,
  94. 'error' => $e->getMessage()
  95. ]);
  96. }
  97. return null;
  98. }
  99. /**
  100. * 更新题目
  101. */
  102. public function updateQuestion(string $questionCode, array $payload): bool
  103. {
  104. try {
  105. $response = Http::timeout(10)
  106. ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
  107. if ($response->successful()) {
  108. return true;
  109. }
  110. Log::warning('更新题目失败', [
  111. 'code' => $questionCode,
  112. 'status' => $response->status(),
  113. 'body' => $response->json(),
  114. ]);
  115. } catch (\Exception $e) {
  116. Log::error('更新题目异常', [
  117. 'code' => $questionCode,
  118. 'error' => $e->getMessage()
  119. ]);
  120. }
  121. return false;
  122. }
  123. /**
  124. * 筛选题目 (支持 kp_codes, skills 等高级筛选)
  125. */
  126. public function filterQuestions(array $params): array
  127. {
  128. try {
  129. $response = Http::timeout(30)
  130. ->get($this->baseUrl . '/questions', $params);
  131. if ($response->successful()) {
  132. return $response->json();
  133. }
  134. Log::warning('筛选题目API调用失败', [
  135. 'status' => $response->status(),
  136. 'params' => $params
  137. ]);
  138. } catch (\Exception $e) {
  139. Log::error('筛选题目异常', [
  140. 'error' => $e->getMessage(),
  141. 'params' => $params
  142. ]);
  143. }
  144. return ['data' => []];
  145. }
  146. /**
  147. * 批量获取题目详情(根据题目 ID 列表)
  148. */
  149. public function getQuestionsByIds(array $ids): array
  150. {
  151. if (empty($ids)) {
  152. return ['data' => []];
  153. }
  154. try {
  155. $response = Http::timeout(15)
  156. ->get($this->baseUrl . '/questions', [
  157. 'ids' => implode(',', $ids),
  158. ]);
  159. if ($response->successful()) {
  160. return $response->json();
  161. }
  162. Log::warning('批量获取题目失败', [
  163. 'ids' => $ids,
  164. 'status' => $response->status(),
  165. ]);
  166. } catch (\Exception $e) {
  167. Log::error('批量获取题目异常', [
  168. 'ids' => $ids,
  169. 'error' => $e->getMessage(),
  170. ]);
  171. }
  172. return ['data' => []];
  173. }
  174. /**
  175. * 智能生成题目(异步模式)
  176. */
  177. public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
  178. {
  179. try {
  180. // 添加回调 URL
  181. if ($callbackUrl) {
  182. $params['callback_url'] = $callbackUrl;
  183. }
  184. // 增加超时时间到60秒,确保有足够时间启动异步任务
  185. // 注意:API是异步的,只需等待任务启动(1-2秒),不需要等待AI生成完成
  186. $response = Http::timeout(60)
  187. ->post($this->baseUrl . '/generate-intelligent-questions', $params);
  188. if ($response->successful()) {
  189. return $response->json();
  190. }
  191. Log::warning('题目生成API调用失败', [
  192. 'status' => $response->status()
  193. ]);
  194. } catch (\Exception $e) {
  195. Log::error('题目生成异常', [
  196. 'error' => $e->getMessage()
  197. ]);
  198. }
  199. return ['success' => false, 'message' => '生成失败'];
  200. }
  201. /**
  202. * 获取任务状态
  203. */
  204. public function getTaskStatus(string $taskId): ?array
  205. {
  206. try {
  207. $response = Http::timeout(10)
  208. ->get($this->baseUrl . '/tasks/' . $taskId);
  209. if ($response->successful()) {
  210. return $response->json();
  211. }
  212. Log::warning('获取任务状态失败', [
  213. 'task_id' => $taskId,
  214. 'status' => $response->status()
  215. ]);
  216. } catch (\Exception $e) {
  217. Log::error('获取任务状态异常', [
  218. 'task_id' => $taskId,
  219. 'error' => $e->getMessage()
  220. ]);
  221. }
  222. return null;
  223. }
  224. /**
  225. * 获取任务列表
  226. */
  227. public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
  228. {
  229. try {
  230. $params = [
  231. 'page' => $page,
  232. 'per_page' => $perPage
  233. ];
  234. if ($status) {
  235. $params['status'] = $status;
  236. }
  237. $response = Http::timeout(10)
  238. ->get($this->baseUrl . '/tasks', $params);
  239. if ($response->successful()) {
  240. return $response->json();
  241. }
  242. Log::warning('获取任务列表失败', [
  243. 'status' => $response->status()
  244. ]);
  245. } catch (\Exception $e) {
  246. Log::error('获取任务列表异常', [
  247. 'error' => $e->getMessage()
  248. ]);
  249. }
  250. return ['data' => [], 'meta' => ['total' => 0]];
  251. }
  252. /**
  253. * 获取题目统计信息
  254. */
  255. public function getStatistics(): array
  256. {
  257. try {
  258. $response = Http::timeout(10)
  259. ->get($this->baseUrl . '/questions/statistics');
  260. if ($response->successful()) {
  261. return $response->json();
  262. }
  263. Log::warning('获取题目统计失败', [
  264. 'status' => $response->status()
  265. ]);
  266. } catch (\Exception $e) {
  267. Log::error('获取题目统计异常', [
  268. 'error' => $e->getMessage()
  269. ]);
  270. }
  271. return [
  272. 'total' => 0,
  273. 'by_difficulty' => [],
  274. 'by_kp' => [],
  275. 'by_source' => []
  276. ];
  277. }
  278. /**
  279. * 根据知识点获取题目
  280. */
  281. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  282. {
  283. try {
  284. $response = Http::timeout(10)
  285. ->get($this->baseUrl . '/questions', [
  286. 'kp_code' => $kpCode,
  287. 'limit' => $limit
  288. ]);
  289. if ($response->successful()) {
  290. return $response->json();
  291. }
  292. } catch (\Exception $e) {
  293. Log::error('根据知识点获取题目失败', [
  294. 'kp_code' => $kpCode,
  295. 'error' => $e->getMessage()
  296. ]);
  297. }
  298. return [];
  299. }
  300. /**
  301. * 删除题目
  302. */
  303. public function deleteQuestion(string $questionCode): bool
  304. {
  305. try {
  306. $response = Http::timeout(10)
  307. ->delete($this->baseUrl . "/questions/{$questionCode}");
  308. // 只有返回204(删除成功)才返回true,404(不存在)返回false
  309. if ($response->status() === 204) {
  310. return true;
  311. }
  312. if ($response->status() === 404) {
  313. Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
  314. return false;
  315. }
  316. return false;
  317. } catch (\Exception $e) {
  318. Log::error('删除题目失败', [
  319. 'question_code' => $questionCode,
  320. 'error' => $e->getMessage()
  321. ]);
  322. return false;
  323. }
  324. }
  325. /**
  326. * 智能选择试卷题目
  327. */
  328. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  329. {
  330. try {
  331. $response = Http::timeout(30)
  332. ->post($this->baseUrl . '/exam/select-questions', [
  333. 'total_questions' => $totalQuestions,
  334. 'filters' => $filters
  335. ]);
  336. if ($response->successful()) {
  337. return $response->json('data', []);
  338. }
  339. Log::warning('智能选题API调用失败', [
  340. 'status' => $response->status()
  341. ]);
  342. } catch (\Exception $e) {
  343. Log::error('智能选题异常', [
  344. 'error' => $e->getMessage()
  345. ]);
  346. }
  347. return [];
  348. }
  349. /**
  350. * 保存试卷到数据库(本地 papers 表)
  351. */
  352. public function saveExamToDatabase(array $examData): ?string
  353. {
  354. // 数据完整性检查
  355. if (empty($examData['questions'])) {
  356. Log::warning('尝试保存没有题目的试卷', [
  357. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  358. 'student_id' => $examData['student_id'] ?? 'unknown'
  359. ]);
  360. return null;
  361. }
  362. try {
  363. // 使用数据库事务确保数据一致性
  364. return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
  365. // 生成试卷ID
  366. $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
  367. Log::info('开始保存试卷到数据库', [
  368. 'paper_id' => $paperId,
  369. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  370. 'question_count' => count($examData['questions'])
  371. ]);
  372. // 使用Laravel模型保存到 papers 表
  373. $paper = \App\Models\Paper::create([
  374. 'paper_id' => $paperId,
  375. 'student_id' => $examData['student_id'] ?? '',
  376. 'teacher_id' => $examData['teacher_id'] ?? '',
  377. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  378. 'paper_type' => 'auto_generated',
  379. 'question_count' => count($examData['questions']), // 使用实际题目数量
  380. 'total_score' => $examData['total_score'] ?? 0,
  381. 'status' => 'draft',
  382. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  383. ]);
  384. // 准备题目数据
  385. $questionInsertData = [];
  386. foreach ($examData['questions'] as $index => $question) {
  387. // 验证题目基本数据
  388. if (empty($question['stem']) && empty($question['content'])) {
  389. Log::warning('跳过没有内容的题目', [
  390. 'paper_id' => $paperId,
  391. 'question_index' => $index
  392. ]);
  393. continue;
  394. }
  395. // 处理题目内容:分离题干和选项(如果存在)
  396. $rawContent = $question['stem'] ?? $question['content'] ?? '';
  397. list($stem, $options) = $this->separateStemAndOptions($rawContent);
  398. // 将选项以换行符形式附加到题干末尾,方便后续渲染
  399. if (!empty($options)) {
  400. $stemWithOptions = $stem . "\n" . implode("\n", array_map(function($opt, $idx) {
  401. return chr(65 + $idx) . '. ' . $opt;
  402. }, $options, array_keys($options)));
  403. $question['stem'] = $stemWithOptions;
  404. $question['options'] = $options;
  405. } else {
  406. $question['stem'] = $stem;
  407. }
  408. // 处理难度字段:如果是字符串则转换为数字
  409. $difficultyValue = $question['difficulty'] ?? 0.5;
  410. if (is_string($difficultyValue)) {
  411. // 将中文难度转换为数字
  412. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  413. $difficultyValue = 0.3;
  414. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  415. $difficultyValue = 0.6;
  416. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  417. $difficultyValue = 0.9;
  418. } else {
  419. $difficultyValue = 0.5;
  420. }
  421. }
  422. // 确保 knowledge_point 有值
  423. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  424. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  425. $knowledgePoint = $question['kp_code'];
  426. }
  427. // 获取题目类型
  428. $questionType = $question['question_type'] ?? 'answer';
  429. if (!$questionType) {
  430. // 如果没有类型,根据内容推断
  431. $content = $question['stem'] ?? $question['content'] ?? '';
  432. if (is_string($content)) {
  433. // 1. 优先检查填空题(下划线)
  434. if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  435. $questionType = 'fill';
  436. }
  437. // 2. 检查选择题(必须有选项 A. B. C. D.)
  438. elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
  439. if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
  440. $questionType = 'choice';
  441. } else {
  442. // 只有括号没有选项,可能是填空
  443. if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  444. $questionType = 'fill';
  445. } else {
  446. $questionType = 'answer';
  447. }
  448. }
  449. }
  450. // 3. 检查纯括号填空
  451. elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  452. $questionType = 'fill';
  453. }
  454. else {
  455. $questionType = 'answer';
  456. }
  457. } else {
  458. $questionType = 'answer';
  459. }
  460. }
  461. $questionInsertData[] = [
  462. 'paper_id' => $paperId,
  463. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  464. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  465. 'knowledge_point' => $knowledgePoint,
  466. 'question_type' => $questionType,
  467. 'question_text' => $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '',
  468. 'difficulty' => $difficultyValue,
  469. 'score' => $question['score'] ?? 5, // 默认5分
  470. 'estimated_time' => $question['estimated_time'] ?? 300,
  471. 'question_number' => $index + 1,
  472. ];
  473. }
  474. // 验证是否有有效的题目数据
  475. if (empty($questionInsertData)) {
  476. Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
  477. throw new \Exception('没有有效的题目数据');
  478. }
  479. // 使用Laravel模型批量插入题目数据
  480. \App\Models\PaperQuestion::insert($questionInsertData);
  481. // 验证插入结果,使用关联关系
  482. $insertedQuestionCount = $paper->questions()->count();
  483. if ($insertedQuestionCount !== count($questionInsertData)) {
  484. throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
  485. }
  486. Log::info('试卷保存成功', [
  487. 'paper_id' => $paperId,
  488. 'expected_questions' => count($questionInsertData),
  489. 'actual_questions' => $insertedQuestionCount,
  490. 'paper_name' => $paper->paper_name
  491. ]);
  492. return $paperId;
  493. });
  494. } catch (\Exception $e) {
  495. Log::error('保存试卷到数据库失败', [
  496. 'error' => $e->getMessage(),
  497. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  498. 'student_id' => $examData['student_id'] ?? 'unknown',
  499. 'question_count' => count($examData['questions'] ?? []),
  500. 'trace' => $e->getTraceAsString()
  501. ]);
  502. return null;
  503. }
  504. }
  505. /**
  506. * 检查数据完整性 - 发现没有题目的试卷
  507. */
  508. public function checkDataIntegrity(): array
  509. {
  510. try {
  511. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  512. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  513. ->whereDoesntHave('questions')
  514. ->get();
  515. Log::warning('发现数据不一致的试卷', [
  516. 'count' => $inconsistentPapers->count(),
  517. 'papers' => $inconsistentPapers->map(function($paper) {
  518. return [
  519. 'paper_id' => $paper->paper_id,
  520. 'paper_name' => $paper->paper_name,
  521. 'expected_questions' => $paper->question_count,
  522. 'student_id' => $paper->student_id,
  523. 'created_at' => $paper->created_at
  524. ];
  525. })->toArray()
  526. ]);
  527. return [
  528. 'inconsistent_count' => $inconsistentPapers->count(),
  529. 'papers' => $inconsistentPapers->toArray()
  530. ];
  531. } catch (\Exception $e) {
  532. Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
  533. return ['inconsistent_count' => 0, 'papers' => []];
  534. }
  535. }
  536. /**
  537. * 清理没有题目的试卷记录
  538. */
  539. public function cleanupInconsistentPapers(): int
  540. {
  541. try {
  542. return \Illuminate\Support\Facades\DB::transaction(function () {
  543. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  544. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  545. ->whereDoesntHave('questions')
  546. ->get();
  547. if ($inconsistentPapers->isEmpty()) {
  548. return 0;
  549. }
  550. // 获取要删除的试卷ID列表
  551. $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
  552. // 使用Laravel模型删除这些不一致的试卷记录
  553. $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
  554. Log::info('清理不一致的试卷记录', [
  555. 'deleted_count' => $deletedCount,
  556. 'deleted_paper_ids' => $deletedPaperIds
  557. ]);
  558. return $deletedCount;
  559. });
  560. } catch (\Exception $e) {
  561. Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
  562. return 0;
  563. }
  564. }
  565. /**
  566. * 修复试卷的题目数量统计
  567. */
  568. public function fixPaperQuestionCounts(): int
  569. {
  570. try {
  571. $fixedCount = 0;
  572. // 使用Laravel模型获取所有试卷
  573. $papers = \App\Models\Paper::all();
  574. foreach ($papers as $paper) {
  575. // 计算实际的题目数量,使用关联关系
  576. $actualQuestionCount = $paper->questions()->count();
  577. // 如果题目数量不匹配,更新试卷
  578. if ($paper->question_count !== $actualQuestionCount) {
  579. $paper->update([
  580. 'question_count' => $actualQuestionCount,
  581. 'updated_at' => now()
  582. ]);
  583. $fixedCount++;
  584. Log::info('修复试卷题目数量', [
  585. 'paper_id' => $paper->paper_id,
  586. 'old_count' => $paper->getOriginal('question_count'),
  587. 'new_count' => $actualQuestionCount
  588. ]);
  589. }
  590. }
  591. Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
  592. return $fixedCount;
  593. } catch (\Exception $e) {
  594. Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
  595. return 0;
  596. }
  597. }
  598. /**
  599. * 获取试卷列表
  600. */
  601. public function listExams(int $page = 1, int $perPage = 20): array
  602. {
  603. try {
  604. $response = Http::timeout(10)
  605. ->get($this->baseUrl . '/exam/list', [
  606. 'page' => $page,
  607. 'per_page' => $perPage
  608. ]);
  609. if ($response->successful()) {
  610. return $response->json();
  611. }
  612. Log::warning('获取试卷列表失败', [
  613. 'status' => $response->status()
  614. ]);
  615. } catch (\Exception $e) {
  616. Log::error('获取试卷列表异常', [
  617. 'error' => $e->getMessage()
  618. ]);
  619. }
  620. return ['data' => [], 'meta' => ['total' => 0]];
  621. }
  622. /**
  623. * 获取试卷详情
  624. */
  625. public function getExamById(string $paperId): ?array
  626. {
  627. try {
  628. $response = Http::timeout(10)
  629. ->get($this->baseUrl . '/exam/' . $paperId);
  630. if ($response->successful()) {
  631. return $response->json();
  632. }
  633. Log::warning('获取试卷详情失败', [
  634. 'paper_id' => $paperId,
  635. 'status' => $response->status()
  636. ]);
  637. } catch (\Exception $e) {
  638. Log::error('获取试卷详情异常', [
  639. 'paper_id' => $paperId,
  640. 'error' => $e->getMessage()
  641. ]);
  642. }
  643. return null;
  644. }
  645. /**
  646. * 导出试卷为PDF
  647. */
  648. public function exportExamToPdf(string $paperId): ?string
  649. {
  650. try {
  651. $response = Http::timeout(60)
  652. ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
  653. if ($response->successful()) {
  654. // 返回PDF文件路径或URL
  655. return $response->json('pdf_url', null);
  656. }
  657. Log::warning('导出PDF失败', [
  658. 'paper_id' => $paperId,
  659. 'status' => $response->status()
  660. ]);
  661. } catch (\Exception $e) {
  662. Log::error('导出PDF异常', [
  663. 'paper_id' => $paperId,
  664. 'error' => $e->getMessage()
  665. ]);
  666. }
  667. return null;
  668. }
  669. /**
  670. * 检查服务健康状态
  671. */
  672. public function checkHealth(): bool
  673. {
  674. try {
  675. $response = Http::timeout(5)
  676. ->get($this->baseUrl . '/health');
  677. return $response->successful();
  678. } catch (\Exception $e) {
  679. Log::error('题库服务健康检查失败', [
  680. 'error' => $e->getMessage()
  681. ]);
  682. return false;
  683. }
  684. }
  685. /**
  686. * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
  687. *
  688. * @param array $questions OCR识别的题目列表
  689. * @param string $gradeLevel 年级
  690. * @param string $subject 科目
  691. * @param int $ocrRecordId OCR记录ID,用于关联
  692. * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
  693. * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
  694. * @return array 任务ID和状态
  695. */
  696. public function generateQuestionsFromOcrAsync(
  697. array $questions,
  698. string $gradeLevel = '高一',
  699. string $subject = '数学',
  700. int $ocrRecordId = null,
  701. string $callbackUrl = null,
  702. string $callbackRouteName = 'api.ocr.callback'
  703. ): array {
  704. try {
  705. // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
  706. if (!$callbackUrl && $ocrRecordId) {
  707. $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
  708. Log::info('动态生成回调URL', [
  709. 'route_name' => $callbackRouteName,
  710. 'generated_url' => $callbackUrl
  711. ]);
  712. }
  713. // 生成唯一的任务ID
  714. $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
  715. // 更新OCR记录状态为生成中
  716. if ($ocrRecordId) {
  717. \DB::table('ocr_question_results')
  718. ->where('ocr_record_id', $ocrRecordId)
  719. ->where('question_bank_id', null) // 只更新未关联的题目
  720. ->update([
  721. 'generation_status' => 'generating',
  722. 'generation_task_id' => $taskId,
  723. 'generation_error' => null
  724. ]);
  725. }
  726. // 启动后台任务(使用Laravel的队列)
  727. if ($ocrRecordId && $callbackUrl) {
  728. // 使用Laravel队列异步处理
  729. $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
  730. } else {
  731. // 如果没有回调URL,使用同步方式
  732. $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
  733. return $response;
  734. }
  735. Log::info('OCR题目生成任务已提交到队列', [
  736. 'task_id' => $taskId,
  737. 'ocr_record_id' => $ocrRecordId,
  738. 'questions_count' => count($questions),
  739. 'callback_url' => $callbackUrl
  740. ]);
  741. return [
  742. 'status' => 'processing',
  743. 'task_id' => $taskId,
  744. 'ocr_record_id' => $ocrRecordId,
  745. 'message' => '题目生成任务已启动,完成后将通过回调通知',
  746. 'estimated_time' => '约' . (count($questions) * 2) . '秒',
  747. 'callback_info' => [
  748. 'will_callback' => !empty($callbackUrl),
  749. 'callback_url' => $callbackUrl
  750. ]
  751. ];
  752. } catch (\Exception $e) {
  753. Log::error('OCR题目生成任务提交异常', [
  754. 'error' => $e->getMessage(),
  755. 'ocr_record_id' => $ocrRecordId
  756. ]);
  757. return [
  758. 'status' => 'error',
  759. 'message' => '任务提交失败: ' . $e->getMessage()
  760. ];
  761. }
  762. }
  763. /**
  764. * 分发OCR生成任务到队列
  765. */
  766. private function dispatchOcrGenerationJob(
  767. int $ocrRecordId,
  768. array $questions,
  769. string $gradeLevel,
  770. string $subject,
  771. string $callbackUrl,
  772. string $taskId
  773. ): void {
  774. try {
  775. // 转换题目数据格式
  776. $formattedQuestions = [];
  777. foreach ($questions as $q) {
  778. $formattedQuestions[] = [
  779. 'id' => $q['id'] ?? uniqid(),
  780. 'content' => $q['content'] ?? ''
  781. ];
  782. }
  783. // 直接调用QuestionBank API的异步端点,提供回调URL
  784. $response = Http::timeout(60)
  785. ->post($this->baseUrl . '/api/questions/generate-from-ocr', [
  786. 'ocr_record_id' => $ocrRecordId,
  787. 'questions' => $formattedQuestions,
  788. 'grade_level' => $gradeLevel,
  789. 'subject' => $subject,
  790. 'callback_url' => $callbackUrl
  791. ]);
  792. if (!$response->successful()) {
  793. Log::error('提交OCR题目生成任务失败', [
  794. 'status' => $response->status(),
  795. 'body' => $response->body(),
  796. 'task_id' => $taskId
  797. ]);
  798. // 发送失败回调
  799. $callbackData = [
  800. 'task_id' => $taskId,
  801. 'ocr_record_id' => $ocrRecordId,
  802. 'status' => 'failed',
  803. 'error' => 'API调用失败: ' . $response->status(),
  804. 'timestamp' => now()->toISOString()
  805. ];
  806. Http::timeout(10)
  807. ->post($callbackUrl, $callbackData);
  808. return;
  809. }
  810. $result = $response->json();
  811. Log::info('OCR题目生成任务已提交到QuestionBank', [
  812. 'task_id' => $taskId,
  813. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  814. 'status' => $result['status'] ?? 'unknown',
  815. 'callback_url' => $callbackUrl
  816. ]);
  817. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  818. // 回调会在题目生成完成后由QuestionBank API主动发送
  819. } catch (\Exception $e) {
  820. Log::error('OCR生成任务处理失败', [
  821. 'task_id' => $taskId,
  822. 'ocr_record_id' => $ocrRecordId,
  823. 'error' => $e->getMessage()
  824. ]);
  825. // 发送异常回调
  826. try {
  827. $callbackData = [
  828. 'task_id' => $taskId,
  829. 'ocr_record_id' => $ocrRecordId,
  830. 'status' => 'failed',
  831. 'error' => $e->getMessage(),
  832. 'timestamp' => now()->toISOString()
  833. ];
  834. Http::timeout(10)
  835. ->post($callbackUrl, $callbackData);
  836. } catch (\Exception $callbackException) {
  837. Log::error('发送异常回调失败', [
  838. 'error' => $callbackException->getMessage()
  839. ]);
  840. }
  841. }
  842. }
  843. /**
  844. * 动态生成回调URL
  845. *
  846. * @param string $routeName 路由名称
  847. * @return string 完整的回调URL
  848. */
  849. private function generateCallbackUrl(string $routeName): string
  850. {
  851. try {
  852. // 获取当前请求的域名
  853. $appUrl = config('app.url', 'http://localhost');
  854. // 如果是在命令行环境中运行,使用配置的域名
  855. if (app()->runningInConsole()) {
  856. $domain = config('services.question_bank.callback_domain', $appUrl);
  857. } else {
  858. $domain = request()->getSchemeAndHttpHost();
  859. }
  860. // 确保domain不为null
  861. $domain = $domain ?? $appUrl;
  862. // 移除末尾的斜杠
  863. $domain = rtrim($domain, '/');
  864. // 生成完整的URL
  865. $callbackUrl = $domain . route($routeName, [], false);
  866. Log::info('生成回调URL', [
  867. 'route_name' => $routeName,
  868. 'domain' => $domain,
  869. 'app_url' => $appUrl,
  870. 'callback_url' => $callbackUrl
  871. ]);
  872. return $callbackUrl;
  873. } catch (\Exception $e) {
  874. // 如果路由生成失败,使用默认URL
  875. Log::warning('路由生成失败,使用默认URL', [
  876. 'route_name' => $routeName,
  877. 'error' => $e->getMessage()
  878. ]);
  879. $fallbackUrl = config('app.url', 'http://localhost');
  880. if ($routeName === 'api.ocr.callback') {
  881. return $fallbackUrl . '/api/ocr-question-callback';
  882. }
  883. return $fallbackUrl;
  884. }
  885. }
  886. /**
  887. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  888. *
  889. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  890. * @param string $gradeLevel 年级
  891. * @param string $subject 科目
  892. * @return array 生成结果
  893. */
  894. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  895. {
  896. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  897. }
  898. /**
  899. * 检查题目生成任务状态
  900. */
  901. public function checkGenerationTaskStatus(string $taskId): array
  902. {
  903. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  904. }
  905. }