QuestionBankService.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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/api'));
  15. $this->baseUrl = rtrim($this->baseUrl, '/');
  16. // 确保 baseUrl 以 /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. $logFile = __DIR__ . '/../../../../select_questions.log';
  361. $startTime = microtime(true);
  362. try {
  363. $requestData = [
  364. 'total_questions' => $totalQuestions,
  365. 'filters' => $filters
  366. ];
  367. $logMsg = "=== " . date('Y-m-d H:i:s') . " ===\n";
  368. $logMsg .= "开始调用 selectQuestionsForExam\n";
  369. $logMsg .= "baseUrl: " . $this->baseUrl . "\n";
  370. $logMsg .= "totalQuestions: $totalQuestions\n";
  371. $logMsg .= "filters: " . json_encode($filters) . "\n\n";
  372. file_put_contents($logFile, $logMsg, FILE_APPEND);
  373. $response = Http::timeout(30)
  374. ->post($this->baseUrl . '/exam/select-questions', $requestData);
  375. $logMsg = "API响应:\n";
  376. $logMsg .= " status: " . $response->status() . "\n";
  377. $logMsg .= " successful: " . ($response->successful() ? 'true' : 'false') . "\n";
  378. $logMsg .= " body: " . $response->body() . "\n\n";
  379. file_put_contents($logFile, $logMsg, FILE_APPEND);
  380. if ($response->successful()) {
  381. $data = $response->json('data', []);
  382. $logMsg = "成功解析JSON:\n";
  383. $logMsg .= " data字段题目数量: " . count($data) . "\n";
  384. $logMsg .= " 耗时: " . round((microtime(true) - $startTime) * 1000, 2) . "ms\n\n";
  385. file_put_contents($logFile, $logMsg, FILE_APPEND);
  386. return $data;
  387. }
  388. $logMsg = "API调用失败! 状态码: " . $response->status() . "\n";
  389. $logMsg .= "响应内容: " . $response->body() . "\n\n";
  390. file_put_contents($logFile, $logMsg, FILE_APPEND);
  391. } catch (\Exception $e) {
  392. $logMsg = "异常: " . $e->getMessage() . "\n";
  393. $logMsg .= "堆栈: " . $e->getTraceAsString() . "\n\n";
  394. file_put_contents($logFile, $logMsg, FILE_APPEND);
  395. }
  396. $logMsg = "返回空数组\n";
  397. $logMsg .= "=== 结束 ===\n\n";
  398. file_put_contents($logFile, $logMsg, FILE_APPEND);
  399. return [];
  400. }
  401. /**
  402. * 保存试卷到数据库(本地 papers 表)
  403. */
  404. public function saveExamToDatabase(array $examData): ?string
  405. {
  406. $logFile = __DIR__ . '/../../../../save_exam.log';
  407. $logMsg = "=== " . date('Y-m-d H:i:s') . " ===\n";
  408. $logMsg .= "saveExamToDatabase 被调用\n";
  409. $logMsg .= "questions_count: " . count($examData['questions'] ?? []) . "\n";
  410. $logMsg .= "paper_name: " . ($examData['paper_name'] ?? 'N/A') . "\n";
  411. $logMsg .= "student_id: " . ($examData['student_id'] ?? 'N/A') . "\n";
  412. if (!empty($examData['questions'])) {
  413. $logMsg .= "first_question_id: " . ($examData['questions'][0]['id'] ?? 'N/A') . "\n";
  414. }
  415. file_put_contents($logFile, $logMsg, FILE_APPEND);
  416. // 数据完整性检查
  417. if (empty($examData['questions'])) {
  418. $logMsg = "❌ 题目为空,返回null!\n";
  419. $logMsg .= "这是导致生成demo ID的原因!\n\n";
  420. file_put_contents($logFile, $logMsg, FILE_APPEND);
  421. return null;
  422. }
  423. try {
  424. // 使用数据库事务确保数据一致性
  425. return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
  426. // 生成12位唯一数字ID(时间戳后8位 + 4位随机数)
  427. $timestamp = substr((string)time(), -8); // 取时间戳后8位
  428. $random = str_pad((string)random_int(0, 9999), 4, '0', STR_PAD_LEFT); // 4位随机数
  429. $uniqueId = $timestamp . $random; // 12位唯一数字
  430. $paperId = 'paper_' . $uniqueId;
  431. Log::info('开始保存试卷到数据库', [
  432. 'paper_id' => $paperId,
  433. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  434. 'question_count' => count($examData['questions'])
  435. ]);
  436. // 使用Laravel模型保存到 papers 表
  437. $paper = \App\Models\Paper::create([
  438. 'paper_id' => $paperId,
  439. 'student_id' => $examData['student_id'] ?? '',
  440. 'teacher_id' => $examData['teacher_id'] ?? '',
  441. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  442. 'paper_type' => 'auto_generated',
  443. 'total_questions' => count($examData['questions']), // 使用实际题目数量
  444. 'total_score' => $examData['total_score'] ?? 0,
  445. 'status' => 'draft',
  446. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  447. ]);
  448. // 获取所有题目的正确答案
  449. $questionBankIds = array_filter(array_map(function($q) {
  450. return $q['id'] ?? $q['question_id'] ?? null;
  451. }, $examData['questions']));
  452. $correctAnswersMap = [];
  453. if (!empty($questionBankIds)) {
  454. Log::info('获取题目正确答案', [
  455. 'paper_id' => $paperId,
  456. 'question_bank_ids' => $questionBankIds
  457. ]);
  458. try {
  459. $response = Http::timeout(10)->post($this->baseUrl . '/questions/batch', [
  460. 'ids' => array_values($questionBankIds)
  461. ]);
  462. if ($response->successful()) {
  463. $questionsDetails = $response->json('data', []);
  464. foreach ($questionsDetails as $detail) {
  465. $correctAnswersMap[$detail['id']] = $detail['answer'] ?? $detail['correct_answer'] ?? '';
  466. }
  467. Log::info('获取到题目正确答案', [
  468. 'paper_id' => $paperId,
  469. 'answers_count' => count($correctAnswersMap)
  470. ]);
  471. }
  472. } catch (\Exception $e) {
  473. Log::warning('获取题目正确答案失败', [
  474. 'paper_id' => $paperId,
  475. 'error' => $e->getMessage()
  476. ]);
  477. }
  478. }
  479. // 准备题目数据
  480. $questionInsertData = [];
  481. foreach ($examData['questions'] as $index => $question) {
  482. // 验证题目基本数据
  483. if (empty($question['stem']) && empty($question['content'])) {
  484. Log::warning('跳过没有内容的题目', [
  485. 'paper_id' => $paperId,
  486. 'question_index' => $index
  487. ]);
  488. continue;
  489. }
  490. // 处理题目内容:分离题干和选项(如果存在)
  491. $rawContent = $question['stem'] ?? $question['content'] ?? '';
  492. list($stem, $options) = $this->separateStemAndOptions($rawContent);
  493. // 将选项以换行符形式附加到题干末尾,方便后续渲染
  494. if (!empty($options)) {
  495. $stemWithOptions = $stem . "\n" . implode("\n", array_map(function($opt, $idx) {
  496. return chr(65 + $idx) . '. ' . $opt;
  497. }, $options, array_keys($options)));
  498. $question['stem'] = $stemWithOptions;
  499. $question['options'] = $options;
  500. } else {
  501. $question['stem'] = $stem;
  502. }
  503. // 处理难度字段:如果是字符串则转换为数字
  504. $difficultyValue = $question['difficulty'] ?? 0.5;
  505. if (is_string($difficultyValue)) {
  506. // 将中文难度转换为数字
  507. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  508. $difficultyValue = 0.3;
  509. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  510. $difficultyValue = 0.6;
  511. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  512. $difficultyValue = 0.9;
  513. } else {
  514. $difficultyValue = 0.5;
  515. }
  516. }
  517. // 确保 knowledge_point 有值
  518. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  519. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  520. $knowledgePoint = $question['kp_code'];
  521. }
  522. // 获取题目类型
  523. $questionType = $question['question_type'] ?? 'answer';
  524. if (!$questionType) {
  525. // 如果没有类型,根据内容推断
  526. $content = $question['stem'] ?? $question['content'] ?? '';
  527. if (is_string($content)) {
  528. // 1. 优先检查填空题(下划线)
  529. if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  530. $questionType = 'fill';
  531. }
  532. // 2. 检查选择题(必须有选项 A. B. C. D.)
  533. elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
  534. if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
  535. $questionType = 'choice';
  536. } else {
  537. // 只有括号没有选项,可能是填空
  538. if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  539. $questionType = 'fill';
  540. } else {
  541. $questionType = 'answer';
  542. }
  543. }
  544. }
  545. // 3. 检查纯括号填空
  546. elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  547. $questionType = 'fill';
  548. }
  549. else {
  550. $questionType = 'answer';
  551. }
  552. } else {
  553. $questionType = 'answer';
  554. }
  555. }
  556. // 获取正确答案
  557. $questionBankId = $question['id'] ?? $question['question_id'] ?? null;
  558. $correctAnswer = $correctAnswersMap[$questionBankId] ?? $question['answer'] ?? $question['correct_answer'] ?? '';
  559. $questionInsertData[] = [
  560. 'paper_id' => $paperId,
  561. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  562. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  563. 'knowledge_point' => $knowledgePoint,
  564. 'question_type' => $questionType,
  565. 'question_text' => is_array($question['stem'] ?? null) ? json_encode($question['stem'], JSON_UNESCAPED_UNICODE) : ($question['stem'] ?? $question['content'] ?? $question['question_text'] ?? ''),
  566. 'correct_answer' => is_array($correctAnswer) ? json_encode($correctAnswer, JSON_UNESCAPED_UNICODE) : $correctAnswer, // 保存正确答案
  567. 'solution' => is_array($question['solution'] ?? null) ? json_encode($question['solution'], JSON_UNESCAPED_UNICODE) : ($question['solution'] ?? ''), // 保存解题思路
  568. 'difficulty' => $difficultyValue,
  569. 'score' => $question['score'] ?? 5, // 默认5分
  570. 'estimated_time' => $question['estimated_time'] ?? 300,
  571. 'question_number' => $index + 1,
  572. ];
  573. }
  574. // 验证是否有有效的题目数据
  575. if (empty($questionInsertData)) {
  576. Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
  577. throw new \Exception('没有有效的题目数据');
  578. }
  579. // 调试:检查第一个题目的solution字段
  580. if (!empty($questionInsertData)) {
  581. $firstQuestion = $questionInsertData[0];
  582. Log::debug('试卷保存调试 - 第一个题目', [
  583. 'paper_id' => $paperId,
  584. 'question_id' => $firstQuestion['question_id'] ?? '',
  585. 'question_bank_id' => $firstQuestion['question_bank_id'] ?? '',
  586. 'has_solution' => !empty($firstQuestion['solution']),
  587. 'solution_length' => strlen($firstQuestion['solution'] ?? ''),
  588. 'solution_preview' => substr($firstQuestion['solution'] ?? '', 0, 80)
  589. ]);
  590. }
  591. // 使用Laravel模型批量插入题目数据
  592. \App\Models\PaperQuestion::insert($questionInsertData);
  593. // 验证插入结果,使用关联关系
  594. $insertedQuestionCount = $paper->questions()->count();
  595. if ($insertedQuestionCount !== count($questionInsertData)) {
  596. throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
  597. }
  598. Log::info('试卷保存成功', [
  599. 'paper_id' => $paperId,
  600. 'expected_questions' => count($questionInsertData),
  601. 'actual_questions' => $insertedQuestionCount,
  602. 'paper_name' => $paper->paper_name
  603. ]);
  604. return $paperId;
  605. });
  606. } catch (\Exception $e) {
  607. Log::error('保存试卷到数据库失败', [
  608. 'error' => $e->getMessage(),
  609. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  610. 'student_id' => $examData['student_id'] ?? 'unknown',
  611. 'question_count' => count($examData['questions'] ?? []),
  612. 'trace' => $e->getTraceAsString()
  613. ]);
  614. return null;
  615. }
  616. }
  617. /**
  618. * 检查数据完整性 - 发现没有题目的试卷
  619. */
  620. public function checkDataIntegrity(): array
  621. {
  622. try {
  623. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  624. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  625. ->whereDoesntHave('questions')
  626. ->get();
  627. Log::warning('发现数据不一致的试卷', [
  628. 'count' => $inconsistentPapers->count(),
  629. 'papers' => $inconsistentPapers->map(function($paper) {
  630. return [
  631. 'paper_id' => $paper->paper_id,
  632. 'paper_name' => $paper->paper_name,
  633. 'expected_questions' => $paper->question_count,
  634. 'student_id' => $paper->student_id,
  635. 'created_at' => $paper->created_at
  636. ];
  637. })->toArray()
  638. ]);
  639. return [
  640. 'inconsistent_count' => $inconsistentPapers->count(),
  641. 'papers' => $inconsistentPapers->toArray()
  642. ];
  643. } catch (\Exception $e) {
  644. Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
  645. return ['inconsistent_count' => 0, 'papers' => []];
  646. }
  647. }
  648. /**
  649. * 清理没有题目的试卷记录
  650. */
  651. public function cleanupInconsistentPapers(): int
  652. {
  653. try {
  654. return \Illuminate\Support\Facades\DB::transaction(function () {
  655. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  656. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  657. ->whereDoesntHave('questions')
  658. ->get();
  659. if ($inconsistentPapers->isEmpty()) {
  660. return 0;
  661. }
  662. // 获取要删除的试卷ID列表
  663. $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
  664. // 使用Laravel模型删除这些不一致的试卷记录
  665. $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
  666. Log::info('清理不一致的试卷记录', [
  667. 'deleted_count' => $deletedCount,
  668. 'deleted_paper_ids' => $deletedPaperIds
  669. ]);
  670. return $deletedCount;
  671. });
  672. } catch (\Exception $e) {
  673. Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
  674. return 0;
  675. }
  676. }
  677. /**
  678. * 修复试卷的题目数量统计
  679. */
  680. public function fixPaperQuestionCounts(): int
  681. {
  682. try {
  683. $fixedCount = 0;
  684. // 使用Laravel模型获取所有试卷
  685. $papers = \App\Models\Paper::all();
  686. foreach ($papers as $paper) {
  687. // 计算实际的题目数量,使用关联关系
  688. $actualQuestionCount = $paper->questions()->count();
  689. // 如果题目数量不匹配,更新试卷
  690. if ($paper->question_count !== $actualQuestionCount) {
  691. $paper->update([
  692. 'question_count' => $actualQuestionCount,
  693. 'updated_at' => now()
  694. ]);
  695. $fixedCount++;
  696. Log::info('修复试卷题目数量', [
  697. 'paper_id' => $paper->paper_id,
  698. 'old_count' => $paper->getOriginal('question_count'),
  699. 'new_count' => $actualQuestionCount
  700. ]);
  701. }
  702. }
  703. Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
  704. return $fixedCount;
  705. } catch (\Exception $e) {
  706. Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
  707. return 0;
  708. }
  709. }
  710. /**
  711. * 获取试卷列表
  712. */
  713. public function listExams(int $page = 1, int $perPage = 20): array
  714. {
  715. try {
  716. $response = Http::timeout(10)
  717. ->get($this->baseUrl . '/exam/list', [
  718. 'page' => $page,
  719. 'per_page' => $perPage
  720. ]);
  721. if ($response->successful()) {
  722. return $response->json();
  723. }
  724. Log::warning('获取试卷列表失败', [
  725. 'status' => $response->status()
  726. ]);
  727. } catch (\Exception $e) {
  728. Log::error('获取试卷列表异常', [
  729. 'error' => $e->getMessage()
  730. ]);
  731. }
  732. return ['data' => [], 'meta' => ['total' => 0]];
  733. }
  734. /**
  735. * 获取试卷详情
  736. */
  737. public function getExamById(string $paperId): ?array
  738. {
  739. try {
  740. $response = Http::timeout(10)
  741. ->get($this->baseUrl . '/exam/' . $paperId);
  742. if ($response->successful()) {
  743. return $response->json();
  744. }
  745. Log::warning('获取试卷详情失败', [
  746. 'paper_id' => $paperId,
  747. 'status' => $response->status()
  748. ]);
  749. } catch (\Exception $e) {
  750. Log::error('获取试卷详情异常', [
  751. 'paper_id' => $paperId,
  752. 'error' => $e->getMessage()
  753. ]);
  754. }
  755. return null;
  756. }
  757. /**
  758. * 导出试卷为PDF
  759. */
  760. public function exportExamToPdf(string $paperId): ?string
  761. {
  762. try {
  763. $response = Http::timeout(60)
  764. ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
  765. if ($response->successful()) {
  766. // 返回PDF文件路径或URL
  767. return $response->json('pdf_url', null);
  768. }
  769. Log::warning('导出PDF失败', [
  770. 'paper_id' => $paperId,
  771. 'status' => $response->status()
  772. ]);
  773. } catch (\Exception $e) {
  774. Log::error('导出PDF异常', [
  775. 'paper_id' => $paperId,
  776. 'error' => $e->getMessage()
  777. ]);
  778. }
  779. return null;
  780. }
  781. /**
  782. * 检查服务健康状态
  783. */
  784. public function checkHealth(): bool
  785. {
  786. try {
  787. // 健康检查使用不带/api的路径
  788. $healthUrl = str_replace('/api', '', $this->baseUrl) . '/health';
  789. $response = Http::timeout(5)
  790. ->get($healthUrl);
  791. return $response->successful();
  792. } catch (\Exception $e) {
  793. Log::error('题库服务健康检查失败', [
  794. 'error' => $e->getMessage()
  795. ]);
  796. return false;
  797. }
  798. }
  799. /**
  800. * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
  801. *
  802. * @param array $questions OCR识别的题目列表
  803. * @param string $gradeLevel 年级
  804. * @param string $subject 科目
  805. * @param int $ocrRecordId OCR记录ID,用于关联
  806. * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
  807. * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
  808. * @return array 任务ID和状态
  809. */
  810. public function generateQuestionsFromOcrAsync(
  811. array $questions,
  812. string $gradeLevel = '高一',
  813. string $subject = '数学',
  814. int $ocrRecordId = null,
  815. string $callbackUrl = null,
  816. string $callbackRouteName = 'api.ocr.callback'
  817. ): array {
  818. try {
  819. // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
  820. if (!$callbackUrl && $ocrRecordId) {
  821. $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
  822. Log::info('动态生成回调URL', [
  823. 'route_name' => $callbackRouteName,
  824. 'generated_url' => $callbackUrl
  825. ]);
  826. }
  827. // 生成唯一的任务ID
  828. $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
  829. // 更新OCR记录状态为生成中
  830. if ($ocrRecordId) {
  831. \DB::table('ocr_question_results')
  832. ->where('ocr_record_id', $ocrRecordId)
  833. ->where('question_bank_id', null) // 只更新未关联的题目
  834. ->update([
  835. 'generation_status' => 'generating',
  836. 'generation_task_id' => $taskId,
  837. 'generation_error' => null
  838. ]);
  839. }
  840. // 启动后台任务(使用Laravel的队列)
  841. if ($ocrRecordId && $callbackUrl) {
  842. // 使用Laravel队列异步处理
  843. $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
  844. } else {
  845. // 如果没有回调URL,使用同步方式
  846. $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
  847. return $response;
  848. }
  849. Log::info('OCR题目生成任务已提交到队列', [
  850. 'task_id' => $taskId,
  851. 'ocr_record_id' => $ocrRecordId,
  852. 'questions_count' => count($questions),
  853. 'callback_url' => $callbackUrl
  854. ]);
  855. return [
  856. 'status' => 'processing',
  857. 'task_id' => $taskId,
  858. 'ocr_record_id' => $ocrRecordId,
  859. 'message' => '题目生成任务已启动,完成后将通过回调通知',
  860. 'estimated_time' => '约' . (count($questions) * 2) . '秒',
  861. 'callback_info' => [
  862. 'will_callback' => !empty($callbackUrl),
  863. 'callback_url' => $callbackUrl
  864. ]
  865. ];
  866. } catch (\Exception $e) {
  867. Log::error('OCR题目生成任务提交异常', [
  868. 'error' => $e->getMessage(),
  869. 'ocr_record_id' => $ocrRecordId
  870. ]);
  871. return [
  872. 'status' => 'error',
  873. 'message' => '任务提交失败: ' . $e->getMessage()
  874. ];
  875. }
  876. }
  877. /**
  878. * 分发OCR生成任务到队列
  879. */
  880. private function dispatchOcrGenerationJob(
  881. int $ocrRecordId,
  882. array $questions,
  883. string $gradeLevel,
  884. string $subject,
  885. string $callbackUrl,
  886. string $taskId
  887. ): void {
  888. try {
  889. // 转换题目数据格式
  890. $formattedQuestions = [];
  891. foreach ($questions as $q) {
  892. $formattedQuestions[] = [
  893. 'id' => $q['id'] ?? uniqid(),
  894. 'content' => $q['content'] ?? ''
  895. ];
  896. }
  897. // 直接调用QuestionBank API的异步端点,提供回调URL
  898. // 注意: baseUrl 已经包含 /api,所以这里只需要 /ocr/questions/generate-from-ocr
  899. $response = Http::timeout(60)
  900. ->post($this->baseUrl . '/ocr/questions/generate-from-ocr', [
  901. 'ocr_record_id' => $ocrRecordId,
  902. 'questions' => $formattedQuestions,
  903. 'grade_level' => $gradeLevel,
  904. 'subject' => $subject,
  905. 'callback_url' => $callbackUrl
  906. ]);
  907. if (!$response->successful()) {
  908. Log::error('提交OCR题目生成任务失败', [
  909. 'status' => $response->status(),
  910. 'body' => $response->body(),
  911. 'task_id' => $taskId
  912. ]);
  913. // 发送失败回调
  914. $callbackData = [
  915. 'task_id' => $taskId,
  916. 'ocr_record_id' => $ocrRecordId,
  917. 'status' => 'failed',
  918. 'error' => 'API调用失败: ' . $response->status(),
  919. 'timestamp' => now()->toISOString()
  920. ];
  921. Http::timeout(10)
  922. ->post($callbackUrl, $callbackData);
  923. return;
  924. }
  925. $result = $response->json();
  926. Log::info('OCR题目生成任务已提交到QuestionBank', [
  927. 'task_id' => $taskId,
  928. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  929. 'status' => $result['status'] ?? 'unknown',
  930. 'callback_url' => $callbackUrl
  931. ]);
  932. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  933. // 回调会在题目生成完成后由QuestionBank API主动发送
  934. } catch (\Exception $e) {
  935. Log::error('OCR生成任务处理失败', [
  936. 'task_id' => $taskId,
  937. 'ocr_record_id' => $ocrRecordId,
  938. 'error' => $e->getMessage()
  939. ]);
  940. // 发送异常回调
  941. try {
  942. $callbackData = [
  943. 'task_id' => $taskId,
  944. 'ocr_record_id' => $ocrRecordId,
  945. 'status' => 'failed',
  946. 'error' => $e->getMessage(),
  947. 'timestamp' => now()->toISOString()
  948. ];
  949. Http::timeout(10)
  950. ->post($callbackUrl, $callbackData);
  951. } catch (\Exception $callbackException) {
  952. Log::error('发送异常回调失败', [
  953. 'error' => $callbackException->getMessage()
  954. ]);
  955. }
  956. }
  957. }
  958. /**
  959. * 动态生成回调URL
  960. *
  961. * @param string $routeName 路由名称
  962. * @return string 完整的回调URL
  963. */
  964. private function generateCallbackUrl(string $routeName): string
  965. {
  966. try {
  967. // 获取当前请求的域名
  968. $appUrl = config('app.url', 'http://localhost');
  969. // 如果是在命令行环境中运行,使用配置的域名
  970. if (app()->runningInConsole()) {
  971. $domain = config('services.question_bank.callback_domain', $appUrl);
  972. } else {
  973. $domain = request()->getSchemeAndHttpHost();
  974. }
  975. // 确保domain不为null
  976. $domain = $domain ?? $appUrl;
  977. // 移除末尾的斜杠
  978. $domain = rtrim($domain, '/');
  979. // 生成完整的URL
  980. $callbackUrl = $domain . route($routeName, [], false);
  981. Log::info('生成回调URL', [
  982. 'route_name' => $routeName,
  983. 'domain' => $domain,
  984. 'app_url' => $appUrl,
  985. 'callback_url' => $callbackUrl
  986. ]);
  987. return $callbackUrl;
  988. } catch (\Exception $e) {
  989. // 如果路由生成失败,使用默认URL
  990. Log::warning('路由生成失败,使用默认URL', [
  991. 'route_name' => $routeName,
  992. 'error' => $e->getMessage()
  993. ]);
  994. $fallbackUrl = config('app.url', 'http://localhost');
  995. if ($routeName === 'api.ocr.callback') {
  996. return $fallbackUrl . '/api/ocr-question-callback';
  997. }
  998. return $fallbackUrl;
  999. }
  1000. }
  1001. /**
  1002. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  1003. *
  1004. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  1005. * @param string $gradeLevel 年级
  1006. * @param string $subject 科目
  1007. * @return array 生成结果
  1008. */
  1009. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  1010. {
  1011. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  1012. }
  1013. /**
  1014. * 检查题目生成任务状态
  1015. */
  1016. public function checkGenerationTaskStatus(string $taskId): array
  1017. {
  1018. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  1019. }
  1020. /**
  1021. * 获取知识点题目统计信息
  1022. * 根据知识点代码,统计该知识点及其子知识点和技能点的题目数量
  1023. */
  1024. public function getKnowledgePointStatistics(?string $kpCode = null): array
  1025. {
  1026. try {
  1027. // 获取知识图谱数据和题目统计数据
  1028. $knowledgeGraph = $this->getKnowledgeGraph();
  1029. $nodes = $knowledgeGraph['nodes'] ?? [];
  1030. $edges = $knowledgeGraph['edges'] ?? [];
  1031. $questionStats = $this->getQuestionsStatisticsFromApi();
  1032. // 构建知识点索引
  1033. $nodeMap = [];
  1034. foreach ($nodes as $node) {
  1035. if (!empty($node['kp_code'])) {
  1036. $nodeMap[$node['kp_code']] = $node;
  1037. }
  1038. }
  1039. // 构建子知识点关系(从edges中提取)
  1040. $childrenMap = [];
  1041. $parentMap = [];
  1042. foreach ($edges as $edge) {
  1043. $source = $edge['source'] ?? '';
  1044. $target = $edge['target'] ?? '';
  1045. $direction = $edge['relation_direction'] ?? '';
  1046. if (!empty($source) && !empty($target)) {
  1047. if ($direction === 'DOWNSTREAM') {
  1048. $childrenMap[$source][] = $target;
  1049. $parentMap[$target] = $source;
  1050. }
  1051. }
  1052. }
  1053. // 构建技能点统计
  1054. $skillStats = [];
  1055. foreach ($questionStats as $stat) {
  1056. $code = $stat['kp_code'] ?? '';
  1057. $skills = $stat['skills_list'] ?? [];
  1058. if (!empty($code)) {
  1059. foreach ($skills as $skillCode) {
  1060. if (!empty($skillCode)) {
  1061. if (!isset($skillStats[$code])) {
  1062. $skillStats[$code] = [];
  1063. }
  1064. if (!isset($skillStats[$code][$skillCode])) {
  1065. $skillStats[$code][$skillCode] = 0;
  1066. }
  1067. $skillStats[$code][$skillCode]++;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. // 如果指定了特定知识点,只返回该知识点的统计
  1073. if ($kpCode && isset($nodeMap[$kpCode])) {
  1074. return $this->buildKnowledgePointStats($kpCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1075. }
  1076. // 否则返回所有顶级知识点的统计
  1077. $result = [];
  1078. $rootNodes = [];
  1079. // 找出根节点(没有父节点的节点)
  1080. foreach ($nodes as $node) {
  1081. $code = $node['kp_code'] ?? '';
  1082. if (!empty($code) && !isset($parentMap[$code])) {
  1083. $rootNodes[] = $code;
  1084. }
  1085. }
  1086. foreach ($rootNodes as $rootCode) {
  1087. $result[] = $this->buildKnowledgePointStats($rootCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1088. }
  1089. // 按题目总数排序
  1090. usort($result, function($a, $b) {
  1091. return ($b['total_questions'] ?? 0) <=> ($a['total_questions'] ?? 0);
  1092. });
  1093. return $result;
  1094. } catch (\Exception $e) {
  1095. Log::error('获取知识点统计失败', [
  1096. 'kp_code' => $kpCode,
  1097. 'error' => $e->getMessage()
  1098. ]);
  1099. return [];
  1100. }
  1101. }
  1102. /**
  1103. * 获取知识图谱数据
  1104. */
  1105. private function getKnowledgeGraph(): array
  1106. {
  1107. try {
  1108. $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');
  1109. $response = Http::timeout(10)
  1110. ->get($knowledgeApiBase . '/graph/export');
  1111. if ($response->successful()) {
  1112. return $response->json();
  1113. }
  1114. } catch (\Exception $e) {
  1115. Log::error('获取知识图谱失败', ['error' => $e->getMessage()]);
  1116. }
  1117. return ['nodes' => [], 'edges' => []];
  1118. }
  1119. /**
  1120. * 从 API 获取题目统计
  1121. */
  1122. private function getQuestionsStatisticsFromApi(): array
  1123. {
  1124. try {
  1125. // 调用题库 API 获取统计数据
  1126. $response = Http::timeout(30)
  1127. ->get($this->baseUrl . '/questions/statistics');
  1128. if ($response->successful()) {
  1129. $data = $response->json();
  1130. return $data['by_kp'] ?? [];
  1131. }
  1132. Log::warning('获取题目统计API失败', [
  1133. 'status' => $response->status(),
  1134. 'url' => $this->baseUrl . '/questions/statistics'
  1135. ]);
  1136. } catch (\Exception $e) {
  1137. Log::error('获取题目统计异常', [
  1138. 'error' => $e->getMessage(),
  1139. 'url' => $this->baseUrl . '/questions/statistics'
  1140. ]);
  1141. }
  1142. return [];
  1143. }
  1144. /**
  1145. * 构建单个知识点的统计信息
  1146. */
  1147. private function buildKnowledgePointStats(
  1148. string $kpCode,
  1149. array $nodeMap,
  1150. array $childrenMap,
  1151. array $questionStats,
  1152. array $skillStats
  1153. ): array {
  1154. $node = $nodeMap[$kpCode] ?? null;
  1155. if (!$node) {
  1156. return [];
  1157. }
  1158. // 获取直接子知识点
  1159. $children = $childrenMap[$kpCode] ?? [];
  1160. $directQuestionCount = 0;
  1161. // 查找当前知识点的题目数
  1162. foreach ($questionStats as $stat) {
  1163. if ($stat['kp_code'] === $kpCode) {
  1164. $directQuestionCount = $stat['question_count'] ?? 0;
  1165. break;
  1166. }
  1167. }
  1168. // 计算子知识点统计
  1169. $childrenStats = [];
  1170. foreach ($children as $childCode) {
  1171. $childStats = $this->buildKnowledgePointStats($childCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1172. if (!empty($childStats)) {
  1173. $childrenStats[] = $childStats;
  1174. }
  1175. }
  1176. // 计算子知识点题目总数
  1177. $childrenQuestionCount = 0;
  1178. foreach ($childrenStats as $child) {
  1179. $childrenQuestionCount += $child['total_questions'] ?? 0;
  1180. }
  1181. // 获取当前知识点的技能点统计
  1182. $skillsCount = 0;
  1183. if (isset($skillStats[$kpCode])) {
  1184. $skillsCount = array_sum($skillStats[$kpCode]);
  1185. }
  1186. return [
  1187. 'kp_code' => $kpCode,
  1188. 'cn_name' => $node['cn_name'] ?? $kpCode,
  1189. 'en_name' => $node['en_name'] ?? '',
  1190. 'total_questions' => $directQuestionCount + $childrenQuestionCount,
  1191. 'direct_questions' => $directQuestionCount,
  1192. 'children_questions' => $childrenQuestionCount,
  1193. 'children' => $childrenStats,
  1194. 'skills_count' => count($skillStats[$kpCode] ?? []),
  1195. 'skills_total_questions' => $skillsCount,
  1196. 'skills' => array_map(function($skillCode, $count) use ($kpCode) {
  1197. return [
  1198. 'kp_code' => $kpCode,
  1199. 'skill_code' => $skillCode,
  1200. 'question_count' => $count
  1201. ];
  1202. }, array_keys($skillStats[$kpCode] ?? []), array_values($skillStats[$kpCode] ?? []))
  1203. ];
  1204. }
  1205. /**
  1206. * 获取所有试卷列表
  1207. */
  1208. public function getAllPapers(): array
  1209. {
  1210. try {
  1211. $response = Http::timeout(10)
  1212. ->get($this->baseUrl . '/papers');
  1213. if ($response->successful()) {
  1214. return $response->json('data', []);
  1215. }
  1216. Log::warning('获取试卷列表失败', [
  1217. 'status' => $response->status(),
  1218. 'response' => $response->body(),
  1219. ]);
  1220. return [];
  1221. } catch (\Exception $e) {
  1222. Log::error('获取试卷列表异常', [
  1223. 'error' => $e->getMessage(),
  1224. ]);
  1225. return [];
  1226. }
  1227. }
  1228. /**
  1229. * 获取指定试卷的题目
  1230. */
  1231. public function getPaperQuestions(string $paperId): array
  1232. {
  1233. try {
  1234. $response = Http::timeout(10)
  1235. ->get($this->baseUrl . '/papers/' . $paperId . '/questions');
  1236. if ($response->successful()) {
  1237. return $response->json('data', []);
  1238. }
  1239. Log::warning('获取试卷题目失败', [
  1240. 'paper_id' => $paperId,
  1241. 'status' => $response->status(),
  1242. 'response' => $response->body(),
  1243. ]);
  1244. return [];
  1245. } catch (\Exception $e) {
  1246. Log::error('获取试卷题目异常', [
  1247. 'paper_id' => $paperId,
  1248. 'error' => $e->getMessage(),
  1249. ]);
  1250. return [];
  1251. }
  1252. }
  1253. }