QuestionBankService.php 53 KB

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