QuestionBankService.php 51 KB

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