QuestionBankService.php 55 KB

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