QuestionBankService.php 55 KB

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