QuestionBankService.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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 App\Services\PaperIdGenerator;
  8. class QuestionBankService
  9. {
  10. protected string $baseUrl;
  11. protected int $timeout;
  12. protected int $retry;
  13. protected int $retryDelay;
  14. protected string $mode;
  15. public function __construct()
  16. {
  17. $this->baseUrl = '';
  18. $this->timeout = (int) config('question_bank.timeout', 60);
  19. $this->retry = (int) config('question_bank.retry', 2);
  20. $this->retryDelay = (int) config('question_bank.retry_delay', 500);
  21. $this->mode = 'local';
  22. }
  23. private function http()
  24. {
  25. return Http::timeout($this->timeout)
  26. ->retry($this->retry, $this->retryDelay);
  27. }
  28. /**
  29. * 从题目内容中提取选项
  30. */
  31. private function extractOptions(string $content): array
  32. {
  33. // 匹配 A. B. C. D. 格式的选项
  34. if (preg_match_all('/([A-D])\.\s*(.+?)(?=[A-D]\.|$)/s', $content, $matches, PREG_SET_ORDER)) {
  35. $options = [];
  36. foreach ($matches as $match) {
  37. $optionText = trim($match[2]);
  38. // 移除末尾的换行和空白
  39. $optionText = preg_replace('/\s+$/', '', $optionText);
  40. $options[] = $optionText;
  41. }
  42. return $options;
  43. }
  44. return [];
  45. }
  46. /**
  47. * 分离题干内容和选项
  48. */
  49. private function separateStemAndOptions(string $content): array
  50. {
  51. // 如果没有选项,直接返回
  52. if (!preg_match('/[A-D]\.\s+/m', $content)) {
  53. return [$content, []];
  54. }
  55. // 提取选项
  56. $options = $this->extractOptions($content);
  57. // 提取题干(选项前的部分)
  58. $stem = preg_replace('/[A-D]\.\s+.+?(?=[A-D]\.|$)/s', '', $content);
  59. $stem = trim($stem);
  60. // 移除末尾的括号或空白
  61. $stem = preg_replace('/()\s*$/', '', $stem);
  62. $stem = trim($stem);
  63. return [$stem, $options];
  64. }
  65. /**
  66. * 获取题目列表
  67. */
  68. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  69. {
  70. if ($this->useLocal()) {
  71. return $this->local()->listQuestions($page, $perPage, $filters);
  72. }
  73. try {
  74. $response = $this->http()
  75. ->get($this->baseUrl . '/questions', [
  76. 'page' => $page,
  77. 'per_page' => $perPage,
  78. ...$filters
  79. ]);
  80. if ($response->successful()) {
  81. info("QuestionBankService::listQuestions", [$response->json()]);
  82. return $response->json();
  83. }
  84. Log::warning('题库API调用失败', [
  85. 'status' => $response->status()
  86. ]);
  87. } catch (\Exception $e) {
  88. Log::error('获取题目列表失败', [
  89. 'error' => $e->getMessage()
  90. ]);
  91. }
  92. return ['data' => [], 'meta' => ['total' => 0]];
  93. }
  94. /**
  95. * 获取题目详情
  96. */
  97. public function getQuestion(string $questionCode): ?array
  98. {
  99. if ($this->useLocal()) {
  100. return $this->local()->getQuestionByCode($questionCode);
  101. }
  102. try {
  103. $response = $this->http()
  104. ->get($this->baseUrl . "/questions/{$questionCode}");
  105. if ($response->successful()) {
  106. return $response->json();
  107. }
  108. Log::warning('获取题目详情失败', [
  109. 'code' => $questionCode,
  110. 'status' => $response->status()
  111. ]);
  112. } catch (\Exception $e) {
  113. Log::error('获取题目详情异常', [
  114. 'code' => $questionCode,
  115. 'error' => $e->getMessage()
  116. ]);
  117. }
  118. return null;
  119. }
  120. /**
  121. * 更新题目
  122. */
  123. public function updateQuestion(string $questionCode, array $payload): bool
  124. {
  125. if ($this->useLocal()) {
  126. return $this->local()->updateQuestionByCode($questionCode, $payload);
  127. }
  128. try {
  129. $response = Http::timeout(10)
  130. ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
  131. if ($response->successful()) {
  132. return true;
  133. }
  134. Log::warning('更新题目失败', [
  135. 'code' => $questionCode,
  136. 'status' => $response->status(),
  137. 'body' => $response->json(),
  138. ]);
  139. } catch (\Exception $e) {
  140. Log::error('更新题目异常', [
  141. 'code' => $questionCode,
  142. 'error' => $e->getMessage()
  143. ]);
  144. }
  145. return false;
  146. }
  147. /**
  148. * 筛选题目 (支持 kp_codes, skills 等高级筛选)
  149. */
  150. public function filterQuestions(array $params): array
  151. {
  152. if ($this->useLocal()) {
  153. return $this->local()->listQuestions(
  154. (int) ($params['page'] ?? 1),
  155. (int) ($params['per_page'] ?? 50),
  156. $params
  157. );
  158. }
  159. try {
  160. $response = Http::timeout(30)
  161. ->get($this->baseUrl . '/questions', $params);
  162. if ($response->successful()) {
  163. info("QuestionBankService::filterQuestions", [$response->json()]);
  164. return $response->json();
  165. }
  166. Log::warning('筛选题目API调用失败', [
  167. 'status' => $response->status(),
  168. 'params' => $params
  169. ]);
  170. } catch (\Exception $e) {
  171. Log::error('筛选题目异常', [
  172. 'error' => $e->getMessage(),
  173. 'params' => $params
  174. ]);
  175. }
  176. return ['data' => []];
  177. }
  178. /**
  179. * 批量获取题目详情(根据题目 ID 列表)
  180. */
  181. public function getQuestionsByIds(array $ids): array
  182. {
  183. if (empty($ids)) {
  184. return ['data' => []];
  185. }
  186. if ($this->useLocal()) {
  187. return $this->local()->getQuestionsByIds($ids);
  188. }
  189. try {
  190. $response = $this->http()
  191. ->get($this->baseUrl . '/questions', [
  192. 'ids' => implode(',', $ids),
  193. ]);
  194. if ($response->successful()) {
  195. return $response->json();
  196. }
  197. Log::warning('批量获取题目失败', [
  198. 'ids' => $ids,
  199. 'status' => $response->status(),
  200. ]);
  201. } catch (\Exception $e) {
  202. Log::error('批量获取题目异常', [
  203. 'ids' => $ids,
  204. 'error' => $e->getMessage(),
  205. ]);
  206. }
  207. return ['data' => []];
  208. }
  209. /**
  210. * 智能生成题目(异步模式)
  211. */
  212. public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
  213. {
  214. if ($this->useLocal()) {
  215. return $this->local()->generateQuestions($params);
  216. }
  217. try {
  218. // 添加回调 URL
  219. if ($callbackUrl) {
  220. $params['callback_url'] = $callbackUrl;
  221. }
  222. // 注意:这里的请求实际上是同步的,会等待响应
  223. // 真正的异步应该使用 Http::async()
  224. $response = $this->http()
  225. ->post($this->baseUrl . '/ai/generate-intelligent-questions', $params);
  226. if ($response->successful()) {
  227. return $response->json();
  228. }
  229. Log::warning('题目生成API调用失败', [
  230. 'status' => $response->status(),
  231. 'body' => $response->body()
  232. ]);
  233. } catch (\Illuminate\Http\Client\ConnectionException $e) {
  234. // 连接超时或网络错误
  235. Log::error('题目生成连接异常', [
  236. 'error' => $e->getMessage(),
  237. 'message' => '可能的原因:1. AI服务未启动 2. 网络连接问题 3. 服务负载过高'
  238. ]);
  239. return [
  240. 'success' => false,
  241. 'message' => '连接AI服务失败,请检查服务是否正常运行'
  242. ];
  243. } catch (\Exception $e) {
  244. Log::error('题目生成异常', [
  245. 'error' => $e->getMessage(),
  246. 'trace' => $e->getTraceAsString()
  247. ]);
  248. }
  249. return ['success' => false, 'message' => '生成失败'];
  250. }
  251. /**
  252. * 获取任务状态
  253. */
  254. public function getTaskStatus(string $taskId): ?array
  255. {
  256. if ($this->useLocal()) {
  257. return null;
  258. }
  259. try {
  260. $response = Http::timeout(10)
  261. ->get($this->baseUrl . '/tasks/' . $taskId);
  262. if ($response->successful()) {
  263. return $response->json();
  264. }
  265. Log::warning('获取任务状态失败', [
  266. 'task_id' => $taskId,
  267. 'status' => $response->status()
  268. ]);
  269. } catch (\Exception $e) {
  270. Log::error('获取任务状态异常', [
  271. 'task_id' => $taskId,
  272. 'error' => $e->getMessage()
  273. ]);
  274. }
  275. return null;
  276. }
  277. /**
  278. * 获取任务列表
  279. */
  280. public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
  281. {
  282. if ($this->useLocal()) {
  283. return ['data' => [], 'meta' => ['total' => 0]];
  284. }
  285. try {
  286. $params = [
  287. 'page' => $page,
  288. 'per_page' => $perPage
  289. ];
  290. if ($status) {
  291. $params['status'] = $status;
  292. }
  293. $response = Http::timeout(10)
  294. ->get($this->baseUrl . '/tasks', $params);
  295. if ($response->successful()) {
  296. return $response->json();
  297. }
  298. Log::warning('获取任务列表失败', [
  299. 'status' => $response->status()
  300. ]);
  301. } catch (\Exception $e) {
  302. Log::error('获取任务列表异常', [
  303. 'error' => $e->getMessage()
  304. ]);
  305. }
  306. return ['data' => [], 'meta' => ['total' => 0]];
  307. }
  308. /**
  309. * 获取题目统计信息
  310. */
  311. public function getStatistics(): array
  312. {
  313. if ($this->useLocal()) {
  314. return $this->local()->getStatistics();
  315. }
  316. try {
  317. $response = Http::timeout(10)
  318. ->get($this->baseUrl . '/questions/statistics');
  319. if ($response->successful()) {
  320. return $response->json();
  321. }
  322. Log::warning('获取题目统计失败', [
  323. 'status' => $response->status()
  324. ]);
  325. } catch (\Exception $e) {
  326. Log::error('获取题目统计异常', [
  327. 'error' => $e->getMessage()
  328. ]);
  329. }
  330. return [
  331. 'total' => 0,
  332. 'by_difficulty' => [],
  333. 'by_kp' => [],
  334. 'by_source' => []
  335. ];
  336. }
  337. /**
  338. * 根据知识点获取题目
  339. */
  340. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  341. {
  342. if ($this->useLocal()) {
  343. return $this->local()->getQuestionsByKpCode($kpCode, $limit);
  344. }
  345. try {
  346. $response = Http::timeout(10)
  347. ->get($this->baseUrl . '/questions', [
  348. 'kp_code' => $kpCode,
  349. 'limit' => $limit
  350. ]);
  351. if ($response->successful()) {
  352. return $response->json();
  353. }
  354. } catch (\Exception $e) {
  355. Log::error('根据知识点获取题目失败', [
  356. 'kp_code' => $kpCode,
  357. 'error' => $e->getMessage()
  358. ]);
  359. }
  360. return [];
  361. }
  362. /**
  363. * 删除题目
  364. */
  365. public function deleteQuestion(string $questionCode): bool
  366. {
  367. if ($this->useLocal()) {
  368. return $this->local()->deleteQuestionByCode($questionCode);
  369. }
  370. try {
  371. $response = Http::timeout(10)
  372. ->delete($this->baseUrl . "/questions/{$questionCode}");
  373. // 只有返回204(删除成功)才返回true,404(不存在)返回false
  374. if ($response->status() === 204) {
  375. return true;
  376. }
  377. if ($response->status() === 404) {
  378. Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
  379. return false;
  380. }
  381. return false;
  382. } catch (\Exception $e) {
  383. Log::error('删除题目失败', [
  384. 'question_code' => $questionCode,
  385. 'error' => $e->getMessage()
  386. ]);
  387. return false;
  388. }
  389. }
  390. /**
  391. * 智能选择试卷题目
  392. */
  393. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  394. {
  395. if ($this->useLocal()) {
  396. return $this->local()->selectQuestionsForExam($totalQuestions, $filters);
  397. }
  398. $logFile = __DIR__ . '/../../../../select_questions.log';
  399. $startTime = microtime(true);
  400. try {
  401. $requestData = [
  402. 'total_questions' => $totalQuestions,
  403. 'filters' => $filters
  404. ];
  405. $logMsg = "=== " . date('Y-m-d H:i:s') . " ===\n";
  406. $logMsg .= "开始调用 selectQuestionsForExam\n";
  407. $logMsg .= "baseUrl: " . $this->baseUrl . "\n";
  408. $logMsg .= "totalQuestions: $totalQuestions\n";
  409. $logMsg .= "filters: " . json_encode($filters) . "\n\n";
  410. file_put_contents($logFile, $logMsg, FILE_APPEND);
  411. $response = Http::timeout(30)
  412. ->post($this->baseUrl . '/exam/select-questions', $requestData);
  413. $logMsg = "API响应:\n";
  414. $logMsg .= " status: " . $response->status() . "\n";
  415. $logMsg .= " successful: " . ($response->successful() ? 'true' : 'false') . "\n";
  416. $logMsg .= " body: " . $response->body() . "\n\n";
  417. file_put_contents($logFile, $logMsg, FILE_APPEND);
  418. if ($response->successful()) {
  419. $data = $response->json('data', []);
  420. $logMsg = "成功解析JSON:\n";
  421. $logMsg .= " data字段题目数量: " . count($data) . "\n";
  422. $logMsg .= " 耗时: " . round((microtime(true) - $startTime) * 1000, 2) . "ms\n\n";
  423. file_put_contents($logFile, $logMsg, FILE_APPEND);
  424. return $data;
  425. }
  426. $logMsg = "API调用失败! 状态码: " . $response->status() . "\n";
  427. $logMsg .= "响应内容: " . $response->body() . "\n\n";
  428. file_put_contents($logFile, $logMsg, FILE_APPEND);
  429. } catch (\Exception $e) {
  430. $logMsg = "异常: " . $e->getMessage() . "\n";
  431. $logMsg .= "堆栈: " . $e->getTraceAsString() . "\n\n";
  432. file_put_contents($logFile, $logMsg, FILE_APPEND);
  433. }
  434. $logMsg = "返回空数组\n";
  435. $logMsg .= "=== 结束 ===\n\n";
  436. file_put_contents($logFile, $logMsg, FILE_APPEND);
  437. return [];
  438. }
  439. /**
  440. * 保存试卷到数据库(本地 papers 表)
  441. */
  442. public function saveExamToDatabase(array $examData): ?string
  443. {
  444. $logFile = __DIR__ . '/../../../../save_exam.log';
  445. $logMsg = "=== " . date('Y-m-d H:i:s') . " ===\n";
  446. $logMsg .= "saveExamToDatabase 被调用\n";
  447. $logMsg .= "questions_count: " . count($examData['questions'] ?? []) . "\n";
  448. $logMsg .= "paper_name: " . ($examData['paper_name'] ?? 'N/A') . "\n";
  449. $logMsg .= "student_id: " . ($examData['student_id'] ?? 'N/A') . "\n";
  450. if (!empty($examData['questions'])) {
  451. $logMsg .= "first_question_id: " . ($examData['questions'][0]['id'] ?? 'N/A') . "\n";
  452. }
  453. file_put_contents($logFile, $logMsg, FILE_APPEND);
  454. // 数据完整性检查
  455. if (empty($examData['questions'])) {
  456. $logMsg = "❌ 题目为空,返回null!\n";
  457. $logMsg .= "这是导致生成demo ID的原因!\n\n";
  458. file_put_contents($logFile, $logMsg, FILE_APPEND);
  459. return null;
  460. }
  461. try {
  462. // 使用数据库事务确保数据一致性
  463. return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
  464. // 使用行业标准的Snowflake ID生成12位唯一数字ID
  465. $uniqueId = PaperIdGenerator::generate();
  466. $paperId = 'paper_' . $uniqueId;
  467. Log::info('开始保存试卷到数据库', [
  468. 'paper_id' => $paperId,
  469. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  470. 'question_count' => count($examData['questions'])
  471. ]);
  472. // 使用Laravel模型保存到 papers 表
  473. $paper = \App\Models\Paper::create([
  474. 'paper_id' => $paperId,
  475. 'student_id' => $examData['student_id'] ?? '',
  476. 'teacher_id' => $examData['teacher_id'] ?? '',
  477. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  478. 'paper_type' => 'auto_generated',
  479. 'total_questions' => count($examData['questions']), // 使用实际题目数量
  480. 'total_score' => $examData['total_score'] ?? 0,
  481. 'status' => 'draft',
  482. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  483. ]);
  484. // 获取所有题目的正确答案
  485. $questionBankIds = array_filter(array_map(function($q) {
  486. return $q['id'] ?? $q['question_id'] ?? null;
  487. }, $examData['questions']));
  488. $correctAnswersMap = [];
  489. if (!empty($questionBankIds)) {
  490. Log::info('从本地题库获取题目正确答案', [
  491. 'paper_id' => $paperId,
  492. 'question_bank_ids' => $questionBankIds
  493. ]);
  494. $localQuestions = Question::query()
  495. ->whereIn('id', array_values($questionBankIds))
  496. ->get(['id', 'answer']);
  497. foreach ($localQuestions as $detail) {
  498. $correctAnswersMap[$detail->id] = $detail->answer ?? '';
  499. }
  500. }
  501. // 准备题目数据
  502. $questionInsertData = [];
  503. foreach ($examData['questions'] as $index => $question) {
  504. // 验证题目基本数据
  505. if (empty($question['stem']) && empty($question['content'])) {
  506. Log::warning('跳过没有内容的题目', [
  507. 'paper_id' => $paperId,
  508. 'question_index' => $index
  509. ]);
  510. continue;
  511. }
  512. // 处理题目内容:分离题干和选项(如果存在)
  513. $rawContent = $question['stem'] ?? $question['content'] ?? '';
  514. list($stem, $options) = $this->separateStemAndOptions($rawContent);
  515. // 将选项以换行符形式附加到题干末尾,方便后续渲染
  516. if (!empty($options)) {
  517. $stemWithOptions = $stem . "\n" . implode("\n", array_map(function($opt, $idx) {
  518. return chr(65 + $idx) . '. ' . $opt;
  519. }, $options, array_keys($options)));
  520. $question['stem'] = $stemWithOptions;
  521. $question['options'] = $options;
  522. } else {
  523. $question['stem'] = $stem;
  524. }
  525. // 处理难度字段:如果是字符串则转换为数字
  526. $difficultyValue = $question['difficulty'] ?? 0.5;
  527. if (is_string($difficultyValue)) {
  528. // 将中文难度转换为数字
  529. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  530. $difficultyValue = 0.3;
  531. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  532. $difficultyValue = 0.6;
  533. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  534. $difficultyValue = 0.9;
  535. } else {
  536. $difficultyValue = 0.5;
  537. }
  538. }
  539. // 确保 knowledge_point 有值
  540. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  541. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  542. $knowledgePoint = $question['kp_code'];
  543. }
  544. // 获取题目类型
  545. $questionType = $this->normalizeQuestionTypeValue($question['question_type'] ?? $question['type'] ?? 'answer');
  546. if (!$questionType) {
  547. // 如果没有类型,根据内容推断
  548. $content = $question['stem'] ?? $question['content'] ?? '';
  549. if (is_string($content)) {
  550. // 1. 优先检查填空题(下划线)
  551. if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  552. $questionType = 'fill';
  553. }
  554. // 2. 检查选择题(必须有选项 A. B. C. D.)
  555. elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
  556. if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
  557. $questionType = 'choice';
  558. } else {
  559. // 只有括号没有选项,可能是填空
  560. if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  561. $questionType = 'fill';
  562. } else {
  563. $questionType = 'answer';
  564. }
  565. }
  566. }
  567. // 3. 检查纯括号填空
  568. elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  569. $questionType = 'fill';
  570. }
  571. else {
  572. $questionType = 'answer';
  573. }
  574. } else {
  575. $questionType = 'answer';
  576. }
  577. }
  578. // 获取正确答案
  579. $questionBankId = $question['id'] ?? $question['question_id'] ?? null;
  580. $correctAnswer = $correctAnswersMap[$questionBankId] ?? $question['answer'] ?? $question['correct_answer'] ?? '';
  581. $questionInsertData[] = [
  582. 'paper_id' => $paperId,
  583. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  584. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  585. 'knowledge_point' => $knowledgePoint,
  586. 'question_type' => $questionType,
  587. 'question_text' => is_array($question['stem'] ?? null) ? json_encode($question['stem'], JSON_UNESCAPED_UNICODE) : ($question['stem'] ?? $question['content'] ?? $question['question_text'] ?? ''),
  588. 'correct_answer' => is_array($correctAnswer) ? json_encode($correctAnswer, JSON_UNESCAPED_UNICODE) : $correctAnswer, // 保存正确答案
  589. 'solution' => is_array($question['solution'] ?? null) ? json_encode($question['solution'], JSON_UNESCAPED_UNICODE) : ($question['solution'] ?? ''), // 保存解题思路
  590. 'difficulty' => $difficultyValue,
  591. 'score' => $question['score'] ?? 5, // 默认5分
  592. 'estimated_time' => $question['estimated_time'] ?? 300,
  593. 'question_number' => $index + 1,
  594. ];
  595. }
  596. // 验证是否有有效的题目数据
  597. if (empty($questionInsertData)) {
  598. Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
  599. throw new \Exception('没有有效的题目数据');
  600. }
  601. // 调试:检查第一个题目的solution字段
  602. if (!empty($questionInsertData)) {
  603. $firstQuestion = $questionInsertData[0];
  604. Log::debug('试卷保存调试 - 第一个题目', [
  605. 'paper_id' => $paperId,
  606. 'question_id' => $firstQuestion['question_id'] ?? '',
  607. 'question_bank_id' => $firstQuestion['question_bank_id'] ?? '',
  608. 'has_solution' => !empty($firstQuestion['solution']),
  609. 'solution_length' => strlen($firstQuestion['solution'] ?? ''),
  610. 'solution_preview' => substr($firstQuestion['solution'] ?? '', 0, 80)
  611. ]);
  612. }
  613. // 使用Laravel模型批量插入题目数据
  614. \App\Models\PaperQuestion::insert($questionInsertData);
  615. // 验证插入结果,使用关联关系
  616. $insertedQuestionCount = $paper->questions()->count();
  617. if ($insertedQuestionCount !== count($questionInsertData)) {
  618. throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
  619. }
  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. }