QuestionBankService.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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. protected int $timeout;
  9. protected int $retry;
  10. protected int $retryDelay;
  11. public function __construct()
  12. {
  13. // 从配置文件读取base_url
  14. $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
  15. $this->baseUrl = rtrim($this->baseUrl, '/');
  16. // 如果配置中不包含/api,则添加它
  17. if (!str_ends_with($this->baseUrl, '/api')) {
  18. $this->baseUrl .= '/api';
  19. }
  20. // 读取超时与重试配置
  21. $this->timeout = (int) config('services.question_bank.timeout', 60);
  22. $this->retry = (int) config('services.question_bank.retry', 2);
  23. $this->retryDelay = (int) config('services.question_bank.retry_delay', 500);
  24. }
  25. private function http()
  26. {
  27. return Http::timeout($this->timeout)
  28. ->retry($this->retry, $this->retryDelay);
  29. }
  30. /**
  31. * 从题目内容中提取选项
  32. */
  33. private function extractOptions(string $content): array
  34. {
  35. // 匹配 A. B. C. D. 格式的选项
  36. if (preg_match_all('/([A-D])\.\s*(.+?)(?=[A-D]\.|$)/s', $content, $matches, PREG_SET_ORDER)) {
  37. $options = [];
  38. foreach ($matches as $match) {
  39. $optionText = trim($match[2]);
  40. // 移除末尾的换行和空白
  41. $optionText = preg_replace('/\s+$/', '', $optionText);
  42. $options[] = $optionText;
  43. }
  44. return $options;
  45. }
  46. return [];
  47. }
  48. /**
  49. * 分离题干内容和选项
  50. */
  51. private function separateStemAndOptions(string $content): array
  52. {
  53. // 如果没有选项,直接返回
  54. if (!preg_match('/[A-D]\.\s+/m', $content)) {
  55. return [$content, []];
  56. }
  57. // 提取选项
  58. $options = $this->extractOptions($content);
  59. // 提取题干(选项前的部分)
  60. $stem = preg_replace('/[A-D]\.\s+.+?(?=[A-D]\.|$)/s', '', $content);
  61. $stem = trim($stem);
  62. // 移除末尾的括号或空白
  63. $stem = preg_replace('/()\s*$/', '', $stem);
  64. $stem = trim($stem);
  65. return [$stem, $options];
  66. }
  67. /**
  68. * 获取题目列表
  69. */
  70. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  71. {
  72. try {
  73. $response = $this->http()
  74. ->get($this->baseUrl . '/questions', [
  75. 'page' => $page,
  76. 'per_page' => $perPage,
  77. ...$filters
  78. ]);
  79. if ($response->successful()) {
  80. info("QuestionBankService::listQuestions", [$response->json()]);
  81. return $response->json();
  82. }
  83. Log::warning('题库API调用失败', [
  84. 'status' => $response->status()
  85. ]);
  86. } catch (\Exception $e) {
  87. Log::error('获取题目列表失败', [
  88. 'error' => $e->getMessage()
  89. ]);
  90. }
  91. return ['data' => [], 'meta' => ['total' => 0]];
  92. }
  93. /**
  94. * 获取题目详情
  95. */
  96. public function getQuestion(string $questionCode): ?array
  97. {
  98. try {
  99. $response = $this->http()
  100. ->get($this->baseUrl . "/questions/{$questionCode}");
  101. if ($response->successful()) {
  102. return $response->json();
  103. }
  104. Log::warning('获取题目详情失败', [
  105. 'code' => $questionCode,
  106. 'status' => $response->status()
  107. ]);
  108. } catch (\Exception $e) {
  109. Log::error('获取题目详情异常', [
  110. 'code' => $questionCode,
  111. 'error' => $e->getMessage()
  112. ]);
  113. }
  114. return null;
  115. }
  116. /**
  117. * 更新题目
  118. */
  119. public function updateQuestion(string $questionCode, array $payload): bool
  120. {
  121. try {
  122. $response = Http::timeout(10)
  123. ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
  124. if ($response->successful()) {
  125. return true;
  126. }
  127. Log::warning('更新题目失败', [
  128. 'code' => $questionCode,
  129. 'status' => $response->status(),
  130. 'body' => $response->json(),
  131. ]);
  132. } catch (\Exception $e) {
  133. Log::error('更新题目异常', [
  134. 'code' => $questionCode,
  135. 'error' => $e->getMessage()
  136. ]);
  137. }
  138. return false;
  139. }
  140. /**
  141. * 筛选题目 (支持 kp_codes, skills 等高级筛选)
  142. */
  143. public function filterQuestions(array $params): array
  144. {
  145. try {
  146. $response = Http::timeout(30)
  147. ->get($this->baseUrl . '/questions', $params);
  148. if ($response->successful()) {
  149. info("QuestionBankService::filterQuestions", [$response->json()]);
  150. return $response->json();
  151. }
  152. Log::warning('筛选题目API调用失败', [
  153. 'status' => $response->status(),
  154. 'params' => $params
  155. ]);
  156. } catch (\Exception $e) {
  157. Log::error('筛选题目异常', [
  158. 'error' => $e->getMessage(),
  159. 'params' => $params
  160. ]);
  161. }
  162. return ['data' => []];
  163. }
  164. /**
  165. * 批量获取题目详情(根据题目 ID 列表)
  166. */
  167. public function getQuestionsByIds(array $ids): array
  168. {
  169. if (empty($ids)) {
  170. return ['data' => []];
  171. }
  172. try {
  173. $response = $this->http()
  174. ->get($this->baseUrl . '/questions', [
  175. 'ids' => implode(',', $ids),
  176. ]);
  177. if ($response->successful()) {
  178. return $response->json();
  179. }
  180. Log::warning('批量获取题目失败', [
  181. 'ids' => $ids,
  182. 'status' => $response->status(),
  183. ]);
  184. } catch (\Exception $e) {
  185. Log::error('批量获取题目异常', [
  186. 'ids' => $ids,
  187. 'error' => $e->getMessage(),
  188. ]);
  189. }
  190. return ['data' => []];
  191. }
  192. /**
  193. * 智能生成题目(异步模式)
  194. */
  195. public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
  196. {
  197. try {
  198. // 添加回调 URL
  199. if ($callbackUrl) {
  200. $params['callback_url'] = $callbackUrl;
  201. }
  202. // 注意:这里的请求实际上是同步的,会等待响应
  203. // 真正的异步应该使用 Http::async()
  204. $response = $this->http()
  205. ->post($this->baseUrl . '/ai/generate-intelligent-questions', $params);
  206. if ($response->successful()) {
  207. return $response->json();
  208. }
  209. Log::warning('题目生成API调用失败', [
  210. 'status' => $response->status(),
  211. 'body' => $response->body()
  212. ]);
  213. } catch (\Illuminate\Http\Client\ConnectionException $e) {
  214. // 连接超时或网络错误
  215. Log::error('题目生成连接异常', [
  216. 'error' => $e->getMessage(),
  217. 'message' => '可能的原因:1. AI服务未启动 2. 网络连接问题 3. 服务负载过高'
  218. ]);
  219. return [
  220. 'success' => false,
  221. 'message' => '连接AI服务失败,请检查服务是否正常运行'
  222. ];
  223. } catch (\Exception $e) {
  224. Log::error('题目生成异常', [
  225. 'error' => $e->getMessage(),
  226. 'trace' => $e->getTraceAsString()
  227. ]);
  228. }
  229. return ['success' => false, 'message' => '生成失败'];
  230. }
  231. /**
  232. * 获取任务状态
  233. */
  234. public function getTaskStatus(string $taskId): ?array
  235. {
  236. try {
  237. $response = Http::timeout(10)
  238. ->get($this->baseUrl . '/tasks/' . $taskId);
  239. if ($response->successful()) {
  240. return $response->json();
  241. }
  242. Log::warning('获取任务状态失败', [
  243. 'task_id' => $taskId,
  244. 'status' => $response->status()
  245. ]);
  246. } catch (\Exception $e) {
  247. Log::error('获取任务状态异常', [
  248. 'task_id' => $taskId,
  249. 'error' => $e->getMessage()
  250. ]);
  251. }
  252. return null;
  253. }
  254. /**
  255. * 获取任务列表
  256. */
  257. public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
  258. {
  259. try {
  260. $params = [
  261. 'page' => $page,
  262. 'per_page' => $perPage
  263. ];
  264. if ($status) {
  265. $params['status'] = $status;
  266. }
  267. $response = Http::timeout(10)
  268. ->get($this->baseUrl . '/tasks', $params);
  269. if ($response->successful()) {
  270. return $response->json();
  271. }
  272. Log::warning('获取任务列表失败', [
  273. 'status' => $response->status()
  274. ]);
  275. } catch (\Exception $e) {
  276. Log::error('获取任务列表异常', [
  277. 'error' => $e->getMessage()
  278. ]);
  279. }
  280. return ['data' => [], 'meta' => ['total' => 0]];
  281. }
  282. /**
  283. * 获取题目统计信息
  284. */
  285. public function getStatistics(): array
  286. {
  287. try {
  288. $response = Http::timeout(10)
  289. ->get($this->baseUrl . '/questions/statistics');
  290. if ($response->successful()) {
  291. return $response->json();
  292. }
  293. Log::warning('获取题目统计失败', [
  294. 'status' => $response->status()
  295. ]);
  296. } catch (\Exception $e) {
  297. Log::error('获取题目统计异常', [
  298. 'error' => $e->getMessage()
  299. ]);
  300. }
  301. return [
  302. 'total' => 0,
  303. 'by_difficulty' => [],
  304. 'by_kp' => [],
  305. 'by_source' => []
  306. ];
  307. }
  308. /**
  309. * 根据知识点获取题目
  310. */
  311. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  312. {
  313. try {
  314. $response = Http::timeout(10)
  315. ->get($this->baseUrl . '/questions', [
  316. 'kp_code' => $kpCode,
  317. 'limit' => $limit
  318. ]);
  319. if ($response->successful()) {
  320. return $response->json();
  321. }
  322. } catch (\Exception $e) {
  323. Log::error('根据知识点获取题目失败', [
  324. 'kp_code' => $kpCode,
  325. 'error' => $e->getMessage()
  326. ]);
  327. }
  328. return [];
  329. }
  330. /**
  331. * 删除题目
  332. */
  333. public function deleteQuestion(string $questionCode): bool
  334. {
  335. try {
  336. $response = Http::timeout(10)
  337. ->delete($this->baseUrl . "/questions/{$questionCode}");
  338. // 只有返回204(删除成功)才返回true,404(不存在)返回false
  339. if ($response->status() === 204) {
  340. return true;
  341. }
  342. if ($response->status() === 404) {
  343. Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
  344. return false;
  345. }
  346. return false;
  347. } catch (\Exception $e) {
  348. Log::error('删除题目失败', [
  349. 'question_code' => $questionCode,
  350. 'error' => $e->getMessage()
  351. ]);
  352. return false;
  353. }
  354. }
  355. /**
  356. * 智能选择试卷题目
  357. */
  358. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  359. {
  360. try {
  361. $response = Http::timeout(30)
  362. ->post($this->baseUrl . '/exam/select-questions', [
  363. 'total_questions' => $totalQuestions,
  364. 'filters' => $filters
  365. ]);
  366. if ($response->successful()) {
  367. return $response->json('data', []);
  368. }
  369. Log::warning('智能选题API调用失败', [
  370. 'status' => $response->status()
  371. ]);
  372. } catch (\Exception $e) {
  373. Log::error('智能选题异常', [
  374. 'error' => $e->getMessage()
  375. ]);
  376. }
  377. return [];
  378. }
  379. /**
  380. * 保存试卷到数据库(本地 papers 表)
  381. */
  382. public function saveExamToDatabase(array $examData): ?string
  383. {
  384. // 数据完整性检查
  385. if (empty($examData['questions'])) {
  386. Log::warning('尝试保存没有题目的试卷', [
  387. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  388. 'student_id' => $examData['student_id'] ?? 'unknown'
  389. ]);
  390. return null;
  391. }
  392. try {
  393. // 使用数据库事务确保数据一致性
  394. return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
  395. // 生成试卷ID
  396. $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
  397. Log::info('开始保存试卷到数据库', [
  398. 'paper_id' => $paperId,
  399. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  400. 'question_count' => count($examData['questions'])
  401. ]);
  402. // 使用Laravel模型保存到 papers 表
  403. $paper = \App\Models\Paper::create([
  404. 'paper_id' => $paperId,
  405. 'student_id' => $examData['student_id'] ?? '',
  406. 'teacher_id' => $examData['teacher_id'] ?? '',
  407. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  408. 'paper_type' => 'auto_generated',
  409. 'total_questions' => count($examData['questions']), // 使用实际题目数量
  410. 'total_score' => $examData['total_score'] ?? 0,
  411. 'status' => 'draft',
  412. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  413. ]);
  414. // 获取所有题目的正确答案
  415. $questionBankIds = array_filter(array_map(function($q) {
  416. return $q['id'] ?? $q['question_id'] ?? null;
  417. }, $examData['questions']));
  418. $correctAnswersMap = [];
  419. if (!empty($questionBankIds)) {
  420. Log::info('获取题目正确答案', [
  421. 'paper_id' => $paperId,
  422. 'question_bank_ids' => $questionBankIds
  423. ]);
  424. try {
  425. $response = Http::timeout(10)->post($this->baseUrl . '/questions/batch', [
  426. 'ids' => array_values($questionBankIds)
  427. ]);
  428. if ($response->successful()) {
  429. $questionsDetails = $response->json('data', []);
  430. foreach ($questionsDetails as $detail) {
  431. $correctAnswersMap[$detail['id']] = $detail['answer'] ?? $detail['correct_answer'] ?? '';
  432. }
  433. Log::info('获取到题目正确答案', [
  434. 'paper_id' => $paperId,
  435. 'answers_count' => count($correctAnswersMap)
  436. ]);
  437. }
  438. } catch (\Exception $e) {
  439. Log::warning('获取题目正确答案失败', [
  440. 'paper_id' => $paperId,
  441. 'error' => $e->getMessage()
  442. ]);
  443. }
  444. }
  445. // 准备题目数据
  446. $questionInsertData = [];
  447. foreach ($examData['questions'] as $index => $question) {
  448. // 验证题目基本数据
  449. if (empty($question['stem']) && empty($question['content'])) {
  450. Log::warning('跳过没有内容的题目', [
  451. 'paper_id' => $paperId,
  452. 'question_index' => $index
  453. ]);
  454. continue;
  455. }
  456. // 处理题目内容:分离题干和选项(如果存在)
  457. $rawContent = $question['stem'] ?? $question['content'] ?? '';
  458. list($stem, $options) = $this->separateStemAndOptions($rawContent);
  459. // 将选项以换行符形式附加到题干末尾,方便后续渲染
  460. if (!empty($options)) {
  461. $stemWithOptions = $stem . "\n" . implode("\n", array_map(function($opt, $idx) {
  462. return chr(65 + $idx) . '. ' . $opt;
  463. }, $options, array_keys($options)));
  464. $question['stem'] = $stemWithOptions;
  465. $question['options'] = $options;
  466. } else {
  467. $question['stem'] = $stem;
  468. }
  469. // 处理难度字段:如果是字符串则转换为数字
  470. $difficultyValue = $question['difficulty'] ?? 0.5;
  471. if (is_string($difficultyValue)) {
  472. // 将中文难度转换为数字
  473. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  474. $difficultyValue = 0.3;
  475. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  476. $difficultyValue = 0.6;
  477. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  478. $difficultyValue = 0.9;
  479. } else {
  480. $difficultyValue = 0.5;
  481. }
  482. }
  483. // 确保 knowledge_point 有值
  484. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  485. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  486. $knowledgePoint = $question['kp_code'];
  487. }
  488. // 获取题目类型
  489. $questionType = $question['question_type'] ?? 'answer';
  490. if (!$questionType) {
  491. // 如果没有类型,根据内容推断
  492. $content = $question['stem'] ?? $question['content'] ?? '';
  493. if (is_string($content)) {
  494. // 1. 优先检查填空题(下划线)
  495. if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  496. $questionType = 'fill';
  497. }
  498. // 2. 检查选择题(必须有选项 A. B. C. D.)
  499. elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
  500. if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
  501. $questionType = 'choice';
  502. } else {
  503. // 只有括号没有选项,可能是填空
  504. if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  505. $questionType = 'fill';
  506. } else {
  507. $questionType = 'answer';
  508. }
  509. }
  510. }
  511. // 3. 检查纯括号填空
  512. elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  513. $questionType = 'fill';
  514. }
  515. else {
  516. $questionType = 'answer';
  517. }
  518. } else {
  519. $questionType = 'answer';
  520. }
  521. }
  522. // 获取正确答案
  523. $questionBankId = $question['id'] ?? $question['question_id'] ?? null;
  524. $correctAnswer = $correctAnswersMap[$questionBankId] ?? $question['answer'] ?? $question['correct_answer'] ?? '';
  525. $questionInsertData[] = [
  526. 'paper_id' => $paperId,
  527. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  528. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  529. 'knowledge_point' => $knowledgePoint,
  530. 'question_type' => $questionType,
  531. 'question_text' => $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '',
  532. 'correct_answer' => $correctAnswer, // 保存正确答案
  533. 'solution' => $question['solution'] ?? '', // 保存解题思路
  534. 'difficulty' => $difficultyValue,
  535. 'score' => $question['score'] ?? 5, // 默认5分
  536. 'estimated_time' => $question['estimated_time'] ?? 300,
  537. 'question_number' => $index + 1,
  538. ];
  539. }
  540. // 验证是否有有效的题目数据
  541. if (empty($questionInsertData)) {
  542. Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
  543. throw new \Exception('没有有效的题目数据');
  544. }
  545. // 调试:检查第一个题目的solution字段
  546. if (!empty($questionInsertData)) {
  547. $firstQuestion = $questionInsertData[0];
  548. Log::debug('试卷保存调试 - 第一个题目', [
  549. 'paper_id' => $paperId,
  550. 'question_id' => $firstQuestion['question_id'] ?? '',
  551. 'question_bank_id' => $firstQuestion['question_bank_id'] ?? '',
  552. 'has_solution' => !empty($firstQuestion['solution']),
  553. 'solution_length' => strlen($firstQuestion['solution'] ?? ''),
  554. 'solution_preview' => substr($firstQuestion['solution'] ?? '', 0, 80)
  555. ]);
  556. }
  557. // 使用Laravel模型批量插入题目数据
  558. \App\Models\PaperQuestion::insert($questionInsertData);
  559. // 验证插入结果,使用关联关系
  560. $insertedQuestionCount = $paper->questions()->count();
  561. if ($insertedQuestionCount !== count($questionInsertData)) {
  562. throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
  563. }
  564. Log::info('试卷保存成功', [
  565. 'paper_id' => $paperId,
  566. 'expected_questions' => count($questionInsertData),
  567. 'actual_questions' => $insertedQuestionCount,
  568. 'paper_name' => $paper->paper_name
  569. ]);
  570. return $paperId;
  571. });
  572. } catch (\Exception $e) {
  573. Log::error('保存试卷到数据库失败', [
  574. 'error' => $e->getMessage(),
  575. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  576. 'student_id' => $examData['student_id'] ?? 'unknown',
  577. 'question_count' => count($examData['questions'] ?? []),
  578. 'trace' => $e->getTraceAsString()
  579. ]);
  580. return null;
  581. }
  582. }
  583. /**
  584. * 检查数据完整性 - 发现没有题目的试卷
  585. */
  586. public function checkDataIntegrity(): array
  587. {
  588. try {
  589. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  590. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  591. ->whereDoesntHave('questions')
  592. ->get();
  593. Log::warning('发现数据不一致的试卷', [
  594. 'count' => $inconsistentPapers->count(),
  595. 'papers' => $inconsistentPapers->map(function($paper) {
  596. return [
  597. 'paper_id' => $paper->paper_id,
  598. 'paper_name' => $paper->paper_name,
  599. 'expected_questions' => $paper->question_count,
  600. 'student_id' => $paper->student_id,
  601. 'created_at' => $paper->created_at
  602. ];
  603. })->toArray()
  604. ]);
  605. return [
  606. 'inconsistent_count' => $inconsistentPapers->count(),
  607. 'papers' => $inconsistentPapers->toArray()
  608. ];
  609. } catch (\Exception $e) {
  610. Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
  611. return ['inconsistent_count' => 0, 'papers' => []];
  612. }
  613. }
  614. /**
  615. * 清理没有题目的试卷记录
  616. */
  617. public function cleanupInconsistentPapers(): int
  618. {
  619. try {
  620. return \Illuminate\Support\Facades\DB::transaction(function () {
  621. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  622. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  623. ->whereDoesntHave('questions')
  624. ->get();
  625. if ($inconsistentPapers->isEmpty()) {
  626. return 0;
  627. }
  628. // 获取要删除的试卷ID列表
  629. $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
  630. // 使用Laravel模型删除这些不一致的试卷记录
  631. $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
  632. Log::info('清理不一致的试卷记录', [
  633. 'deleted_count' => $deletedCount,
  634. 'deleted_paper_ids' => $deletedPaperIds
  635. ]);
  636. return $deletedCount;
  637. });
  638. } catch (\Exception $e) {
  639. Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
  640. return 0;
  641. }
  642. }
  643. /**
  644. * 修复试卷的题目数量统计
  645. */
  646. public function fixPaperQuestionCounts(): int
  647. {
  648. try {
  649. $fixedCount = 0;
  650. // 使用Laravel模型获取所有试卷
  651. $papers = \App\Models\Paper::all();
  652. foreach ($papers as $paper) {
  653. // 计算实际的题目数量,使用关联关系
  654. $actualQuestionCount = $paper->questions()->count();
  655. // 如果题目数量不匹配,更新试卷
  656. if ($paper->question_count !== $actualQuestionCount) {
  657. $paper->update([
  658. 'question_count' => $actualQuestionCount,
  659. 'updated_at' => now()
  660. ]);
  661. $fixedCount++;
  662. Log::info('修复试卷题目数量', [
  663. 'paper_id' => $paper->paper_id,
  664. 'old_count' => $paper->getOriginal('question_count'),
  665. 'new_count' => $actualQuestionCount
  666. ]);
  667. }
  668. }
  669. Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
  670. return $fixedCount;
  671. } catch (\Exception $e) {
  672. Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
  673. return 0;
  674. }
  675. }
  676. /**
  677. * 获取试卷列表
  678. */
  679. public function listExams(int $page = 1, int $perPage = 20): array
  680. {
  681. try {
  682. $response = Http::timeout(10)
  683. ->get($this->baseUrl . '/exam/list', [
  684. 'page' => $page,
  685. 'per_page' => $perPage
  686. ]);
  687. if ($response->successful()) {
  688. return $response->json();
  689. }
  690. Log::warning('获取试卷列表失败', [
  691. 'status' => $response->status()
  692. ]);
  693. } catch (\Exception $e) {
  694. Log::error('获取试卷列表异常', [
  695. 'error' => $e->getMessage()
  696. ]);
  697. }
  698. return ['data' => [], 'meta' => ['total' => 0]];
  699. }
  700. /**
  701. * 获取试卷详情
  702. */
  703. public function getExamById(string $paperId): ?array
  704. {
  705. try {
  706. $response = Http::timeout(10)
  707. ->get($this->baseUrl . '/exam/' . $paperId);
  708. if ($response->successful()) {
  709. return $response->json();
  710. }
  711. Log::warning('获取试卷详情失败', [
  712. 'paper_id' => $paperId,
  713. 'status' => $response->status()
  714. ]);
  715. } catch (\Exception $e) {
  716. Log::error('获取试卷详情异常', [
  717. 'paper_id' => $paperId,
  718. 'error' => $e->getMessage()
  719. ]);
  720. }
  721. return null;
  722. }
  723. /**
  724. * 导出试卷为PDF
  725. */
  726. public function exportExamToPdf(string $paperId): ?string
  727. {
  728. try {
  729. $response = Http::timeout(60)
  730. ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
  731. if ($response->successful()) {
  732. // 返回PDF文件路径或URL
  733. return $response->json('pdf_url', null);
  734. }
  735. Log::warning('导出PDF失败', [
  736. 'paper_id' => $paperId,
  737. 'status' => $response->status()
  738. ]);
  739. } catch (\Exception $e) {
  740. Log::error('导出PDF异常', [
  741. 'paper_id' => $paperId,
  742. 'error' => $e->getMessage()
  743. ]);
  744. }
  745. return null;
  746. }
  747. /**
  748. * 检查服务健康状态
  749. */
  750. public function checkHealth(): bool
  751. {
  752. try {
  753. // 健康检查使用不带/api的路径
  754. $healthUrl = str_replace('/api', '', $this->baseUrl) . '/health';
  755. $response = Http::timeout(5)
  756. ->get($healthUrl);
  757. return $response->successful();
  758. } catch (\Exception $e) {
  759. Log::error('题库服务健康检查失败', [
  760. 'error' => $e->getMessage()
  761. ]);
  762. return false;
  763. }
  764. }
  765. /**
  766. * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
  767. *
  768. * @param array $questions OCR识别的题目列表
  769. * @param string $gradeLevel 年级
  770. * @param string $subject 科目
  771. * @param int $ocrRecordId OCR记录ID,用于关联
  772. * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
  773. * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
  774. * @return array 任务ID和状态
  775. */
  776. public function generateQuestionsFromOcrAsync(
  777. array $questions,
  778. string $gradeLevel = '高一',
  779. string $subject = '数学',
  780. int $ocrRecordId = null,
  781. string $callbackUrl = null,
  782. string $callbackRouteName = 'api.ocr.callback'
  783. ): array {
  784. try {
  785. // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
  786. if (!$callbackUrl && $ocrRecordId) {
  787. $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
  788. Log::info('动态生成回调URL', [
  789. 'route_name' => $callbackRouteName,
  790. 'generated_url' => $callbackUrl
  791. ]);
  792. }
  793. // 生成唯一的任务ID
  794. $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
  795. // 更新OCR记录状态为生成中
  796. if ($ocrRecordId) {
  797. \DB::table('ocr_question_results')
  798. ->where('ocr_record_id', $ocrRecordId)
  799. ->where('question_bank_id', null) // 只更新未关联的题目
  800. ->update([
  801. 'generation_status' => 'generating',
  802. 'generation_task_id' => $taskId,
  803. 'generation_error' => null
  804. ]);
  805. }
  806. // 启动后台任务(使用Laravel的队列)
  807. if ($ocrRecordId && $callbackUrl) {
  808. // 使用Laravel队列异步处理
  809. $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
  810. } else {
  811. // 如果没有回调URL,使用同步方式
  812. $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
  813. return $response;
  814. }
  815. Log::info('OCR题目生成任务已提交到队列', [
  816. 'task_id' => $taskId,
  817. 'ocr_record_id' => $ocrRecordId,
  818. 'questions_count' => count($questions),
  819. 'callback_url' => $callbackUrl
  820. ]);
  821. return [
  822. 'status' => 'processing',
  823. 'task_id' => $taskId,
  824. 'ocr_record_id' => $ocrRecordId,
  825. 'message' => '题目生成任务已启动,完成后将通过回调通知',
  826. 'estimated_time' => '约' . (count($questions) * 2) . '秒',
  827. 'callback_info' => [
  828. 'will_callback' => !empty($callbackUrl),
  829. 'callback_url' => $callbackUrl
  830. ]
  831. ];
  832. } catch (\Exception $e) {
  833. Log::error('OCR题目生成任务提交异常', [
  834. 'error' => $e->getMessage(),
  835. 'ocr_record_id' => $ocrRecordId
  836. ]);
  837. return [
  838. 'status' => 'error',
  839. 'message' => '任务提交失败: ' . $e->getMessage()
  840. ];
  841. }
  842. }
  843. /**
  844. * 分发OCR生成任务到队列
  845. */
  846. private function dispatchOcrGenerationJob(
  847. int $ocrRecordId,
  848. array $questions,
  849. string $gradeLevel,
  850. string $subject,
  851. string $callbackUrl,
  852. string $taskId
  853. ): void {
  854. try {
  855. // 转换题目数据格式
  856. $formattedQuestions = [];
  857. foreach ($questions as $q) {
  858. $formattedQuestions[] = [
  859. 'id' => $q['id'] ?? uniqid(),
  860. 'content' => $q['content'] ?? ''
  861. ];
  862. }
  863. // 直接调用QuestionBank API的异步端点,提供回调URL
  864. // 注意: baseUrl 已经包含 /api,所以这里只需要 /ocr/questions/generate-from-ocr
  865. $response = Http::timeout(60)
  866. ->post($this->baseUrl . '/ocr/questions/generate-from-ocr', [
  867. 'ocr_record_id' => $ocrRecordId,
  868. 'questions' => $formattedQuestions,
  869. 'grade_level' => $gradeLevel,
  870. 'subject' => $subject,
  871. 'callback_url' => $callbackUrl
  872. ]);
  873. if (!$response->successful()) {
  874. Log::error('提交OCR题目生成任务失败', [
  875. 'status' => $response->status(),
  876. 'body' => $response->body(),
  877. 'task_id' => $taskId
  878. ]);
  879. // 发送失败回调
  880. $callbackData = [
  881. 'task_id' => $taskId,
  882. 'ocr_record_id' => $ocrRecordId,
  883. 'status' => 'failed',
  884. 'error' => 'API调用失败: ' . $response->status(),
  885. 'timestamp' => now()->toISOString()
  886. ];
  887. Http::timeout(10)
  888. ->post($callbackUrl, $callbackData);
  889. return;
  890. }
  891. $result = $response->json();
  892. Log::info('OCR题目生成任务已提交到QuestionBank', [
  893. 'task_id' => $taskId,
  894. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  895. 'status' => $result['status'] ?? 'unknown',
  896. 'callback_url' => $callbackUrl
  897. ]);
  898. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  899. // 回调会在题目生成完成后由QuestionBank API主动发送
  900. } catch (\Exception $e) {
  901. Log::error('OCR生成任务处理失败', [
  902. 'task_id' => $taskId,
  903. 'ocr_record_id' => $ocrRecordId,
  904. 'error' => $e->getMessage()
  905. ]);
  906. // 发送异常回调
  907. try {
  908. $callbackData = [
  909. 'task_id' => $taskId,
  910. 'ocr_record_id' => $ocrRecordId,
  911. 'status' => 'failed',
  912. 'error' => $e->getMessage(),
  913. 'timestamp' => now()->toISOString()
  914. ];
  915. Http::timeout(10)
  916. ->post($callbackUrl, $callbackData);
  917. } catch (\Exception $callbackException) {
  918. Log::error('发送异常回调失败', [
  919. 'error' => $callbackException->getMessage()
  920. ]);
  921. }
  922. }
  923. }
  924. /**
  925. * 动态生成回调URL
  926. *
  927. * @param string $routeName 路由名称
  928. * @return string 完整的回调URL
  929. */
  930. private function generateCallbackUrl(string $routeName): string
  931. {
  932. try {
  933. // 获取当前请求的域名
  934. $appUrl = config('app.url', 'http://localhost');
  935. // 如果是在命令行环境中运行,使用配置的域名
  936. if (app()->runningInConsole()) {
  937. $domain = config('services.question_bank.callback_domain', $appUrl);
  938. } else {
  939. $domain = request()->getSchemeAndHttpHost();
  940. }
  941. // 确保domain不为null
  942. $domain = $domain ?? $appUrl;
  943. // 移除末尾的斜杠
  944. $domain = rtrim($domain, '/');
  945. // 生成完整的URL
  946. $callbackUrl = $domain . route($routeName, [], false);
  947. Log::info('生成回调URL', [
  948. 'route_name' => $routeName,
  949. 'domain' => $domain,
  950. 'app_url' => $appUrl,
  951. 'callback_url' => $callbackUrl
  952. ]);
  953. return $callbackUrl;
  954. } catch (\Exception $e) {
  955. // 如果路由生成失败,使用默认URL
  956. Log::warning('路由生成失败,使用默认URL', [
  957. 'route_name' => $routeName,
  958. 'error' => $e->getMessage()
  959. ]);
  960. $fallbackUrl = config('app.url', 'http://localhost');
  961. if ($routeName === 'api.ocr.callback') {
  962. return $fallbackUrl . '/api/ocr-question-callback';
  963. }
  964. return $fallbackUrl;
  965. }
  966. }
  967. /**
  968. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  969. *
  970. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  971. * @param string $gradeLevel 年级
  972. * @param string $subject 科目
  973. * @return array 生成结果
  974. */
  975. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  976. {
  977. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  978. }
  979. /**
  980. * 检查题目生成任务状态
  981. */
  982. public function checkGenerationTaskStatus(string $taskId): array
  983. {
  984. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  985. }
  986. /**
  987. * 获取知识点题目统计信息
  988. * 根据知识点代码,统计该知识点及其子知识点和技能点的题目数量
  989. */
  990. public function getKnowledgePointStatistics(?string $kpCode = null): array
  991. {
  992. try {
  993. // 获取知识图谱数据和题目统计数据
  994. $knowledgeGraph = $this->getKnowledgeGraph();
  995. $nodes = $knowledgeGraph['nodes'] ?? [];
  996. $edges = $knowledgeGraph['edges'] ?? [];
  997. $questionStats = $this->getQuestionsStatisticsFromApi();
  998. // 构建知识点索引
  999. $nodeMap = [];
  1000. foreach ($nodes as $node) {
  1001. if (!empty($node['kp_code'])) {
  1002. $nodeMap[$node['kp_code']] = $node;
  1003. }
  1004. }
  1005. // 构建子知识点关系(从edges中提取)
  1006. $childrenMap = [];
  1007. $parentMap = [];
  1008. foreach ($edges as $edge) {
  1009. $source = $edge['source'] ?? '';
  1010. $target = $edge['target'] ?? '';
  1011. $direction = $edge['relation_direction'] ?? '';
  1012. if (!empty($source) && !empty($target)) {
  1013. if ($direction === 'DOWNSTREAM') {
  1014. $childrenMap[$source][] = $target;
  1015. $parentMap[$target] = $source;
  1016. }
  1017. }
  1018. }
  1019. // 构建技能点统计
  1020. $skillStats = [];
  1021. foreach ($questionStats as $stat) {
  1022. $code = $stat['kp_code'] ?? '';
  1023. $skills = $stat['skills_list'] ?? [];
  1024. if (!empty($code)) {
  1025. foreach ($skills as $skillCode) {
  1026. if (!empty($skillCode)) {
  1027. if (!isset($skillStats[$code])) {
  1028. $skillStats[$code] = [];
  1029. }
  1030. if (!isset($skillStats[$code][$skillCode])) {
  1031. $skillStats[$code][$skillCode] = 0;
  1032. }
  1033. $skillStats[$code][$skillCode]++;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. // 如果指定了特定知识点,只返回该知识点的统计
  1039. if ($kpCode && isset($nodeMap[$kpCode])) {
  1040. return $this->buildKnowledgePointStats($kpCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1041. }
  1042. // 否则返回所有顶级知识点的统计
  1043. $result = [];
  1044. $rootNodes = [];
  1045. // 找出根节点(没有父节点的节点)
  1046. foreach ($nodes as $node) {
  1047. $code = $node['kp_code'] ?? '';
  1048. if (!empty($code) && !isset($parentMap[$code])) {
  1049. $rootNodes[] = $code;
  1050. }
  1051. }
  1052. foreach ($rootNodes as $rootCode) {
  1053. $result[] = $this->buildKnowledgePointStats($rootCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1054. }
  1055. // 按题目总数排序
  1056. usort($result, function($a, $b) {
  1057. return ($b['total_questions'] ?? 0) <=> ($a['total_questions'] ?? 0);
  1058. });
  1059. return $result;
  1060. } catch (\Exception $e) {
  1061. Log::error('获取知识点统计失败', [
  1062. 'kp_code' => $kpCode,
  1063. 'error' => $e->getMessage()
  1064. ]);
  1065. return [];
  1066. }
  1067. }
  1068. /**
  1069. * 获取知识图谱数据
  1070. */
  1071. private function getKnowledgeGraph(): array
  1072. {
  1073. try {
  1074. $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');
  1075. $response = Http::timeout(10)
  1076. ->get($knowledgeApiBase . '/graph/export');
  1077. if ($response->successful()) {
  1078. return $response->json();
  1079. }
  1080. } catch (\Exception $e) {
  1081. Log::error('获取知识图谱失败', ['error' => $e->getMessage()]);
  1082. }
  1083. return ['nodes' => [], 'edges' => []];
  1084. }
  1085. /**
  1086. * 从 API 获取题目统计
  1087. */
  1088. private function getQuestionsStatisticsFromApi(): array
  1089. {
  1090. try {
  1091. // 调用题库 API 获取统计数据
  1092. $response = Http::timeout(30)
  1093. ->get($this->baseUrl . '/questions/statistics');
  1094. if ($response->successful()) {
  1095. $data = $response->json();
  1096. return $data['by_kp'] ?? [];
  1097. }
  1098. Log::warning('获取题目统计API失败', [
  1099. 'status' => $response->status(),
  1100. 'url' => $this->baseUrl . '/questions/statistics'
  1101. ]);
  1102. } catch (\Exception $e) {
  1103. Log::error('获取题目统计异常', [
  1104. 'error' => $e->getMessage(),
  1105. 'url' => $this->baseUrl . '/questions/statistics'
  1106. ]);
  1107. }
  1108. return [];
  1109. }
  1110. /**
  1111. * 构建单个知识点的统计信息
  1112. */
  1113. private function buildKnowledgePointStats(
  1114. string $kpCode,
  1115. array $nodeMap,
  1116. array $childrenMap,
  1117. array $questionStats,
  1118. array $skillStats
  1119. ): array {
  1120. $node = $nodeMap[$kpCode] ?? null;
  1121. if (!$node) {
  1122. return [];
  1123. }
  1124. // 获取直接子知识点
  1125. $children = $childrenMap[$kpCode] ?? [];
  1126. $directQuestionCount = 0;
  1127. // 查找当前知识点的题目数
  1128. foreach ($questionStats as $stat) {
  1129. if ($stat['kp_code'] === $kpCode) {
  1130. $directQuestionCount = $stat['question_count'] ?? 0;
  1131. break;
  1132. }
  1133. }
  1134. // 计算子知识点统计
  1135. $childrenStats = [];
  1136. foreach ($children as $childCode) {
  1137. $childStats = $this->buildKnowledgePointStats($childCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1138. if (!empty($childStats)) {
  1139. $childrenStats[] = $childStats;
  1140. }
  1141. }
  1142. // 计算子知识点题目总数
  1143. $childrenQuestionCount = 0;
  1144. foreach ($childrenStats as $child) {
  1145. $childrenQuestionCount += $child['total_questions'] ?? 0;
  1146. }
  1147. // 获取当前知识点的技能点统计
  1148. $skillsCount = 0;
  1149. if (isset($skillStats[$kpCode])) {
  1150. $skillsCount = array_sum($skillStats[$kpCode]);
  1151. }
  1152. return [
  1153. 'kp_code' => $kpCode,
  1154. 'cn_name' => $node['cn_name'] ?? $kpCode,
  1155. 'en_name' => $node['en_name'] ?? '',
  1156. 'total_questions' => $directQuestionCount + $childrenQuestionCount,
  1157. 'direct_questions' => $directQuestionCount,
  1158. 'children_questions' => $childrenQuestionCount,
  1159. 'children' => $childrenStats,
  1160. 'skills_count' => count($skillStats[$kpCode] ?? []),
  1161. 'skills_total_questions' => $skillsCount,
  1162. 'skills' => array_map(function($skillCode, $count) use ($kpCode) {
  1163. return [
  1164. 'kp_code' => $kpCode,
  1165. 'skill_code' => $skillCode,
  1166. 'question_count' => $count
  1167. ];
  1168. }, array_keys($skillStats[$kpCode] ?? []), array_values($skillStats[$kpCode] ?? []))
  1169. ];
  1170. }
  1171. /**
  1172. * 获取所有试卷列表
  1173. */
  1174. public function getAllPapers(): array
  1175. {
  1176. try {
  1177. $response = Http::timeout(10)
  1178. ->get($this->baseUrl . '/papers');
  1179. if ($response->successful()) {
  1180. return $response->json('data', []);
  1181. }
  1182. Log::warning('获取试卷列表失败', [
  1183. 'status' => $response->status(),
  1184. 'response' => $response->body(),
  1185. ]);
  1186. return [];
  1187. } catch (\Exception $e) {
  1188. Log::error('获取试卷列表异常', [
  1189. 'error' => $e->getMessage(),
  1190. ]);
  1191. return [];
  1192. }
  1193. }
  1194. /**
  1195. * 获取指定试卷的题目
  1196. */
  1197. public function getPaperQuestions(string $paperId): array
  1198. {
  1199. try {
  1200. $response = Http::timeout(10)
  1201. ->get($this->baseUrl . '/papers/' . $paperId . '/questions');
  1202. if ($response->successful()) {
  1203. return $response->json('data', []);
  1204. }
  1205. Log::warning('获取试卷题目失败', [
  1206. 'paper_id' => $paperId,
  1207. 'status' => $response->status(),
  1208. 'response' => $response->body(),
  1209. ]);
  1210. return [];
  1211. } catch (\Exception $e) {
  1212. Log::error('获取试卷题目异常', [
  1213. 'paper_id' => $paperId,
  1214. 'error' => $e->getMessage(),
  1215. ]);
  1216. return [];
  1217. }
  1218. }
  1219. }