QuestionBankService.php 54 KB

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