QuestionBankService.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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. 'total_questions' => 0, // 临时设为0,处理完题目后再更新
  477. 'total_score' => $examData['total_score'] ?? 0,
  478. 'status' => 'draft',
  479. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  480. ]);
  481. // 获取所有题目的正确答案
  482. $questionBankIds = array_filter(array_map(function ($q) {
  483. return $q['id'] ?? $q['question_id'] ?? null;
  484. }, $examData['questions']));
  485. $correctAnswersMap = [];
  486. if (! empty($questionBankIds)) {
  487. Log::info('从本地题库获取题目正确答案', [
  488. 'paper_id' => $paperId,
  489. 'question_bank_ids' => $questionBankIds,
  490. ]);
  491. $localQuestions = Question::query()
  492. ->whereIn('id', array_values($questionBankIds))
  493. ->get(['id', 'answer']);
  494. foreach ($localQuestions as $detail) {
  495. $correctAnswersMap[$detail->id] = $detail->answer ?? '';
  496. }
  497. }
  498. // 准备题目数据
  499. $questionInsertData = [];
  500. $skippedQuestions = 0;
  501. Log::info('开始处理题目数据', [
  502. 'paper_id' => $paperId,
  503. 'total_questions' => count($examData['questions']),
  504. ]);
  505. foreach ($examData['questions'] as $index => $question) {
  506. // 验证题目基本数据
  507. if (empty($question['stem']) && empty($question['content'])) {
  508. $skippedQuestions++;
  509. Log::warning('跳过没有内容的题目', [
  510. 'paper_id' => $paperId,
  511. 'question_index' => $index,
  512. 'question_id' => $question['id'] ?? 'N/A',
  513. 'has_stem' => ! empty($question['stem']),
  514. 'has_content' => ! empty($question['content']),
  515. 'stem_preview' => substr($question['stem'] ?? '', 0, 50),
  516. ]);
  517. continue;
  518. }
  519. // 处理题目内容:分离题干和选项(如果存在)
  520. $rawContent = $question['stem'] ?? $question['content'] ?? '';
  521. [$stem, $options] = $this->separateStemAndOptions($rawContent);
  522. // 将选项以换行符形式附加到题干末尾,方便后续渲染
  523. if (! empty($options)) {
  524. $stemWithOptions = $stem."\n".implode("\n", array_map(function ($opt, $idx) {
  525. return chr(65 + $idx).'. '.$opt;
  526. }, $options, array_keys($options)));
  527. $question['stem'] = $stemWithOptions;
  528. $question['options'] = $options;
  529. } else {
  530. $question['stem'] = $stem;
  531. }
  532. // 处理难度字段:如果是字符串则转换为数字
  533. $difficultyValue = $question['difficulty'] ?? 0.5;
  534. if (is_string($difficultyValue)) {
  535. // 将中文难度转换为数字
  536. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  537. $difficultyValue = 0.3;
  538. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  539. $difficultyValue = 0.6;
  540. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  541. $difficultyValue = 0.9;
  542. } else {
  543. $difficultyValue = 0.5;
  544. }
  545. }
  546. // 确保 knowledge_point 有值
  547. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  548. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  549. $knowledgePoint = $question['kp_code'];
  550. }
  551. // 获取题目类型(以题库原始类型为准,不再二次推断/归一化)
  552. $questionType = $question['question_type'] ?? $question['type'] ?? 'answer';
  553. // 获取正确答案
  554. $questionBankId = $question['id'] ?? $question['question_id'] ?? null;
  555. $correctAnswer = $correctAnswersMap[$questionBankId] ?? $question['answer'] ?? $question['correct_answer'] ?? '';
  556. $questionInsertData[] = [
  557. 'paper_id' => $paperId,
  558. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  559. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  560. 'knowledge_point' => $knowledgePoint,
  561. 'question_type' => $questionType,
  562. 'question_text' => is_array($question['stem'] ?? null) ? json_encode($question['stem'], JSON_UNESCAPED_UNICODE) : ($question['stem'] ?? $question['content'] ?? $question['question_text'] ?? ''),
  563. 'correct_answer' => is_array($correctAnswer) ? json_encode($correctAnswer, JSON_UNESCAPED_UNICODE) : $correctAnswer, // 保存正确答案
  564. 'solution' => is_array($question['solution'] ?? null) ? json_encode($question['solution'], JSON_UNESCAPED_UNICODE) : ($question['solution'] ?? ''), // 保存解题思路
  565. 'difficulty' => $difficultyValue,
  566. 'score' => $question['score'] ?? 5, // 默认5分
  567. 'estimated_time' => $question['estimated_time'] ?? 300,
  568. 'question_number' => $question['question_number'] ?? ($index + 1),
  569. ];
  570. }
  571. // 验证是否有有效的题目数据
  572. if (empty($questionInsertData)) {
  573. Log::error('没有有效的题目数据可以保存', [
  574. 'paper_id' => $paperId,
  575. 'total_input_questions' => count($examData['questions']),
  576. 'skipped_questions' => $skippedQuestions,
  577. ]);
  578. throw new \Exception('没有有效的题目数据');
  579. }
  580. Log::info('准备插入题目数据', [
  581. 'paper_id' => $paperId,
  582. 'total_input_questions' => count($examData['questions']),
  583. 'skipped_questions' => $skippedQuestions,
  584. 'questions_to_insert' => count($questionInsertData),
  585. ]);
  586. // 调试:检查第一个题目的solution字段
  587. if (! empty($questionInsertData)) {
  588. $firstQuestion = $questionInsertData[0];
  589. Log::debug('试卷保存调试 - 第一个题目', [
  590. 'paper_id' => $paperId,
  591. 'question_id' => $firstQuestion['question_id'] ?? '',
  592. 'question_bank_id' => $firstQuestion['question_bank_id'] ?? '',
  593. 'has_solution' => ! empty($firstQuestion['solution']),
  594. 'solution_length' => strlen($firstQuestion['solution'] ?? ''),
  595. 'solution_preview' => substr($firstQuestion['solution'] ?? '', 0, 80),
  596. ]);
  597. }
  598. // 使用Laravel模型批量插入题目数据
  599. \App\Models\PaperQuestion::insert($questionInsertData);
  600. // 验证插入结果,使用关联关系
  601. $insertedQuestionCount = $paper->questions()->count();
  602. Log::info('验证题目插入结果', [
  603. 'paper_id' => $paperId,
  604. 'expected_count' => count($questionInsertData),
  605. 'actual_count' => $insertedQuestionCount,
  606. 'difference' => $insertedQuestionCount - count($questionInsertData),
  607. ]);
  608. if ($insertedQuestionCount !== count($questionInsertData)) {
  609. Log::error('题目插入数量不匹配', [
  610. 'paper_id' => $paperId,
  611. 'expected' => count($questionInsertData),
  612. 'actual' => $insertedQuestionCount,
  613. 'difference' => $insertedQuestionCount - count($questionInsertData),
  614. 'input_questions_count' => count($examData['questions']),
  615. 'skipped_questions' => $skippedQuestions,
  616. ]);
  617. throw new \Exception('题目插入数量不匹配:预期 '.count($questionInsertData).",实际 {$insertedQuestionCount}");
  618. }
  619. // 【重要】更新试卷的total_questions字段为实际插入的题目数量
  620. $paper->update(['total_questions' => $insertedQuestionCount]);
  621. Log::info('试卷保存成功', [
  622. 'paper_id' => $paperId,
  623. 'expected_questions' => count($questionInsertData),
  624. 'actual_questions' => $insertedQuestionCount,
  625. 'paper_name' => $paper->paper_name,
  626. ]);
  627. return $paperId;
  628. });
  629. } catch (\Exception $e) {
  630. Log::error('保存试卷到数据库失败', [
  631. 'error' => $e->getMessage(),
  632. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  633. 'student_id' => $examData['student_id'] ?? 'unknown',
  634. 'question_count' => count($examData['questions'] ?? []),
  635. 'trace' => $e->getTraceAsString(),
  636. ]);
  637. }
  638. return null;
  639. }
  640. private function useLocal(): bool
  641. {
  642. return true;
  643. }
  644. private function local(): QuestionLocalService
  645. {
  646. return app(QuestionLocalService::class);
  647. }
  648. private function normalizeQuestionTypeValue(string $type): string
  649. {
  650. $type = trim($type);
  651. $lower = strtolower($type);
  652. if (in_array($lower, ['choice', 'single_choice', 'multiple_choice'], true)) {
  653. return 'choice';
  654. }
  655. if (in_array($lower, ['fill', 'blank', 'fill_in_the_blank'], true)) {
  656. return 'fill';
  657. }
  658. if (in_array($lower, ['answer', 'calculation', 'word_problem', 'proof'], true)) {
  659. return 'answer';
  660. }
  661. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  662. return 'choice';
  663. }
  664. if (in_array($type, ['FILL', 'FILL_IN_THE_BLANK'], true)) {
  665. return 'fill';
  666. }
  667. if (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  668. return 'answer';
  669. }
  670. if (in_array($type, ['选择题'], true)) {
  671. return 'choice';
  672. }
  673. if (in_array($type, ['填空题'], true)) {
  674. return 'fill';
  675. }
  676. if (in_array($type, ['解答题', '计算题'], true)) {
  677. return 'answer';
  678. }
  679. return $lower ?: 'answer';
  680. }
  681. /**
  682. * 检查数据完整性 - 发现没有题目的试卷
  683. */
  684. public function checkDataIntegrity(): array
  685. {
  686. try {
  687. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  688. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  689. ->whereDoesntHave('questions')
  690. ->get();
  691. Log::warning('发现数据不一致的试卷', [
  692. 'count' => $inconsistentPapers->count(),
  693. 'papers' => $inconsistentPapers->map(function ($paper) {
  694. return [
  695. 'paper_id' => $paper->paper_id,
  696. 'paper_name' => $paper->paper_name,
  697. 'expected_questions' => $paper->question_count,
  698. 'student_id' => $paper->student_id,
  699. 'created_at' => $paper->created_at,
  700. ];
  701. })->toArray(),
  702. ]);
  703. return [
  704. 'inconsistent_count' => $inconsistentPapers->count(),
  705. 'papers' => $inconsistentPapers->toArray(),
  706. ];
  707. } catch (\Exception $e) {
  708. Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
  709. return ['inconsistent_count' => 0, 'papers' => []];
  710. }
  711. }
  712. /**
  713. * 清理没有题目的试卷记录
  714. */
  715. public function cleanupInconsistentPapers(): int
  716. {
  717. try {
  718. return \Illuminate\Support\Facades\DB::transaction(function () {
  719. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  720. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  721. ->whereDoesntHave('questions')
  722. ->get();
  723. if ($inconsistentPapers->isEmpty()) {
  724. return 0;
  725. }
  726. // 获取要删除的试卷ID列表
  727. $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
  728. // 使用Laravel模型删除这些不一致的试卷记录
  729. $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
  730. Log::info('清理不一致的试卷记录', [
  731. 'deleted_count' => $deletedCount,
  732. 'deleted_paper_ids' => $deletedPaperIds,
  733. ]);
  734. return $deletedCount;
  735. });
  736. } catch (\Exception $e) {
  737. Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
  738. return 0;
  739. }
  740. }
  741. /**
  742. * 修复试卷的题目数量统计
  743. */
  744. public function fixPaperQuestionCounts(): int
  745. {
  746. try {
  747. $fixedCount = 0;
  748. // 使用Laravel模型获取所有试卷
  749. $papers = \App\Models\Paper::all();
  750. foreach ($papers as $paper) {
  751. // 计算实际的题目数量,使用关联关系
  752. $actualQuestionCount = $paper->questions()->count();
  753. // 如果题目数量不匹配,更新试卷
  754. if ($paper->question_count !== $actualQuestionCount) {
  755. $paper->update([
  756. 'question_count' => $actualQuestionCount,
  757. 'updated_at' => now(),
  758. ]);
  759. $fixedCount++;
  760. Log::info('修复试卷题目数量', [
  761. 'paper_id' => $paper->paper_id,
  762. 'old_count' => $paper->getOriginal('question_count'),
  763. 'new_count' => $actualQuestionCount,
  764. ]);
  765. }
  766. }
  767. Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
  768. return $fixedCount;
  769. } catch (\Exception $e) {
  770. Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
  771. return 0;
  772. }
  773. }
  774. /**
  775. * 获取试卷列表
  776. */
  777. public function listExams(int $page = 1, int $perPage = 20): array
  778. {
  779. $query = Paper::query()->whereHas('questions');
  780. $paginator = $query->orderByDesc('id')->paginate($perPage, ['*'], 'page', $page);
  781. $data = $paginator->getCollection()->map(function (Paper $paper) {
  782. return [
  783. 'paper_id' => $paper->paper_id,
  784. 'paper_name' => $paper->paper_name,
  785. 'student_id' => $paper->student_id,
  786. 'teacher_id' => $paper->teacher_id,
  787. 'total_questions' => $paper->question_count ?? $paper->questions()->count(),
  788. 'total_score' => $paper->total_score,
  789. 'difficulty_category' => $paper->difficulty_category,
  790. 'status' => $paper->status,
  791. 'created_at' => $paper->created_at,
  792. 'updated_at' => $paper->updated_at,
  793. ];
  794. })->toArray();
  795. return [
  796. 'data' => $data,
  797. 'meta' => [
  798. 'page' => $paginator->currentPage(),
  799. 'per_page' => $paginator->perPage(),
  800. 'total' => $paginator->total(),
  801. 'total_pages' => $paginator->lastPage(),
  802. ],
  803. ];
  804. }
  805. /**
  806. * 获取试卷详情
  807. */
  808. public function getExamById(string $paperId): ?array
  809. {
  810. $paper = Paper::where('paper_id', $paperId)->first();
  811. if (! $paper) {
  812. return null;
  813. }
  814. return app(PaperPayloadService::class)->buildPaperApiPayload($paper);
  815. }
  816. /**
  817. * 导出试卷为PDF
  818. */
  819. public function exportExamToPdf(string $paperId): ?string
  820. {
  821. return app(ExamPdfExportService::class)->generateExamPdf($paperId);
  822. }
  823. /**
  824. * 检查服务健康状态
  825. */
  826. public function checkHealth(): bool
  827. {
  828. return true;
  829. }
  830. /**
  831. * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
  832. *
  833. * @param array $questions OCR识别的题目列表
  834. * @param string $gradeLevel 年级
  835. * @param string $subject 科目
  836. * @param int $ocrRecordId OCR记录ID,用于关联
  837. * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
  838. * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
  839. * @return array 任务ID和状态
  840. */
  841. public function generateQuestionsFromOcrAsync(
  842. array $questions,
  843. string $gradeLevel = '高一',
  844. string $subject = '数学',
  845. ?int $ocrRecordId = null,
  846. ?string $callbackUrl = null,
  847. string $callbackRouteName = 'api.ocr.callback'
  848. ): array {
  849. try {
  850. // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
  851. if (! $callbackUrl && $ocrRecordId) {
  852. $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
  853. Log::info('动态生成回调URL', [
  854. 'route_name' => $callbackRouteName,
  855. 'generated_url' => $callbackUrl,
  856. ]);
  857. }
  858. // 生成唯一的任务ID
  859. $taskId = 'ocr_'.$ocrRecordId.'_'.time().'_'.substr(md5(uniqid()), 0, 8);
  860. // 更新OCR记录状态为生成中
  861. if ($ocrRecordId) {
  862. \DB::table('ocr_question_results')
  863. ->where('ocr_record_id', $ocrRecordId)
  864. ->where('question_bank_id', null) // 只更新未关联的题目
  865. ->update([
  866. 'generation_status' => 'generating',
  867. 'generation_task_id' => $taskId,
  868. 'generation_error' => null,
  869. ]);
  870. }
  871. // 启动后台任务(使用Laravel的队列)
  872. if ($ocrRecordId && $callbackUrl) {
  873. // 使用Laravel队列异步处理
  874. $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
  875. } else {
  876. // 如果没有回调URL,使用同步方式
  877. $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
  878. return $response;
  879. }
  880. Log::info('OCR题目生成任务已提交到队列', [
  881. 'task_id' => $taskId,
  882. 'ocr_record_id' => $ocrRecordId,
  883. 'questions_count' => count($questions),
  884. 'callback_url' => $callbackUrl,
  885. ]);
  886. return [
  887. 'status' => 'processing',
  888. 'task_id' => $taskId,
  889. 'ocr_record_id' => $ocrRecordId,
  890. 'message' => '题目生成任务已启动,完成后将通过回调通知',
  891. 'estimated_time' => '约'.(count($questions) * 2).'秒',
  892. 'callback_info' => [
  893. 'will_callback' => ! empty($callbackUrl),
  894. 'callback_url' => $callbackUrl,
  895. ],
  896. ];
  897. } catch (\Exception $e) {
  898. Log::error('OCR题目生成任务提交异常', [
  899. 'error' => $e->getMessage(),
  900. 'ocr_record_id' => $ocrRecordId,
  901. ]);
  902. return [
  903. 'status' => 'error',
  904. 'message' => '任务提交失败: '.$e->getMessage(),
  905. ];
  906. }
  907. }
  908. /**
  909. * 分发OCR生成任务到队列
  910. */
  911. private function dispatchOcrGenerationJob(
  912. int $ocrRecordId,
  913. array $questions,
  914. string $gradeLevel,
  915. string $subject,
  916. string $callbackUrl,
  917. string $taskId
  918. ): void {
  919. try {
  920. // 转换题目数据格式
  921. $formattedQuestions = [];
  922. foreach ($questions as $q) {
  923. $formattedQuestions[] = [
  924. 'id' => $q['id'] ?? uniqid(),
  925. 'content' => $q['content'] ?? '',
  926. ];
  927. }
  928. // 直接调用QuestionBank API的异步端点,提供回调URL
  929. // 注意: baseUrl 已经包含 /api,所以这里只需要 /ocr/questions/generate-from-ocr
  930. $response = Http::timeout(60)
  931. ->post($this->baseUrl.'/ocr/questions/generate-from-ocr', [
  932. 'ocr_record_id' => $ocrRecordId,
  933. 'questions' => $formattedQuestions,
  934. 'grade_level' => $gradeLevel,
  935. 'subject' => $subject,
  936. 'callback_url' => $callbackUrl,
  937. ]);
  938. if (! $response->successful()) {
  939. Log::error('提交OCR题目生成任务失败', [
  940. 'status' => $response->status(),
  941. 'body' => $response->body(),
  942. 'task_id' => $taskId,
  943. ]);
  944. // 发送失败回调
  945. $callbackData = [
  946. 'task_id' => $taskId,
  947. 'ocr_record_id' => $ocrRecordId,
  948. 'status' => 'failed',
  949. 'error' => 'API调用失败: '.$response->status(),
  950. 'timestamp' => now()->toISOString(),
  951. ];
  952. Http::timeout(10)
  953. ->post($callbackUrl, $callbackData);
  954. return;
  955. }
  956. $result = $response->json();
  957. Log::info('OCR题目生成任务已提交到QuestionBank', [
  958. 'task_id' => $taskId,
  959. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  960. 'status' => $result['status'] ?? 'unknown',
  961. 'callback_url' => $callbackUrl,
  962. ]);
  963. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  964. // 回调会在题目生成完成后由QuestionBank API主动发送
  965. } catch (\Exception $e) {
  966. Log::error('OCR生成任务处理失败', [
  967. 'task_id' => $taskId,
  968. 'ocr_record_id' => $ocrRecordId,
  969. 'error' => $e->getMessage(),
  970. ]);
  971. // 发送异常回调
  972. try {
  973. $callbackData = [
  974. 'task_id' => $taskId,
  975. 'ocr_record_id' => $ocrRecordId,
  976. 'status' => 'failed',
  977. 'error' => $e->getMessage(),
  978. 'timestamp' => now()->toISOString(),
  979. ];
  980. Http::timeout(10)
  981. ->post($callbackUrl, $callbackData);
  982. } catch (\Exception $callbackException) {
  983. Log::error('发送异常回调失败', [
  984. 'error' => $callbackException->getMessage(),
  985. ]);
  986. }
  987. }
  988. }
  989. /**
  990. * 动态生成回调URL
  991. *
  992. * @param string $routeName 路由名称
  993. * @return string 完整的回调URL
  994. */
  995. private function generateCallbackUrl(string $routeName): string
  996. {
  997. try {
  998. // 获取当前请求的域名
  999. $appUrl = config('app.url', 'http://localhost');
  1000. // 如果是在命令行环境中运行,使用配置的域名
  1001. if (app()->runningInConsole()) {
  1002. $domain = $appUrl;
  1003. } else {
  1004. $domain = request()->getSchemeAndHttpHost();
  1005. }
  1006. // 确保domain不为null
  1007. $domain = $domain ?? $appUrl;
  1008. // 移除末尾的斜杠
  1009. $domain = rtrim($domain, '/');
  1010. // 生成完整的URL
  1011. $callbackUrl = $domain.route($routeName, [], false);
  1012. Log::info('生成回调URL', [
  1013. 'route_name' => $routeName,
  1014. 'domain' => $domain,
  1015. 'app_url' => $appUrl,
  1016. 'callback_url' => $callbackUrl,
  1017. ]);
  1018. return $callbackUrl;
  1019. } catch (\Exception $e) {
  1020. // 如果路由生成失败,使用默认URL
  1021. Log::warning('路由生成失败,使用默认URL', [
  1022. 'route_name' => $routeName,
  1023. 'error' => $e->getMessage(),
  1024. ]);
  1025. $fallbackUrl = config('app.url', 'http://localhost');
  1026. if ($routeName === 'api.ocr.callback') {
  1027. return $fallbackUrl.'/api/ocr-question-callback';
  1028. }
  1029. return $fallbackUrl;
  1030. }
  1031. }
  1032. /**
  1033. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  1034. *
  1035. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  1036. * @param string $gradeLevel 年级
  1037. * @param string $subject 科目
  1038. * @return array 生成结果
  1039. */
  1040. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  1041. {
  1042. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  1043. }
  1044. /**
  1045. * 检查题目生成任务状态
  1046. */
  1047. public function checkGenerationTaskStatus(string $taskId): array
  1048. {
  1049. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  1050. }
  1051. /**
  1052. * 获取知识点题目统计信息
  1053. * 根据知识点代码,统计该知识点及其子知识点和技能点的题目数量
  1054. */
  1055. public function getKnowledgePointStatistics(?string $kpCode = null): array
  1056. {
  1057. try {
  1058. // 获取知识图谱数据和题目统计数据
  1059. $knowledgeGraph = $this->getKnowledgeGraph();
  1060. $nodes = $knowledgeGraph['nodes'] ?? [];
  1061. $edges = $knowledgeGraph['edges'] ?? [];
  1062. $questionStats = $this->getQuestionsStatisticsFromApi();
  1063. // 构建知识点索引
  1064. $nodeMap = [];
  1065. foreach ($nodes as $node) {
  1066. if (! empty($node['kp_code'])) {
  1067. $nodeMap[$node['kp_code']] = $node;
  1068. }
  1069. }
  1070. // 构建子知识点关系(从edges中提取)
  1071. $childrenMap = [];
  1072. $parentMap = [];
  1073. foreach ($edges as $edge) {
  1074. $source = $edge['source'] ?? '';
  1075. $target = $edge['target'] ?? '';
  1076. $direction = $edge['relation_direction'] ?? '';
  1077. if (! empty($source) && ! empty($target)) {
  1078. if ($direction === 'DOWNSTREAM') {
  1079. $childrenMap[$source][] = $target;
  1080. $parentMap[$target] = $source;
  1081. }
  1082. }
  1083. }
  1084. // 构建技能点统计
  1085. $skillStats = [];
  1086. foreach ($questionStats as $stat) {
  1087. $code = $stat['kp_code'] ?? '';
  1088. $skills = $stat['skills_list'] ?? [];
  1089. if (! empty($code)) {
  1090. foreach ($skills as $skillCode) {
  1091. if (! empty($skillCode)) {
  1092. if (! isset($skillStats[$code])) {
  1093. $skillStats[$code] = [];
  1094. }
  1095. if (! isset($skillStats[$code][$skillCode])) {
  1096. $skillStats[$code][$skillCode] = 0;
  1097. }
  1098. $skillStats[$code][$skillCode]++;
  1099. }
  1100. }
  1101. }
  1102. }
  1103. // 如果指定了特定知识点,只返回该知识点的统计
  1104. if ($kpCode && isset($nodeMap[$kpCode])) {
  1105. return $this->buildKnowledgePointStats($kpCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1106. }
  1107. // 否则返回所有顶级知识点的统计
  1108. $result = [];
  1109. $rootNodes = [];
  1110. // 找出根节点(没有父节点的节点)
  1111. foreach ($nodes as $node) {
  1112. $code = $node['kp_code'] ?? '';
  1113. if (! empty($code) && ! isset($parentMap[$code])) {
  1114. $rootNodes[] = $code;
  1115. }
  1116. }
  1117. foreach ($rootNodes as $rootCode) {
  1118. $result[] = $this->buildKnowledgePointStats($rootCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1119. }
  1120. // 按题目总数排序
  1121. usort($result, function ($a, $b) {
  1122. return ($b['total_questions'] ?? 0) <=> ($a['total_questions'] ?? 0);
  1123. });
  1124. return $result;
  1125. } catch (\Exception $e) {
  1126. Log::error('获取知识点统计失败', [
  1127. 'kp_code' => $kpCode,
  1128. 'error' => $e->getMessage(),
  1129. ]);
  1130. return [];
  1131. }
  1132. }
  1133. /**
  1134. * 获取知识图谱数据
  1135. */
  1136. private function getKnowledgeGraph(): array
  1137. {
  1138. try {
  1139. $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');
  1140. $response = Http::timeout(10)
  1141. ->get($knowledgeApiBase.'/graph/export');
  1142. if ($response->successful()) {
  1143. return $response->json();
  1144. }
  1145. } catch (\Exception $e) {
  1146. Log::error('获取知识图谱失败', ['error' => $e->getMessage()]);
  1147. }
  1148. return ['nodes' => [], 'edges' => []];
  1149. }
  1150. /**
  1151. * 从 API 获取题目统计
  1152. */
  1153. private function getQuestionsStatisticsFromApi(): array
  1154. {
  1155. try {
  1156. // 调用题库 API 获取统计数据
  1157. $response = Http::timeout(30)
  1158. ->get($this->baseUrl.'/questions/statistics');
  1159. if ($response->successful()) {
  1160. $data = $response->json();
  1161. return $data['by_kp'] ?? [];
  1162. }
  1163. Log::warning('获取题目统计API失败', [
  1164. 'status' => $response->status(),
  1165. 'url' => $this->baseUrl.'/questions/statistics',
  1166. ]);
  1167. } catch (\Exception $e) {
  1168. Log::error('获取题目统计异常', [
  1169. 'error' => $e->getMessage(),
  1170. 'url' => $this->baseUrl.'/questions/statistics',
  1171. ]);
  1172. }
  1173. return [];
  1174. }
  1175. /**
  1176. * 构建单个知识点的统计信息
  1177. */
  1178. private function buildKnowledgePointStats(
  1179. string $kpCode,
  1180. array $nodeMap,
  1181. array $childrenMap,
  1182. array $questionStats,
  1183. array $skillStats
  1184. ): array {
  1185. $node = $nodeMap[$kpCode] ?? null;
  1186. if (! $node) {
  1187. return [];
  1188. }
  1189. // 获取直接子知识点
  1190. $children = $childrenMap[$kpCode] ?? [];
  1191. $directQuestionCount = 0;
  1192. // 查找当前知识点的题目数
  1193. foreach ($questionStats as $stat) {
  1194. if ($stat['kp_code'] === $kpCode) {
  1195. $directQuestionCount = $stat['question_count'] ?? 0;
  1196. break;
  1197. }
  1198. }
  1199. // 计算子知识点统计
  1200. $childrenStats = [];
  1201. foreach ($children as $childCode) {
  1202. $childStats = $this->buildKnowledgePointStats($childCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1203. if (! empty($childStats)) {
  1204. $childrenStats[] = $childStats;
  1205. }
  1206. }
  1207. // 计算子知识点题目总数
  1208. $childrenQuestionCount = 0;
  1209. foreach ($childrenStats as $child) {
  1210. $childrenQuestionCount += $child['total_questions'] ?? 0;
  1211. }
  1212. // 获取当前知识点的技能点统计
  1213. $skillsCount = 0;
  1214. if (isset($skillStats[$kpCode])) {
  1215. $skillsCount = array_sum($skillStats[$kpCode]);
  1216. }
  1217. return [
  1218. 'kp_code' => $kpCode,
  1219. 'cn_name' => $node['cn_name'] ?? $kpCode,
  1220. 'en_name' => $node['en_name'] ?? '',
  1221. 'total_questions' => $directQuestionCount + $childrenQuestionCount,
  1222. 'direct_questions' => $directQuestionCount,
  1223. 'children_questions' => $childrenQuestionCount,
  1224. 'children' => $childrenStats,
  1225. 'skills_count' => count($skillStats[$kpCode] ?? []),
  1226. 'skills_total_questions' => $skillsCount,
  1227. 'skills' => array_map(function ($skillCode, $count) use ($kpCode) {
  1228. return [
  1229. 'kp_code' => $kpCode,
  1230. 'skill_code' => $skillCode,
  1231. 'question_count' => $count,
  1232. ];
  1233. }, array_keys($skillStats[$kpCode] ?? []), array_values($skillStats[$kpCode] ?? [])),
  1234. ];
  1235. }
  1236. /**
  1237. * 获取所有试卷列表
  1238. */
  1239. public function getAllPapers(): array
  1240. {
  1241. try {
  1242. $response = Http::timeout(10)
  1243. ->get($this->baseUrl.'/papers');
  1244. if ($response->successful()) {
  1245. return $response->json('data', []);
  1246. }
  1247. Log::warning('获取试卷列表失败', [
  1248. 'status' => $response->status(),
  1249. 'response' => $response->body(),
  1250. ]);
  1251. return [];
  1252. } catch (\Exception $e) {
  1253. Log::error('获取试卷列表异常', [
  1254. 'error' => $e->getMessage(),
  1255. ]);
  1256. return [];
  1257. }
  1258. }
  1259. /**
  1260. * 获取指定试卷的题目
  1261. */
  1262. public function getPaperQuestions(string $paperId): array
  1263. {
  1264. try {
  1265. $response = Http::timeout(10)
  1266. ->get($this->baseUrl.'/papers/'.$paperId.'/questions');
  1267. if ($response->successful()) {
  1268. return $response->json('data', []);
  1269. }
  1270. Log::warning('获取试卷题目失败', [
  1271. 'paper_id' => $paperId,
  1272. 'status' => $response->status(),
  1273. 'response' => $response->body(),
  1274. ]);
  1275. return [];
  1276. } catch (\Exception $e) {
  1277. Log::error('获取试卷题目异常', [
  1278. 'paper_id' => $paperId,
  1279. 'error' => $e->getMessage(),
  1280. ]);
  1281. return [];
  1282. }
  1283. }
  1284. /**
  1285. * 【通用方法】获取题目的知识点信息
  1286. * 直接从MySQL的questions表查询
  1287. */
  1288. public function getQuestionKnowledgePoint(int $questionBankId): array
  1289. {
  1290. try {
  1291. // 直接从MySQL questions表查询题目
  1292. $question = \App\Models\Question::where('id', $questionBankId)->first();
  1293. if (! $question) {
  1294. Log::warning('QuestionBankService: MySQL中未找到题目', ['question_bank_id' => $questionBankId]);
  1295. return [
  1296. 'kp_code' => null,
  1297. 'kp_name' => null,
  1298. 'question_content' => '',
  1299. 'question_answer' => '',
  1300. 'question_type' => 'unknown',
  1301. ];
  1302. }
  1303. return [
  1304. 'kp_code' => $question->kp_code,
  1305. 'kp_name' => $question->kp_name ?? $question->kp_code,
  1306. 'question_content' => $question->stem ?? '',
  1307. 'question_answer' => $question->answer ?? '',
  1308. 'question_type' => $question->question_type ?? 'unknown',
  1309. ];
  1310. } catch (\Exception $e) {
  1311. Log::error('QuestionBankService: 获取题目知识点失败', [
  1312. 'question_bank_id' => $questionBankId,
  1313. 'error' => $e->getMessage(),
  1314. ]);
  1315. return [
  1316. 'kp_code' => null,
  1317. 'kp_name' => null,
  1318. 'question_content' => '',
  1319. 'question_answer' => '',
  1320. 'question_type' => 'unknown',
  1321. 'error' => $e->getMessage(),
  1322. ];
  1323. }
  1324. }
  1325. }