ExamPdfExportService.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. <?php
  2. namespace App\Services;
  3. use App\DTO\ExamAnalysisDataDto;
  4. use App\DTO\ReportPayloadDto;
  5. use App\Models\Paper;
  6. use App\Models\PaperQuestion;
  7. use App\Models\Student;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\File;
  11. use Illuminate\Support\Facades\Http;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Support\Facades\URL;
  15. use Symfony\Component\Process\Exception\ProcessSignaledException;
  16. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  17. use Symfony\Component\Process\Process;
  18. /**
  19. * PDF导出服务(重构版)
  20. * 负责生成试卷PDF、判卷PDF和学情报告PDF
  21. */
  22. class ExamPdfExportService
  23. {
  24. public function __construct(
  25. private readonly LearningAnalyticsService $learningAnalyticsService,
  26. private readonly QuestionBankService $questionBankService,
  27. private readonly QuestionServiceApi $questionServiceApi,
  28. private readonly PdfStorageService $pdfStorageService,
  29. private readonly MasteryCalculator $masteryCalculator
  30. ) {}
  31. /**
  32. * 生成试卷 PDF(不含答案)
  33. */
  34. public function generateExamPdf(string $paperId): ?string
  35. {
  36. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  37. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
  38. Log::info('generateExamPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  39. // 如果生成成功,将 URL 写入数据库
  40. if ($url) {
  41. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
  42. }
  43. return $url;
  44. }
  45. /**
  46. * 生成判卷 PDF(含答案与解析)
  47. */
  48. public function generateGradingPdf(string $paperId): ?string
  49. {
  50. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  51. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  52. Log::info('generateGradingPdf url 生成结果:', ['paper_id' => $paperId, 'url' => $url]);
  53. // 如果生成成功,将 URL 写入数据库
  54. if ($url) {
  55. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
  56. }
  57. return $url;
  58. }
  59. /**
  60. * 生成学情分析 PDF
  61. */
  62. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  63. {
  64. if (function_exists('set_time_limit')) {
  65. @set_time_limit(240);
  66. }
  67. try {
  68. // 【调试】打印输入参数
  69. Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
  70. 'paper_id' => $paperId,
  71. 'student_id' => $studentId,
  72. 'record_id' => $recordId,
  73. ]);
  74. // 构建分析数据
  75. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  76. if (!$analysisData) {
  77. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  78. 'paper_id' => $paperId,
  79. 'student_id' => $studentId,
  80. ]);
  81. return null;
  82. }
  83. Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
  84. 'paper_id' => $paperId,
  85. 'student_id' => $studentId,
  86. 'analysisData_keys' => array_keys($analysisData),
  87. 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
  88. 'questions_count' => count($analysisData['questions'] ?? []),
  89. ]);
  90. // 创建DTO
  91. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  92. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  93. // 【调试】打印传给模板的数据
  94. $templateData = $payloadDto->toArray();
  95. Log::info('ExamPdfExportService: 传给模板的数据', [
  96. 'paper' => $templateData['paper'] ?? null,
  97. 'student' => $templateData['student'] ?? null,
  98. 'mastery' => $templateData['mastery'] ?? null,
  99. 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null, // 新增:检查父节点掌握度
  100. 'questions_count' => count($templateData['questions'] ?? []),
  101. 'insights_count' => count($templateData['question_insights'] ?? []),
  102. 'recommendations_count' => count($templateData['recommendations'] ?? []),
  103. ]);
  104. // 渲染HTML
  105. $html = view('exam-analysis.pdf-report', $templateData)->render();
  106. if (!$html) {
  107. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  108. return null;
  109. }
  110. // 生成PDF
  111. $pdfBinary = $this->buildPdf($html);
  112. if (!$pdfBinary) {
  113. return null;
  114. }
  115. // 保存PDF
  116. $version = time();
  117. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  118. $url = $this->pdfStorageService->put($path, $pdfBinary);
  119. if (!$url) {
  120. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  121. return null;
  122. }
  123. // 保存URL到数据库
  124. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  125. return $url;
  126. } catch (\Throwable $e) {
  127. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  128. 'paper_id' => $paperId,
  129. 'student_id' => $studentId,
  130. 'record_id' => $recordId,
  131. 'error' => $e->getMessage(),
  132. 'exception' => get_class($e),
  133. 'trace' => $e->getTraceAsString(),
  134. ]);
  135. return null;
  136. }
  137. }
  138. /**
  139. * 渲染并存储试卷PDF
  140. */
  141. private function renderAndStoreExamPdf(
  142. string $paperId,
  143. bool $includeAnswer,
  144. string $suffix,
  145. bool $useGradingView = false
  146. ): ?string {
  147. // 放宽脚本执行时间
  148. if (function_exists('set_time_limit')) {
  149. @set_time_limit(240);
  150. }
  151. try {
  152. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  153. if (!$html) {
  154. Log::error('ExamPdfExportService: 渲染HTML为空', [
  155. 'paper_id' => $paperId,
  156. 'include_answer' => $includeAnswer,
  157. 'use_grading_view' => $useGradingView,
  158. ]);
  159. return null;
  160. }
  161. $pdfBinary = $this->buildPdf($html);
  162. if (!$pdfBinary) {
  163. Log::error('ExamPdfExportService: buildPdf为空', [
  164. 'paper_id' => $paperId,
  165. 'include_answer' => $includeAnswer,
  166. 'use_grading_view' => $useGradingView,
  167. ]);
  168. return null;
  169. }
  170. $path = "exams/{$paperId}_{$suffix}.pdf";
  171. $url = $this->pdfStorageService->put($path, $pdfBinary);
  172. if (!$url) {
  173. Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
  174. return null;
  175. }
  176. return $url;
  177. } catch (\Throwable $e) {
  178. Log::error('ExamPdfExportService: 生成PDF失败', [
  179. 'paper_id' => $paperId,
  180. 'suffix' => $suffix,
  181. 'error' => $e->getMessage(),
  182. 'exception' => get_class($e),
  183. 'trace' => $e->getTraceAsString(),
  184. ]);
  185. return null;
  186. }
  187. }
  188. /**
  189. * 渲染试卷HTML(重构版)
  190. */
  191. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  192. {
  193. // 直接构造请求URL,使用路由生成HTML
  194. $routeName = $useGradingView
  195. ? 'filament.admin.auth.intelligent-exam.grading'
  196. : 'filament.admin.auth.intelligent-exam.pdf';
  197. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  198. // 使用HTTP客户端获取渲染后的HTML
  199. try {
  200. $response = Http::get($url);
  201. if ($response->successful()) {
  202. $html = $response->body();
  203. if (!empty(trim($html))) {
  204. return $this->ensureUtf8Html($html);
  205. } else {
  206. Log::warning('ExamPdfExportService: HTTP返回的HTML为空,使用备用方案', [
  207. 'paper_id' => $paperId,
  208. 'url' => $url,
  209. ]);
  210. }
  211. }
  212. } catch (\Exception $e) {
  213. Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
  214. 'paper_id' => $paperId,
  215. 'error' => $e->getMessage(),
  216. ]);
  217. }
  218. // 备用方案:直接渲染视图(如果路由不可用)
  219. try {
  220. $paper = Paper::with('questions')->find($paperId);
  221. if (!$paper) {
  222. Log::error('ExamPdfExportService: 试卷不存在,备用方案无法渲染', [
  223. 'paper_id' => $paperId,
  224. 'include_answer' => $includeAnswer,
  225. 'use_grading_view' => $useGradingView,
  226. ]);
  227. return null;
  228. }
  229. // 检查试卷是否有题目
  230. if ($paper->questions->isEmpty()) {
  231. Log::error('ExamPdfExportService: 试卷没有题目数据', [
  232. 'paper_id' => $paperId,
  233. 'question_count' => 0,
  234. ]);
  235. return null;
  236. }
  237. $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
  238. $html = view($viewName, compact('paper'))->render();
  239. if (empty(trim($html))) {
  240. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  241. 'paper_id' => $paperId,
  242. 'view_name' => $viewName,
  243. 'question_count' => $paper->questions->count(),
  244. ]);
  245. return null;
  246. }
  247. return $this->ensureUtf8Html($html);
  248. } catch (\Exception $e) {
  249. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  250. 'paper_id' => $paperId,
  251. 'error' => $e->getMessage(),
  252. 'trace' => $e->getTraceAsString(),
  253. ]);
  254. return null;
  255. }
  256. }
  257. /**
  258. * 构建分析数据(重构版)
  259. * 优先使用本地MySQL数据,减少API依赖
  260. */
  261. private function buildAnalysisData(string $paperId, string $studentId): ?array
  262. {
  263. // 【关键调试】确认方法被调用
  264. Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
  265. 'paper_id' => $paperId,
  266. 'student_id' => $studentId,
  267. 'timestamp' => now()->toISOString()
  268. ]);
  269. $paper = Paper::with(['questions' => function ($query) {
  270. $query->orderBy('question_number')->orderBy('id');
  271. }])->find($paperId);
  272. if (!$paper) {
  273. Log::error('ExamPdfExportService: 未找到试卷', [
  274. 'paper_id' => $paperId,
  275. 'student_id' => $studentId,
  276. ]);
  277. return null;
  278. }
  279. $student = Student::find($studentId);
  280. $studentInfo = [
  281. 'id' => $student?->student_id ?? $studentId,
  282. 'name' => $student?->name ?? $studentId,
  283. 'grade' => $student?->grade ?? '未知年级',
  284. 'class' => $student?->class_name ?? '未知班级',
  285. ];
  286. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  287. $analysisData = [];
  288. // 首先尝试从paper->analysis_id获取
  289. if (!empty($paper->analysis_id)) {
  290. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  291. 'paper_id' => $paperId,
  292. 'student_id' => $studentId,
  293. 'analysis_id' => $paper->analysis_id
  294. ]);
  295. $analysisRecord = \DB::table('exam_analysis_results')
  296. ->where('id', $paper->analysis_id)
  297. ->where('student_id', $studentId)
  298. ->first();
  299. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  300. $analysisData = json_decode($analysisRecord->analysis_data, true);
  301. Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
  302. 'data_size' => strlen($analysisRecord->analysis_data)
  303. ]);
  304. } else {
  305. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  306. 'paper_id' => $paperId,
  307. 'student_id' => $studentId,
  308. 'analysis_id' => $paper->analysis_id
  309. ]);
  310. }
  311. }
  312. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  313. if (empty($analysisData)) {
  314. Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
  315. 'paper_id' => $paperId,
  316. 'student_id' => $studentId
  317. ]);
  318. $analysisRecord = \DB::table('exam_analysis_results')
  319. ->where('paper_id', $paperId)
  320. ->where('student_id', $studentId)
  321. ->first();
  322. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  323. $analysisData = json_decode($analysisRecord->analysis_data, true);
  324. Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
  325. 'data_size' => strlen($analysisRecord->analysis_data),
  326. 'question_count' => count($analysisData['question_analysis'] ?? [])
  327. ]);
  328. } else {
  329. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  330. 'paper_id' => $paperId,
  331. 'student_id' => $studentId
  332. ]);
  333. }
  334. }
  335. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  336. $masteryData = [];
  337. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  338. Log::info('ExamPdfExportService: 开始处理掌握度数据', [
  339. 'student_id' => $studentId,
  340. 'analysisData_keys' => array_keys($analysisData),
  341. 'has_knowledge_point_analysis' => !empty($analysisData['knowledge_point_analysis']),
  342. ]);
  343. if (!empty($analysisData['knowledge_point_analysis'])) {
  344. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  345. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  346. $masteryData[] = [
  347. 'kp_code' => $kp['kp_id'] ?? null,
  348. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  349. 'mastery_level' => $kp['mastery_level'] ?? 0,
  350. 'mastery_change' => $kp['change'] ?? null,
  351. ];
  352. }
  353. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  354. try {
  355. // 获取本次考试涉及的知识点代码列表
  356. $examKpCodes = array_column($masteryData, 'kp_code');
  357. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  358. 'count' => count($examKpCodes),
  359. 'kp_codes' => $examKpCodes
  360. ]);
  361. // 获取上一个快照的数据(用于计算变化)
  362. // 如果没有其他试卷的记录,使用同一试卷的上一次快照
  363. $lastSnapshot = DB::connection('mysql')
  364. ->table('knowledge_point_mastery_snapshots')
  365. ->where('student_id', $studentId)
  366. ->where('paper_id', $paper->paper_id)
  367. ->where('snapshot_id', '!=', "snap_{$paper->paper_id}_" . date('YmdHis'))
  368. ->latest('snapshot_time')
  369. ->first();
  370. $previousMasteryData = [];
  371. if ($lastSnapshot) {
  372. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  373. foreach ($previousMasteryJson as $kpCode => $data) {
  374. $previousMasteryData[$kpCode] = [
  375. 'current_mastery' => $data['current_mastery'] ?? 0,
  376. 'previous_mastery' => $data['previous_mastery'] ?? null,
  377. ];
  378. }
  379. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  380. 'snapshot_time' => $lastSnapshot->snapshot_time,
  381. 'kp_count' => count($previousMasteryData)
  382. ]);
  383. }
  384. // 为当前知识点添加变化数据
  385. foreach ($masteryData as &$item) {
  386. $kpCode = $item['kp_code'];
  387. if (isset($previousMasteryData[$kpCode])) {
  388. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery'] ?? 0);
  389. $current = floatval($item['mastery_level']);
  390. $item['mastery_change'] = $current - $previous;
  391. }
  392. }
  393. unset($item); // 解除引用
  394. // 获取所有父节点掌握度
  395. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  396. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  397. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  398. $parentMasteryLevels = [];
  399. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  400. // 检查这个父节点是否有子节点在本次考试中出现
  401. $hasRelevantChild = false;
  402. foreach ($examKpCodes as $childKpCode) {
  403. if (str_starts_with($childKpCode, $parentKpCode)) {
  404. $hasRelevantChild = true;
  405. break;
  406. }
  407. }
  408. if ($hasRelevantChild) {
  409. // 【修复】计算父节点变化:基于所有子节点的平均变化
  410. $childChanges = [];
  411. foreach ($examKpCodes as $childKpCode) {
  412. if (str_starts_with($childKpCode, $parentKpCode)) {
  413. $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
  414. $currentChild = null;
  415. foreach ($masteryData as $item) {
  416. if ($item['kp_code'] === $childKpCode) {
  417. $currentChild = $item['mastery_level'];
  418. break;
  419. }
  420. }
  421. if ($previousChild !== null && $currentChild !== null) {
  422. $childChanges[] = floatval($currentChild) - floatval($previousChild);
  423. }
  424. }
  425. }
  426. $avgChange = !empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
  427. $parentMasteryLevels[$parentKpCode] = [
  428. 'mastery_level' => $parentMastery,
  429. 'mastery_change' => $avgChange,
  430. ];
  431. }
  432. }
  433. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  434. 'all_parent_count' => count($allParentMasteryLevels),
  435. 'filtered_parent_count' => count($parentMasteryLevels),
  436. 'filtered_codes' => array_keys($parentMasteryLevels)
  437. ]);
  438. } catch (\Exception $e) {
  439. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  440. 'error' => $e->getMessage()
  441. ]);
  442. }
  443. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  444. 'count' => count($masteryData),
  445. 'masteryData_sample' => !empty($masteryData) ? array_slice($masteryData, 0, 2) : []
  446. ]);
  447. } else {
  448. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  449. try {
  450. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  451. 'student_id' => $studentId
  452. ]);
  453. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  454. $masteryData = $masteryOverview['details'] ?? [];
  455. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  456. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  457. if (!empty($masteryData) && is_array($masteryData)) {
  458. $masteryData = array_map(function($item) {
  459. if (is_object($item)) {
  460. return [
  461. 'kp_code' => $item->kp_code ?? null,
  462. 'kp_name' => $item->kp_name ?? null,
  463. 'mastery_level' => floatval($item->mastery_level ?? 0),
  464. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  465. ];
  466. }
  467. return $item;
  468. }, $masteryData);
  469. }
  470. // 【修复】获取快照数据以计算掌握度变化
  471. $lastSnapshot = DB::connection('mysql')
  472. ->table('knowledge_point_mastery_snapshots')
  473. ->where('student_id', $studentId)
  474. ->latest('snapshot_time')
  475. ->first();
  476. if ($lastSnapshot) {
  477. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  478. foreach ($masteryData as &$item) {
  479. $kpCode = $item['kp_code'];
  480. if (isset($previousMasteryJson[$kpCode])) {
  481. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  482. $current = floatval($item['mastery_level']);
  483. $item['mastery_change'] = $current - $previous;
  484. }
  485. }
  486. unset($item);
  487. }
  488. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  489. 'count' => count($masteryData),
  490. 'parent_count' => count($parentMasteryLevels)
  491. ]);
  492. } catch (\Exception $e) {
  493. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  494. 'student_id' => $studentId,
  495. 'error' => $e->getMessage()
  496. ]);
  497. }
  498. }
  499. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  500. $recommendations = [];
  501. try {
  502. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  503. 'student_id' => $studentId
  504. ]);
  505. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  506. $recommendations = $learningPaths['recommendations'] ?? [];
  507. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  508. 'count' => count($recommendations)
  509. ]);
  510. } catch (\Exception $e) {
  511. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  512. 'student_id' => $studentId,
  513. 'error' => $e->getMessage()
  514. ]);
  515. }
  516. // 获取知识点名称映射
  517. $kpNameMap = $this->buildKnowledgePointNameMap();
  518. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  519. 'kpNameMap_count' => count($kpNameMap),
  520. 'kpNameMap_keys_sample' => !empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : []
  521. ]);
  522. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  523. $questionDetails = $this->getQuestionDetailsFromMySQL($paper);
  524. // 处理题目数据
  525. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  526. // 【关键调试】查看buildMasterySummary的返回结果
  527. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  528. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  529. 'masteryData_count' => count($masteryData),
  530. 'kpNameMap_count' => count($kpNameMap),
  531. 'masterySummary_keys' => array_keys($masterySummary),
  532. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  533. 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
  534. ]);
  535. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  536. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  537. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
  538. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  539. 'raw_count' => count($parentMasteryLevels),
  540. 'processed_count' => count($processedParentMastery),
  541. 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
  542. ]);
  543. return [
  544. 'paper' => [
  545. 'id' => $paper->paper_id,
  546. 'name' => $paper->paper_name,
  547. 'total_questions' => $paper->question_count,
  548. 'total_score' => $paper->total_score,
  549. 'created_at' => $paper->created_at,
  550. ],
  551. 'student' => $studentInfo,
  552. 'questions' => $questions,
  553. 'mastery' => $masterySummary,
  554. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  555. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  556. 'recommendations' => $recommendations,
  557. 'analysis_data' => $analysisData,
  558. ];
  559. }
  560. /**
  561. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  562. */
  563. private function getQuestionDetailsFromMySQL(Paper $paper): array
  564. {
  565. $details = [];
  566. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  567. 'paper_id' => $paper->paper_id,
  568. 'question_count' => $paper->questions->count()
  569. ]);
  570. foreach ($paper->questions as $pq) {
  571. try {
  572. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  573. $detail = [
  574. 'id' => $pq->question_id,
  575. 'content' => $pq->question_text,
  576. 'question_type' => $pq->question_type,
  577. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  578. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  579. ];
  580. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  581. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  582. 'paper_question_id' => $pq->id,
  583. 'question_id' => $pq->question_id,
  584. 'has_answer' => !empty($pq->correct_answer),
  585. 'has_solution' => !empty($pq->solution),
  586. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
  587. ]);
  588. } catch (\Throwable $e) {
  589. Log::error('ExamPdfExportService: 获取题目详情失败', [
  590. 'paper_question_id' => $pq->id,
  591. 'error' => $e->getMessage(),
  592. ]);
  593. }
  594. }
  595. return $details;
  596. }
  597. /**
  598. * 处理题目数据(用于报告)
  599. */
  600. private function processQuestionsForReport(Paper $paper, array $questionDetails, array $kpNameMap): array
  601. {
  602. $grouped = [
  603. 'choice' => [],
  604. 'fill' => [],
  605. 'answer' => [],
  606. ];
  607. $sortedQuestions = $paper->questions
  608. ->sortBy(function (PaperQuestion $q, int $idx) {
  609. $number = $q->question_number ?? $idx + 1;
  610. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  611. });
  612. foreach ($sortedQuestions as $idx => $question) {
  613. $kpCode = $question->knowledge_point ?? '';
  614. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  615. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  616. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  617. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  618. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  619. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  620. $normalizedType = $this->normalizeQuestionType($typeRaw);
  621. $number = $question->question_number ?? ($idx + 1);
  622. $payload = [
  623. 'question_number' => $number,
  624. 'question_text' => is_array($question->question_text)
  625. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  626. : ($question->question_text ?? ''),
  627. 'question_type' => $normalizedType,
  628. 'knowledge_point' => $kpCode,
  629. 'knowledge_point_name' => $kpName,
  630. 'score' => $question->score,
  631. 'answer' => $answer, // 正确答案
  632. 'solution' => $solution, // 解题思路
  633. 'student_answer' => $question->student_answer ?? null, // 【新增】学生答案
  634. 'correct_answer' => $answer, // 【新增】正确答案
  635. 'is_correct' => $question->is_correct ?? null, // 【新增】判分结果
  636. 'score_obtained' => $question->score_obtained ?? null, // 【新增】得分
  637. ];
  638. $grouped[$normalizedType][] = $payload;
  639. // 【调试】记录题目数据
  640. Log::debug('ExamPdfExportService: 处理题目数据', [
  641. 'paper_question_id' => $question->id,
  642. 'question_id' => $question->question_id,
  643. 'has_answer' => !empty($answer),
  644. 'has_solution' => !empty($solution),
  645. 'answer_preview' => $answer ? substr($answer, 0, 50) : null
  646. ]);
  647. }
  648. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  649. // 按卷面顺序重新编号
  650. foreach ($ordered as $i => &$q) {
  651. $q['display_number'] = $i + 1;
  652. }
  653. unset($q);
  654. return $ordered;
  655. }
  656. /**
  657. * 构建PDF
  658. */
  659. private function buildPdf(string $html): ?string
  660. {
  661. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  662. $utf8Html = $this->ensureUtf8Html($html);
  663. file_put_contents($tmpHtml, $utf8Html);
  664. // 仅使用Chrome渲染
  665. $chromePdf = $this->renderWithChrome($tmpHtml);
  666. @unlink($tmpHtml);
  667. return $chromePdf;
  668. }
  669. /**
  670. * 使用Chrome渲染PDF
  671. */
  672. private function renderWithChrome(string $htmlPath): ?string
  673. {
  674. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  675. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  676. $chromeBinary = $this->findChromeBinary();
  677. if (!$chromeBinary) {
  678. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  679. return null;
  680. }
  681. // 设置运行时目录
  682. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  683. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  684. if (!File::exists($runtimeHome)) {
  685. @File::makeDirectory($runtimeHome, 0755, true);
  686. }
  687. if (!File::exists($runtimeXdg)) {
  688. @File::makeDirectory($runtimeXdg, 0755, true);
  689. }
  690. $process = new Process([
  691. $chromeBinary,
  692. '--headless',
  693. '--disable-gpu',
  694. '--no-sandbox',
  695. '--disable-setuid-sandbox',
  696. '--disable-dev-shm-usage',
  697. '--no-zygote',
  698. '--disable-features=VizDisplayCompositor',
  699. '--disable-software-rasterizer',
  700. '--disable-extensions',
  701. '--disable-background-networking',
  702. '--disable-component-update',
  703. '--disable-client-side-phishing-detection',
  704. '--disable-default-apps',
  705. '--disable-domain-reliability',
  706. '--disable-sync',
  707. '--safebrowsing-disable-auto-update',
  708. '--no-first-run',
  709. '--no-default-browser-check',
  710. '--disable-crash-reporter',
  711. '--disable-print-preview',
  712. '--disable-features=PrintHeaderFooter',
  713. '--disable-features=TranslateUI',
  714. '--disable-features=OptimizationHints',
  715. '--disable-ipc-flooding-protection',
  716. '--disable-background-networking',
  717. '--disable-background-timer-throttling',
  718. '--disable-backgrounding-occluded-windows',
  719. '--disable-renderer-backgrounding',
  720. '--disable-features=AudioServiceOutOfProcess',
  721. '--user-data-dir=' . $userDataDir,
  722. '--print-to-pdf=' . $tmpPdf,
  723. '--print-to-pdf-no-header',
  724. '--allow-file-access-from-files',
  725. 'file://' . $htmlPath,
  726. ], null, [
  727. 'HOME' => $runtimeHome,
  728. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  729. ]);
  730. $process->setTimeout(60);
  731. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  732. try {
  733. $startedAt = microtime(true);
  734. $process->start();
  735. $pdfGenerated = false;
  736. // 轮询检测PDF是否生成
  737. $pollStart = microtime(true);
  738. $maxPollSeconds = 30;
  739. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  740. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  741. $pdfGenerated = true;
  742. $process->stop(5, $killSignal);
  743. break;
  744. }
  745. usleep(200_000);
  746. }
  747. if ($process->isRunning()) {
  748. $process->stop(5, $killSignal);
  749. }
  750. $process->wait();
  751. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  752. if ($process->isRunning()) {
  753. $process->stop(5, $killSignal);
  754. }
  755. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  756. } catch (\Throwable $e) {
  757. if ($process->isRunning()) {
  758. $process->stop(5, $killSignal);
  759. }
  760. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  761. }
  762. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  763. }
  764. /**
  765. * 处理Chrome进程结果
  766. */
  767. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  768. {
  769. $pdfExists = file_exists($tmpPdf);
  770. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  771. if (!$process->isSuccessful()) {
  772. if ($pdfExists && $pdfSize > 0) {
  773. Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
  774. 'exit_code' => $process->getExitCode(),
  775. 'tmp_pdf_size' => $pdfSize,
  776. ]);
  777. } else {
  778. Log::error('ExamPdfExportService: Chrome渲染失败', [
  779. 'exit_code' => $process->getExitCode(),
  780. 'error' => $process->getErrorOutput(),
  781. ]);
  782. @unlink($tmpPdf);
  783. File::deleteDirectory($userDataDir);
  784. return null;
  785. }
  786. }
  787. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  788. @unlink($tmpPdf);
  789. File::deleteDirectory($userDataDir);
  790. return $pdfBinary ?: null;
  791. }
  792. /**
  793. * 查找Chrome二进制文件
  794. */
  795. private function findChromeBinary(): ?string
  796. {
  797. $candidates = [
  798. env('PDF_CHROME_BINARY'),
  799. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  800. '/usr/bin/google-chrome-stable',
  801. '/usr/bin/google-chrome',
  802. '/usr/bin/chromium-browser',
  803. '/usr/bin/chromium',
  804. ];
  805. foreach ($candidates as $path) {
  806. if ($path && is_file($path) && is_executable($path)) {
  807. return $path;
  808. }
  809. }
  810. return null;
  811. }
  812. /**
  813. * 确保HTML为UTF-8编码
  814. */
  815. private function ensureUtf8Html(string $html): string
  816. {
  817. $meta = '<meta charset="UTF-8">';
  818. if (stripos($html, '<head>') !== false) {
  819. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  820. }
  821. return $meta . $html;
  822. }
  823. /**
  824. * 构建知识点名称映射
  825. */
  826. private function buildKnowledgePointNameMap(): array
  827. {
  828. try {
  829. $options = $this->questionServiceApi->getKnowledgePointOptions();
  830. return $options ?: [];
  831. } catch (\Throwable $e) {
  832. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  833. 'error' => $e->getMessage(),
  834. ]);
  835. return [];
  836. }
  837. }
  838. /**
  839. * 构建掌握度摘要
  840. */
  841. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  842. {
  843. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  844. 'masteryData_count' => count($masteryData),
  845. 'kpNameMap_count' => count($kpNameMap)
  846. ]);
  847. $items = [];
  848. $total = 0;
  849. $count = 0;
  850. foreach ($masteryData as $row) {
  851. $code = $row['kp_code'] ?? null;
  852. // 【修复】使用kpNameMap转换名称为友好显示名
  853. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  854. $level = (float)($row['mastery_level'] ?? 0);
  855. $delta = $row['mastery_change'] ?? null;
  856. $items[] = [
  857. 'kp_code' => $code,
  858. 'kp_name' => $name,
  859. 'mastery_level' => $level,
  860. 'mastery_change' => $delta,
  861. ];
  862. $total += $level;
  863. $count++;
  864. }
  865. $average = $count > 0 ? round($total / $count, 2) : null;
  866. // 按掌握度从低到高排序
  867. if (!empty($items)) {
  868. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  869. }
  870. $result = [
  871. 'items' => $items,
  872. 'average' => $average,
  873. 'weak_list' => array_slice($items, 0, 5),
  874. ];
  875. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  876. 'total_count' => $count,
  877. 'items_count' => count($items)
  878. ]);
  879. return $result;
  880. }
  881. /**
  882. * 标准化题型
  883. */
  884. private function normalizeQuestionType(string $type): string
  885. {
  886. $t = strtolower(trim($type));
  887. return match (true) {
  888. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  889. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  890. default => 'answer',
  891. };
  892. }
  893. /**
  894. * 保存PDF URL到数据库
  895. */
  896. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  897. {
  898. try {
  899. $paper = Paper::where('paper_id', $paperId)->first();
  900. if ($paper) {
  901. $paper->update([$field => $url]);
  902. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  903. 'paper_id' => $paperId,
  904. 'field' => $field,
  905. 'url' => $url,
  906. ]);
  907. }
  908. } catch (\Throwable $e) {
  909. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  910. 'paper_id' => $paperId,
  911. 'field' => $field,
  912. 'error' => $e->getMessage(),
  913. ]);
  914. }
  915. }
  916. /**
  917. * 保存学情分析PDF URL
  918. */
  919. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  920. {
  921. try {
  922. if ($recordId) {
  923. // OCR记录
  924. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  925. if ($ocrRecord) {
  926. $ocrRecord->update(['analysis_pdf_url' => $url]);
  927. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  928. 'record_id' => $recordId,
  929. 'paper_id' => $paperId,
  930. 'student_id' => $studentId,
  931. 'url' => $url,
  932. ]);
  933. }
  934. } else {
  935. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  936. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  937. ->where('student_id', $studentId)
  938. ->where('paper_id', $paperId)
  939. ->update([
  940. 'analysis_pdf_url' => $url,
  941. 'updated_at' => now(),
  942. ]);
  943. if ($updated) {
  944. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  945. 'student_id' => $studentId,
  946. 'paper_id' => $paperId,
  947. 'url' => $url,
  948. 'updated_rows' => $updated,
  949. ]);
  950. } else {
  951. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  952. 'student_id' => $studentId,
  953. 'paper_id' => $paperId,
  954. ]);
  955. }
  956. // 学生记录 - 使用新的 student_reports 表(备用)
  957. \App\Models\StudentReport::updateOrCreate(
  958. [
  959. 'student_id' => $studentId,
  960. 'report_type' => 'exam_analysis',
  961. 'paper_id' => $paperId,
  962. ],
  963. [
  964. 'pdf_url' => $url,
  965. 'generation_status' => 'completed',
  966. 'generated_at' => now(),
  967. 'updated_at' => now(),
  968. ]
  969. );
  970. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  971. 'student_id' => $studentId,
  972. 'paper_id' => $paperId,
  973. 'url' => $url,
  974. ]);
  975. }
  976. } catch (\Throwable $e) {
  977. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  978. 'paper_id' => $paperId,
  979. 'student_id' => $studentId,
  980. 'record_id' => $recordId,
  981. 'error' => $e->getMessage(),
  982. ]);
  983. }
  984. }
  985. /**
  986. * 【修复】处理父节点掌握度数据
  987. * 1. 过滤掉掌握度为0或null的父节点
  988. * 2. 将kp_code转换为友好的kp_name
  989. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  990. */
  991. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
  992. {
  993. $processed = [];
  994. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  995. // 兼容不同数据结构:可能是数组或数字
  996. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  997. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  998. // 过滤零值和空值
  999. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1000. continue;
  1001. }
  1002. // 获取友好名称
  1003. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1004. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1005. $processed[$kpCode] = [
  1006. 'kp_code' => $kpCode,
  1007. 'kp_name' => $kpName,
  1008. 'mastery_level' => round(floatval($masteryLevel), 4),
  1009. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1010. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1011. // 【修复】只获取本次考试涉及的子节点
  1012. 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
  1013. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1014. ];
  1015. }
  1016. // 按掌握度降序排序
  1017. uasort($processed, function($a, $b) {
  1018. return $b['mastery_level'] <=> $a['mastery_level'];
  1019. });
  1020. return $processed;
  1021. }
  1022. /**
  1023. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1024. */
  1025. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
  1026. {
  1027. $children = [];
  1028. try {
  1029. $childCodes = DB::connection('mysql')
  1030. ->table('knowledge_points')
  1031. ->where('parent_kp_code', $parentKpCode)
  1032. ->pluck('kp_code')
  1033. ->toArray();
  1034. foreach ($childCodes as $childCode) {
  1035. // 只包含本次考试涉及的知识点
  1036. if (in_array($childCode, $examKpCodes)) {
  1037. $children[] = [
  1038. 'kp_code' => $childCode,
  1039. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1040. ];
  1041. }
  1042. }
  1043. } catch (\Exception $e) {
  1044. Log::warning('获取子知识点失败', [
  1045. 'parent_kp_code' => $parentKpCode,
  1046. 'error' => $e->getMessage(),
  1047. ]);
  1048. }
  1049. return $children;
  1050. }
  1051. /**
  1052. * 计算知识点层级深度
  1053. */
  1054. private function calculateKnowledgePointLevel(string $kpCode): int
  1055. {
  1056. // 根据kp_code前缀判断层级深度
  1057. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  1058. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  1059. return 1; // 一级分类,如 M, S, E, G
  1060. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  1061. return 2; // 二级分类,如 M01, S02
  1062. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  1063. return 3; // 三级分类,如 M01A, S02B
  1064. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  1065. return 4; // 四级分类,如 M01A1
  1066. }
  1067. return 1; // 默认一级
  1068. }
  1069. }