QuestionBankService.php 51 KB

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