QuestionBankService.php 51 KB

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