QuestionBankService.php 53 KB

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