QuestionBankService.php 55 KB

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