QuestionBankService.php 55 KB

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