QuestionBankService.php 55 KB

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