QuestionBankService.php 54 KB

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