QuestionBankService.php 52 KB

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