ExamPdfExportService.php 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  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. private readonly PdfMerger $pdfMerger
  31. ) {}
  32. /**
  33. * 确保exams目录存在
  34. */
  35. private function ensureExamsDirectory(): bool
  36. {
  37. $examsDir = storage_path("app/public/exams");
  38. if (!is_dir($examsDir)) {
  39. Log::info('ExamPdfExportService: 创建exams目录', ['path' => $examsDir]);
  40. if (!mkdir($examsDir, 0755, true)) {
  41. Log::error('ExamPdfExportService: 创建exams目录失败', ['path' => $examsDir]);
  42. return false;
  43. }
  44. Log::info('ExamPdfExportService: exams目录创建成功', ['path' => $examsDir]);
  45. }
  46. return true;
  47. }
  48. /**
  49. * 生成试卷 PDF(不含答案)
  50. */
  51. public function generateExamPdf(string $paperId): ?string
  52. {
  53. Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
  54. // 返回页面URL(用于数据库保存)
  55. $pageUrl = route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  56. Log::info('generateExamPdf 页面URL:', ['paper_id' => $paperId, 'url' => $pageUrl]);
  57. // 将页面URL写入数据库
  58. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $pageUrl);
  59. // 生成PDF文件(用于合并,不上传云存储)
  60. $pdfPath = storage_path("app/public/exams/{$paperId}_exam.pdf");
  61. // 【修复】确保exams目录存在
  62. if (!$this->ensureExamsDirectory()) {
  63. return null;
  64. }
  65. Log::info('ExamPdfExportService: 开始生成试卷PDF', ['path' => $pdfPath, 'url' => $pageUrl]);
  66. $pdfBinary = $this->buildPdfFromUrl($pageUrl);
  67. if (!$pdfBinary) {
  68. Log::error('ExamPdfExportService: 生成试卷PDF失败', ['url' => $pageUrl]);
  69. return null;
  70. }
  71. Log::info('ExamPdfExportService: PDF生成成功,开始写入文件', ['path' => $pdfPath, 'size' => strlen($pdfBinary)]);
  72. $result = file_put_contents($pdfPath, $pdfBinary);
  73. if ($result === false) {
  74. Log::error('ExamPdfExportService: 写入试卷PDF文件失败', ['path' => $pdfPath]);
  75. return null;
  76. }
  77. // 【关键修复】验证文件是否真的写入成功
  78. if (!file_exists($pdfPath)) {
  79. Log::error('ExamPdfExportService: 文件写入后不存在', ['path' => $pdfPath, 'result' => $result]);
  80. return null;
  81. }
  82. Log::info('ExamPdfExportService: 试卷PDF文件写入成功', ['path' => $pdfPath, 'size' => $result]);
  83. // 返回页面URL(不是PDF URL)
  84. return $pageUrl;
  85. }
  86. /**
  87. * 生成判卷 PDF(含答案与解析)
  88. */
  89. public function generateGradingPdf(string $paperId): ?string
  90. {
  91. Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
  92. // 返回页面URL(用于数据库保存)
  93. $pageUrl = route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  94. Log::info('generateGradingPdf 页面URL:', ['paper_id' => $paperId, 'url' => $pageUrl]);
  95. // 将页面URL写入数据库
  96. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $pageUrl);
  97. // 生成PDF文件(用于合并,不上传云存储)
  98. $pdfPath = storage_path("app/public/exams/{$paperId}_grading.pdf");
  99. // 【修复】确保exams目录存在
  100. if (!$this->ensureExamsDirectory()) {
  101. return null;
  102. }
  103. Log::info('ExamPdfExportService: 开始生成判卷PDF', ['path' => $pdfPath, 'url' => $pageUrl]);
  104. $pdfBinary = $this->buildPdfFromUrl($pageUrl);
  105. if (!$pdfBinary) {
  106. Log::error('ExamPdfExportService: 生成判卷PDF失败', ['url' => $pageUrl]);
  107. return null;
  108. }
  109. Log::info('ExamPdfExportService: 判卷PDF生成成功,开始写入文件', ['path' => $pdfPath, 'size' => strlen($pdfBinary)]);
  110. $result = file_put_contents($pdfPath, $pdfBinary);
  111. if ($result === false) {
  112. Log::error('ExamPdfExportService: 写入判卷PDF文件失败', ['path' => $pdfPath]);
  113. return null;
  114. }
  115. // 【关键修复】验证文件是否真的写入成功
  116. if (!file_exists($pdfPath)) {
  117. Log::error('ExamPdfExportService: 判卷文件写入后不存在', ['path' => $pdfPath, 'result' => $result]);
  118. return null;
  119. }
  120. Log::info('ExamPdfExportService: 判卷PDF文件写入成功', ['path' => $pdfPath, 'size' => $result]);
  121. // 返回页面URL(不是PDF URL)
  122. return $pageUrl;
  123. }
  124. /**
  125. * 生成合并PDF(试卷 + 判卷)
  126. * 先分别生成两个PDF,然后合并
  127. * 【优化】添加进度回调支持和快速合并模式
  128. * 【修复】优化临时文件清理逻辑,确保合并成功后才删除源文件
  129. */
  130. public function generateMergedPdf(string $paperId, ?callable $progressCallback = null): ?string
  131. {
  132. Log::info('generateMergedPdf 开始:', ['paper_id' => $paperId]);
  133. // 【新增】快速幂等性检查:如果all_pdf_url已存在,直接返回
  134. $existingPaper = \App\Models\Paper::where('paper_id', $paperId)->first();
  135. if ($existingPaper && $existingPaper->all_pdf_url) {
  136. Log::info('【快速返回】合并PDF已存在,无需重新生成', [
  137. 'paper_id' => $paperId,
  138. 'existing_url' => $existingPaper->all_pdf_url
  139. ]);
  140. if ($progressCallback) {
  141. $progressCallback(100, '合并PDF已存在,直接返回');
  142. }
  143. return $existingPaper->all_pdf_url;
  144. }
  145. if ($progressCallback) {
  146. $progressCallback(0, '准备合并PDF...');
  147. }
  148. $tempDir = storage_path("app/temp");
  149. if (!is_dir($tempDir)) {
  150. mkdir($tempDir, 0755, true);
  151. }
  152. $examPdfPath = null;
  153. $gradingPdfPath = null;
  154. $mergedPdfPath = null;
  155. $mergeSuccess = false;
  156. $uploadSuccess = false;
  157. try {
  158. // 【修复】不重复生成PDF,直接使用已有的文件
  159. // 假设PDF已经通过generateExamPdf和generateGradingPdf生成过了
  160. // 获取数据库中的页面URL(用于记录)
  161. $paper = \App\Models\Paper::where('paper_id', $paperId)->first();
  162. $examPdfUrl = $paper?->exam_pdf_url;
  163. $gradingPdfUrl = $paper?->grading_pdf_url;
  164. if (!$examPdfUrl || !$gradingPdfUrl) {
  165. Log::warning('ExamPdfExportService: 未找到PDF页面URL,可能尚未生成', [
  166. 'paper_id' => $paperId,
  167. 'exam_pdf_url' => $examPdfUrl,
  168. 'grading_pdf_url' => $gradingPdfUrl
  169. ]);
  170. }
  171. Log::info('使用本地PDF文件进行合并', [
  172. 'exam_url' => $examPdfUrl,
  173. 'grading_url' => $gradingPdfUrl
  174. ]);
  175. if ($progressCallback) {
  176. $progressCallback(10, '验证PDF文件...');
  177. }
  178. // 直接使用本地PDF文件
  179. $examPdfPath = storage_path("app/public/exams/{$paperId}_exam.pdf");
  180. $gradingPdfPath = storage_path("app/public/exams/{$paperId}_grading.pdf");
  181. // 验证文件是否存在
  182. Log::info('ExamPdfExportService: 检查PDF文件是否存在', [
  183. 'exam_pdf' => $examPdfPath,
  184. 'exam_exists' => file_exists($examPdfPath),
  185. 'grading_pdf' => $gradingPdfPath,
  186. 'grading_exists' => file_exists($gradingPdfPath)
  187. ]);
  188. if (!file_exists($examPdfPath)) {
  189. Log::error('ExamPdfExportService: 试卷PDF文件不存在', [
  190. 'path' => $examPdfUrl,
  191. 'local_path' => $examPdfPath,
  192. 'directory_exists' => is_dir(dirname($examPdfPath)),
  193. 'directory_contents' => is_dir(dirname($examPdfPath)) ? scandir(dirname($examPdfPath)) : null
  194. ]);
  195. return null;
  196. }
  197. if (!file_exists($gradingPdfPath)) {
  198. Log::error('ExamPdfExportService: 判卷PDF文件不存在', [
  199. 'path' => $gradingPdfUrl,
  200. 'local_path' => $gradingPdfPath,
  201. 'directory_exists' => is_dir(dirname($gradingPdfPath)),
  202. 'directory_contents' => is_dir(dirname($gradingPdfPath)) ? scandir(dirname($gradingPdfPath)) : null
  203. ]);
  204. return null;
  205. }
  206. $examSize = filesize($examPdfPath);
  207. $gradingSize = filesize($gradingPdfPath);
  208. Log::info('PDF文件验证成功', [
  209. 'exam_pdf' => $examPdfPath,
  210. 'grading_pdf' => $gradingPdfPath,
  211. 'exam_size' => $examSize,
  212. 'grading_size' => $gradingSize,
  213. 'total_size' => $examSize + $gradingSize
  214. ]);
  215. if ($examSize < 1000 || $gradingSize < 1000) {
  216. Log::warning('ExamPdfExportService: PDF文件过小,可能生成不完整', [
  217. 'exam_size' => $examSize,
  218. 'grading_size' => $gradingSize
  219. ]);
  220. }
  221. if ($progressCallback) {
  222. $progressCallback(20, '开始合并PDF文件...');
  223. }
  224. // 【优化】合并PDF文件 - 使用快速合并模式
  225. $mergedPdfPath = $tempDir . "/{$paperId}_merged.pdf";
  226. $merged = $this->pdfMerger->mergeWithProgress([$examPdfPath, $gradingPdfPath], $mergedPdfPath, $progressCallback);
  227. if (!$merged) {
  228. Log::error('ExamPdfExportService: PDF文件合并失败', [
  229. 'tool' => $this->pdfMerger->getMergeTool(),
  230. 'exam_pdf' => $examPdfPath,
  231. 'grading_pdf' => $gradingPdfPath,
  232. 'output_pdf' => $mergedPdfPath
  233. ]);
  234. return null;
  235. }
  236. // 【新增】验证合并后的PDF内容
  237. if (!file_exists($mergedPdfPath)) {
  238. Log::error('ExamPdfExportService: 合并后PDF文件不存在', ['path' => $mergedPdfPath]);
  239. return null;
  240. }
  241. $mergedSize = filesize($mergedPdfPath);
  242. Log::info('ExamPdfExportService: 合并PDF验证', [
  243. 'merged_pdf' => $mergedPdfPath,
  244. 'merged_size' => $mergedSize,
  245. 'expected_min_size' => max($examSize, $gradingSize) + 1000,
  246. 'size_valid' => $mergedSize > max($examSize, $gradingSize)
  247. ]);
  248. // 验证合并后的PDF大小是否合理(应该大于任一源文件)
  249. if ($mergedSize <= max($examSize, $gradingSize)) {
  250. Log::warning('ExamPdfExportService: 合并PDF大小异常,可能合并失败', [
  251. 'merged_size' => $mergedSize,
  252. 'exam_size' => $examSize,
  253. 'grading_size' => $gradingSize,
  254. 'max_source_size' => max($examSize, $gradingSize)
  255. ]);
  256. }
  257. $mergeSuccess = true;
  258. if ($progressCallback) {
  259. $progressCallback(80, '上传合并PDF...');
  260. }
  261. // 读取合并后的PDF内容并上传到云存储
  262. $mergedPdfContent = file_get_contents($mergedPdfPath);
  263. if (strlen($mergedPdfContent) < 1000) {
  264. Log::error('ExamPdfExportService: 合并PDF内容过小,上传失败', [
  265. 'content_size' => strlen($mergedPdfContent),
  266. 'file_size' => $mergedSize
  267. ]);
  268. return null;
  269. }
  270. $path = "exams/{$paperId}_all.pdf";
  271. $mergedUrl = $this->pdfStorageService->put($path, $mergedPdfContent);
  272. if (!$mergedUrl) {
  273. Log::error('ExamPdfExportService: 保存合并PDF失败', ['path' => $path]);
  274. return null;
  275. }
  276. Log::info('ExamPdfExportService: 合并PDF上传成功', [
  277. 'url' => $mergedUrl,
  278. 'content_size' => strlen($mergedPdfContent),
  279. 'file_size' => $mergedSize
  280. ]);
  281. $uploadSuccess = true;
  282. // 保存到数据库的all_pdf_url字段
  283. $this->saveAllPdfUrlToDatabase($paperId, $mergedUrl);
  284. Log::info('generateMergedPdf 完成:', [
  285. 'paper_id' => $paperId,
  286. 'url' => $mergedUrl,
  287. 'tool' => $this->pdfMerger->getMergeTool(),
  288. 'exam_size' => $examSize,
  289. 'grading_size' => $gradingSize,
  290. 'merged_size' => $mergedSize
  291. ]);
  292. return $mergedUrl;
  293. } catch (\Throwable $e) {
  294. Log::error('ExamPdfExportService: 生成合并PDF失败', [
  295. 'paper_id' => $paperId,
  296. 'error' => $e->getMessage(),
  297. 'trace' => $e->getTraceAsString(),
  298. ]);
  299. if ($progressCallback) {
  300. $progressCallback(-1, '合并PDF失败: ' . $e->getMessage());
  301. }
  302. return null;
  303. } finally {
  304. // 【修复】优化临时文件清理逻辑:
  305. // 1. 合并失败时不删除源文件,便于重试
  306. // 2. 合并成功后不立即删除源文件,保留2小时用于调试
  307. // 3. 保留合并后的文件30分钟用于调试
  308. if ($mergeSuccess && $uploadSuccess) {
  309. // 【优化】合并成功且上传成功,不立即删除源文件
  310. // 改为设置未来删除时间,让源文件保留2小时
  311. $sourceFiles = [$examPdfPath, $gradingPdfPath];
  312. foreach ($sourceFiles as $file) {
  313. if ($file && file_exists($file)) {
  314. // 设置2小时后删除
  315. $deletionTime = time() + 7200; // 2小时 = 7200秒
  316. @touch($file, $deletionTime);
  317. Log::info('源PDF文件将在2小时后自动删除', [
  318. 'path' => $file,
  319. 'deletion_time' => date('Y-m-d H:i:s', $deletionTime)
  320. ]);
  321. }
  322. }
  323. // 保留合并文件30分钟后删除
  324. if ($mergedPdfPath && file_exists($mergedPdfPath)) {
  325. $deletionTime = time() + 1800; // 30分钟后
  326. @touch($mergedPdfPath, $deletionTime);
  327. Log::info('合并PDF文件保留30分钟用于调试', [
  328. 'path' => $mergedPdfPath,
  329. 'deletion_time' => date('Y-m-d H:i:s', $deletionTime)
  330. ]);
  331. }
  332. } else {
  333. // 合并失败或上传失败,保留所有文件用于调试
  334. Log::warning('PDF合并未完全成功,保留临时文件用于调试', [
  335. 'merge_success' => $mergeSuccess,
  336. 'upload_success' => $uploadSuccess,
  337. 'exam_pdf' => $examPdfPath,
  338. 'grading_pdf' => $gradingPdfPath,
  339. 'merged_pdf' => $mergedPdfPath,
  340. 'exam_exists' => $examPdfPath ? file_exists($examPdfPath) : false,
  341. 'grading_exists' => $gradingPdfPath ? file_exists($gradingPdfPath) : false,
  342. 'merged_exists' => $mergedPdfPath ? file_exists($mergedPdfPath) : false
  343. ]);
  344. }
  345. Log::debug('PDF合并流程完成', [
  346. 'merge_success' => $mergeSuccess,
  347. 'upload_success' => $uploadSuccess
  348. ]);
  349. }
  350. }
  351. /**
  352. * 将URL转换为本地文件路径
  353. */
  354. private function convertUrlToPath(string $url): ?string
  355. {
  356. // 如果是本地存储,URL格式类似:/storage/exams/paper_id_exam.pdf
  357. // 需要转换为绝对路径
  358. if (strpos($url, '/storage/') === 0) {
  359. return public_path(ltrim($url, '/'));
  360. }
  361. // 如果是完整路径,直接返回
  362. if (strpos($url, '/') === 0 && file_exists($url)) {
  363. return $url;
  364. }
  365. // 如果是相对路径,转换为绝对路径
  366. $path = public_path($url);
  367. if (file_exists($path)) {
  368. return $path;
  369. }
  370. return null;
  371. }
  372. /**
  373. * 保存合并PDF URL到数据库
  374. */
  375. private function saveAllPdfUrlToDatabase(string $paperId, string $url): void
  376. {
  377. try {
  378. \App\Models\Paper::where('paper_id', $paperId)->update([
  379. 'all_pdf_url' => $url
  380. ]);
  381. Log::debug('保存all_pdf_url成功', ['paper_id' => $paperId, 'url' => $url]);
  382. } catch (\Exception $e) {
  383. Log::error('保存all_pdf_url失败', [
  384. 'paper_id' => $paperId,
  385. 'url' => $url,
  386. 'error' => $e->getMessage()
  387. ]);
  388. throw $e;
  389. }
  390. }
  391. /**
  392. * 生成学情分析 PDF
  393. */
  394. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  395. {
  396. if (function_exists('set_time_limit')) {
  397. @set_time_limit(240);
  398. }
  399. try {
  400. // 【调试】打印输入参数
  401. Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
  402. 'paper_id' => $paperId,
  403. 'student_id' => $studentId,
  404. 'record_id' => $recordId,
  405. ]);
  406. // 构建分析数据
  407. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  408. if (!$analysisData) {
  409. Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
  410. 'paper_id' => $paperId,
  411. 'student_id' => $studentId,
  412. ]);
  413. return null;
  414. }
  415. Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
  416. 'paper_id' => $paperId,
  417. 'student_id' => $studentId,
  418. 'analysisData_keys' => array_keys($analysisData),
  419. 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
  420. 'questions_count' => count($analysisData['questions'] ?? []),
  421. ]);
  422. // 创建DTO
  423. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  424. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  425. // 【调试】打印传给模板的数据
  426. $templateData = $payloadDto->toArray();
  427. Log::info('ExamPdfExportService: 传给模板的数据', [
  428. 'paper' => $templateData['paper'] ?? null,
  429. 'student' => $templateData['student'] ?? null,
  430. 'mastery' => $templateData['mastery'] ?? null,
  431. 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null, // 新增:检查父节点掌握度
  432. 'questions_count' => count($templateData['questions'] ?? []),
  433. 'insights_count' => count($templateData['question_insights'] ?? []),
  434. 'recommendations_count' => count($templateData['recommendations'] ?? []),
  435. ]);
  436. // 渲染HTML
  437. $html = view('exam-analysis.pdf-report', $templateData)->render();
  438. if (!$html) {
  439. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  440. return null;
  441. }
  442. // 生成PDF
  443. $pdfBinary = $this->buildPdf($html);
  444. if (!$pdfBinary) {
  445. return null;
  446. }
  447. // 保存PDF
  448. $version = time();
  449. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  450. $url = $this->pdfStorageService->put($path, $pdfBinary);
  451. if (!$url) {
  452. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  453. return null;
  454. }
  455. // 保存URL到数据库
  456. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  457. return $url;
  458. } catch (\Throwable $e) {
  459. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  460. 'paper_id' => $paperId,
  461. 'student_id' => $studentId,
  462. 'record_id' => $recordId,
  463. 'error' => $e->getMessage(),
  464. 'exception' => get_class($e),
  465. 'trace' => $e->getTraceAsString(),
  466. ]);
  467. return null;
  468. }
  469. }
  470. /**
  471. * 渲染并存储试卷PDF
  472. */
  473. private function renderAndStoreExamPdf(
  474. string $paperId,
  475. bool $includeAnswer,
  476. string $suffix,
  477. bool $useGradingView = false
  478. ): ?string {
  479. // 放宽脚本执行时间
  480. if (function_exists('set_time_limit')) {
  481. @set_time_limit(240);
  482. }
  483. try {
  484. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  485. if (!$html) {
  486. Log::error('ExamPdfExportService: 渲染HTML为空', [
  487. 'paper_id' => $paperId,
  488. 'include_answer' => $includeAnswer,
  489. 'use_grading_view' => $useGradingView,
  490. ]);
  491. return null;
  492. }
  493. $pdfBinary = $this->buildPdf($html);
  494. if (!$pdfBinary) {
  495. Log::error('ExamPdfExportService: buildPdf为空', [
  496. 'paper_id' => $paperId,
  497. 'include_answer' => $includeAnswer,
  498. 'use_grading_view' => $useGradingView,
  499. ]);
  500. return null;
  501. }
  502. $path = "exams/{$paperId}_{$suffix}.pdf";
  503. $url = $this->pdfStorageService->put($path, $pdfBinary);
  504. if (!$url) {
  505. Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
  506. return null;
  507. }
  508. return $url;
  509. } catch (\Throwable $e) {
  510. Log::error('ExamPdfExportService: 生成PDF失败', [
  511. 'paper_id' => $paperId,
  512. 'suffix' => $suffix,
  513. 'error' => $e->getMessage(),
  514. 'exception' => get_class($e),
  515. 'trace' => $e->getTraceAsString(),
  516. ]);
  517. return null;
  518. }
  519. }
  520. /**
  521. * 渲染试卷HTML(重构版)
  522. */
  523. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  524. {
  525. // 直接构造请求URL,使用路由生成HTML
  526. $routeName = $useGradingView
  527. ? 'filament.admin.auth.intelligent-exam.grading'
  528. : 'filament.admin.auth.intelligent-exam.pdf';
  529. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  530. // 使用HTTP客户端获取渲染后的HTML
  531. try {
  532. $response = Http::get($url);
  533. if ($response->successful()) {
  534. $html = $response->body();
  535. if (!empty(trim($html))) {
  536. return $this->ensureUtf8Html($html);
  537. } else {
  538. Log::warning('ExamPdfExportService: HTTP返回的HTML为空,使用备用方案', [
  539. 'paper_id' => $paperId,
  540. 'url' => $url,
  541. ]);
  542. }
  543. }
  544. } catch (\Exception $e) {
  545. Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
  546. 'paper_id' => $paperId,
  547. 'error' => $e->getMessage(),
  548. ]);
  549. }
  550. // 备用方案:直接渲染视图(如果路由不可用)
  551. try {
  552. $paper = Paper::with('questions')->find($paperId);
  553. if (!$paper) {
  554. Log::error('ExamPdfExportService: 试卷不存在,备用方案无法渲染', [
  555. 'paper_id' => $paperId,
  556. 'include_answer' => $includeAnswer,
  557. 'use_grading_view' => $useGradingView,
  558. ]);
  559. return null;
  560. }
  561. // 检查试卷是否有题目
  562. if ($paper->questions->isEmpty()) {
  563. Log::error('ExamPdfExportService: 试卷没有题目数据', [
  564. 'paper_id' => $paperId,
  565. 'question_count' => 0,
  566. ]);
  567. return null;
  568. }
  569. $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
  570. $html = view($viewName, compact('paper'))->render();
  571. if (empty(trim($html))) {
  572. Log::error('ExamPdfExportService: 视图渲染结果为空', [
  573. 'paper_id' => $paperId,
  574. 'view_name' => $viewName,
  575. 'question_count' => $paper->questions->count(),
  576. ]);
  577. return null;
  578. }
  579. return $this->ensureUtf8Html($html);
  580. } catch (\Exception $e) {
  581. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  582. 'paper_id' => $paperId,
  583. 'error' => $e->getMessage(),
  584. 'trace' => $e->getTraceAsString(),
  585. ]);
  586. return null;
  587. }
  588. }
  589. /**
  590. * 构建分析数据(重构版)
  591. * 优先使用本地MySQL数据,减少API依赖
  592. */
  593. private function buildAnalysisData(string $paperId, string $studentId): ?array
  594. {
  595. // 【关键调试】确认方法被调用
  596. Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
  597. 'paper_id' => $paperId,
  598. 'student_id' => $studentId,
  599. 'timestamp' => now()->toISOString()
  600. ]);
  601. $paper = Paper::with(['questions' => function ($query) {
  602. $query->orderBy('question_number')->orderBy('id');
  603. }])->find($paperId);
  604. if (!$paper) {
  605. Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
  606. 'paper_id' => $paperId,
  607. 'student_id' => $studentId,
  608. ]);
  609. // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
  610. $paper = new \stdClass();
  611. $paper->paper_id = $paperId;
  612. $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
  613. $paper->question_count = 0;
  614. $paper->total_score = 0;
  615. $paper->created_at = now();
  616. $paper->questions = collect();
  617. }
  618. $student = Student::find($studentId);
  619. $studentInfo = [
  620. 'id' => $student?->student_id ?? $studentId,
  621. 'name' => $student?->name ?? $studentId,
  622. 'grade' => $student?->grade ?? '未知年级',
  623. 'class' => $student?->class_name ?? '未知班级',
  624. ];
  625. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  626. $analysisData = [];
  627. // 首先尝试从paper->analysis_id获取
  628. if (!empty($paper->analysis_id)) {
  629. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  630. 'paper_id' => $paperId,
  631. 'student_id' => $studentId,
  632. 'analysis_id' => $paper->analysis_id
  633. ]);
  634. $analysisRecord = \DB::table('exam_analysis_results')
  635. ->where('id', $paper->analysis_id)
  636. ->where('student_id', $studentId)
  637. ->first();
  638. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  639. $analysisData = json_decode($analysisRecord->analysis_data, true);
  640. Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
  641. 'data_size' => strlen($analysisRecord->analysis_data)
  642. ]);
  643. } else {
  644. Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
  645. 'paper_id' => $paperId,
  646. 'student_id' => $studentId,
  647. 'analysis_id' => $paper->analysis_id
  648. ]);
  649. }
  650. }
  651. // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
  652. if (empty($analysisData)) {
  653. Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
  654. 'paper_id' => $paperId,
  655. 'student_id' => $studentId
  656. ]);
  657. $analysisRecord = \DB::table('exam_analysis_results')
  658. ->where('paper_id', $paperId)
  659. ->where('student_id', $studentId)
  660. ->first();
  661. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  662. $analysisData = json_decode($analysisRecord->analysis_data, true);
  663. Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
  664. 'data_size' => strlen($analysisRecord->analysis_data),
  665. 'question_count' => count($analysisData['question_analysis'] ?? [])
  666. ]);
  667. } else {
  668. Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
  669. 'paper_id' => $paperId,
  670. 'student_id' => $studentId
  671. ]);
  672. }
  673. }
  674. // 【修复】优先使用analysisData中的knowledge_point_analysis数据
  675. $masteryData = [];
  676. $parentMasteryLevels = []; // 新增:父节点掌握度数据
  677. Log::info('ExamPdfExportService: 开始处理掌握度数据', [
  678. 'student_id' => $studentId,
  679. 'analysisData_keys' => array_keys($analysisData),
  680. 'has_knowledge_point_analysis' => !empty($analysisData['knowledge_point_analysis']),
  681. ]);
  682. if (!empty($analysisData['knowledge_point_analysis'])) {
  683. // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
  684. foreach ($analysisData['knowledge_point_analysis'] as $kp) {
  685. $masteryData[] = [
  686. 'kp_code' => $kp['kp_id'] ?? null,
  687. 'kp_name' => $kp['kp_id'] ?? '未知知识点',
  688. 'mastery_level' => $kp['mastery_level'] ?? 0,
  689. 'mastery_change' => $kp['change'] ?? null,
  690. ];
  691. }
  692. // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
  693. try {
  694. // 获取本次考试涉及的知识点代码列表
  695. $examKpCodes = array_column($masteryData, 'kp_code');
  696. Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
  697. 'count' => count($examKpCodes),
  698. 'kp_codes' => $examKpCodes
  699. ]);
  700. // 获取上一个快照的数据(用于计算变化)
  701. // 如果没有其他试卷的记录,使用同一试卷的上一次快照
  702. $lastSnapshot = DB::connection('mysql')
  703. ->table('knowledge_point_mastery_snapshots')
  704. ->where('student_id', $studentId)
  705. ->where('paper_id', $paper->paper_id)
  706. ->where('snapshot_id', '!=', "snap_{$paper->paper_id}_" . date('YmdHis'))
  707. ->latest('snapshot_time')
  708. ->first();
  709. $previousMasteryData = [];
  710. if ($lastSnapshot) {
  711. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  712. foreach ($previousMasteryJson as $kpCode => $data) {
  713. $previousMasteryData[$kpCode] = [
  714. 'current_mastery' => $data['current_mastery'] ?? 0,
  715. 'previous_mastery' => $data['previous_mastery'] ?? null,
  716. ];
  717. }
  718. Log::info('ExamPdfExportService: 获取到上一次快照数据', [
  719. 'snapshot_time' => $lastSnapshot->snapshot_time,
  720. 'kp_count' => count($previousMasteryData)
  721. ]);
  722. }
  723. // 为当前知识点添加变化数据
  724. foreach ($masteryData as &$item) {
  725. $kpCode = $item['kp_code'];
  726. if (isset($previousMasteryData[$kpCode])) {
  727. $previous = floatval($previousMasteryData[$kpCode]['previous_mastery'] ?? 0);
  728. $current = floatval($item['mastery_level']);
  729. $item['mastery_change'] = $current - $previous;
  730. }
  731. }
  732. unset($item); // 解除引用
  733. // 获取所有父节点掌握度
  734. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  735. $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
  736. // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
  737. $parentMasteryLevels = [];
  738. // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
  739. foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
  740. // 查询这个父节点的所有子节点
  741. $childNodes = DB::connection('mysql')
  742. ->table('knowledge_points')
  743. ->where('parent_kp_code', $parentKpCode)
  744. ->pluck('kp_code')
  745. ->toArray();
  746. // 检查是否有子节点在本次考试中出现
  747. $relevantChildren = array_intersect($examKpCodes, $childNodes);
  748. if (!empty($relevantChildren)) {
  749. // 【修复】计算父节点变化:基于所有子节点的平均变化
  750. $childChanges = [];
  751. foreach ($relevantChildren as $childKpCode) {
  752. $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
  753. $currentChild = null;
  754. foreach ($masteryData as $item) {
  755. if ($item['kp_code'] === $childKpCode) {
  756. $currentChild = $item['mastery_level'];
  757. break;
  758. }
  759. }
  760. if ($previousChild !== null && $currentChild !== null) {
  761. $childChanges[] = floatval($currentChild) - floatval($previousChild);
  762. }
  763. }
  764. $avgChange = !empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
  765. // 获取父节点中文名称
  766. $parentKpInfo = DB::connection('mysql')
  767. ->table('knowledge_points')
  768. ->where('kp_code', $parentKpCode)
  769. ->first();
  770. $parentMasteryLevels[$parentKpCode] = [
  771. 'kp_code' => $parentKpCode,
  772. 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
  773. 'mastery_level' => $parentMastery,
  774. 'mastery_percentage' => round($parentMastery * 100, 1),
  775. 'mastery_change' => $avgChange,
  776. 'children' => $relevantChildren,
  777. ];
  778. }
  779. }
  780. Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
  781. 'all_parent_count' => count($allParentMasteryLevels),
  782. 'filtered_parent_count' => count($parentMasteryLevels),
  783. 'filtered_codes' => array_keys($parentMasteryLevels)
  784. ]);
  785. } catch (\Exception $e) {
  786. Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
  787. 'error' => $e->getMessage()
  788. ]);
  789. }
  790. Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
  791. 'count' => count($masteryData),
  792. 'masteryData_sample' => !empty($masteryData) ? array_slice($masteryData, 0, 2) : []
  793. ]);
  794. } else {
  795. // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
  796. try {
  797. Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
  798. 'student_id' => $studentId
  799. ]);
  800. $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
  801. $masteryData = $masteryOverview['details'] ?? [];
  802. $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
  803. // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
  804. if (!empty($masteryData) && is_array($masteryData)) {
  805. $masteryData = array_map(function($item) {
  806. if (is_object($item)) {
  807. return [
  808. 'kp_code' => $item->kp_code ?? null,
  809. 'kp_name' => $item->kp_name ?? null,
  810. 'mastery_level' => floatval($item->mastery_level ?? 0),
  811. 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
  812. ];
  813. }
  814. return $item;
  815. }, $masteryData);
  816. }
  817. // 【修复】获取快照数据以计算掌握度变化
  818. $lastSnapshot = DB::connection('mysql')
  819. ->table('knowledge_point_mastery_snapshots')
  820. ->where('student_id', $studentId)
  821. ->latest('snapshot_time')
  822. ->first();
  823. if ($lastSnapshot) {
  824. $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
  825. foreach ($masteryData as &$item) {
  826. $kpCode = $item['kp_code'];
  827. if (isset($previousMasteryJson[$kpCode])) {
  828. $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
  829. $current = floatval($item['mastery_level']);
  830. $item['mastery_change'] = $current - $previous;
  831. }
  832. }
  833. unset($item);
  834. }
  835. Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
  836. 'count' => count($masteryData),
  837. 'parent_count' => count($parentMasteryLevels)
  838. ]);
  839. } catch (\Exception $e) {
  840. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  841. 'student_id' => $studentId,
  842. 'error' => $e->getMessage()
  843. ]);
  844. }
  845. }
  846. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  847. $recommendations = [];
  848. try {
  849. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  850. 'student_id' => $studentId
  851. ]);
  852. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  853. $recommendations = $learningPaths['recommendations'] ?? [];
  854. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  855. 'count' => count($recommendations)
  856. ]);
  857. } catch (\Exception $e) {
  858. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  859. 'student_id' => $studentId,
  860. 'error' => $e->getMessage()
  861. ]);
  862. }
  863. // 获取知识点名称映射
  864. $kpNameMap = $this->buildKnowledgePointNameMap();
  865. Log::info('ExamPdfExportService: 获取知识点名称映射', [
  866. 'kpNameMap_count' => count($kpNameMap),
  867. 'kpNameMap_keys_sample' => !empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : []
  868. ]);
  869. // 【修复】直接从MySQL数据库获取题目详情(不通过API)
  870. $questionDetails = $this->getQuestionDetailsFromMySQL($paper);
  871. // 处理题目数据
  872. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  873. // 【关键调试】查看buildMasterySummary的返回结果
  874. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  875. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  876. 'masteryData_count' => count($masteryData),
  877. 'kpNameMap_count' => count($kpNameMap),
  878. 'masterySummary_keys' => array_keys($masterySummary),
  879. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  880. 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
  881. ]);
  882. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  883. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  884. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
  885. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  886. 'raw_count' => count($parentMasteryLevels),
  887. 'processed_count' => count($processedParentMastery),
  888. 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
  889. ]);
  890. return [
  891. 'paper' => [
  892. 'id' => $paper->paper_id,
  893. 'name' => $paper->paper_name,
  894. 'total_questions' => $paper->question_count,
  895. 'total_score' => $paper->total_score,
  896. 'created_at' => $paper->created_at,
  897. ],
  898. 'student' => $studentInfo,
  899. 'questions' => $questions,
  900. 'mastery' => $masterySummary,
  901. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  902. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  903. 'recommendations' => $recommendations,
  904. 'analysis_data' => $analysisData,
  905. ];
  906. }
  907. /**
  908. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  909. */
  910. private function getQuestionDetailsFromMySQL(Paper $paper): array
  911. {
  912. $details = [];
  913. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  914. 'paper_id' => $paper->paper_id,
  915. 'question_count' => $paper->questions->count()
  916. ]);
  917. foreach ($paper->questions as $pq) {
  918. try {
  919. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  920. $detail = [
  921. 'id' => $pq->question_id,
  922. 'content' => $pq->question_text,
  923. 'question_type' => $pq->question_type,
  924. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  925. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  926. ];
  927. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  928. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  929. 'paper_question_id' => $pq->id,
  930. 'question_id' => $pq->question_id,
  931. 'has_answer' => !empty($pq->correct_answer),
  932. 'has_solution' => !empty($pq->solution),
  933. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
  934. ]);
  935. } catch (\Throwable $e) {
  936. Log::error('ExamPdfExportService: 获取题目详情失败', [
  937. 'paper_question_id' => $pq->id,
  938. 'error' => $e->getMessage(),
  939. ]);
  940. }
  941. }
  942. return $details;
  943. }
  944. /**
  945. * 处理题目数据(用于报告)
  946. */
  947. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  948. {
  949. $grouped = [
  950. 'choice' => [],
  951. 'fill' => [],
  952. 'answer' => [],
  953. ];
  954. // 【修复】处理空的试卷(questions可能不存在)
  955. $questions = $paper->questions ?? collect();
  956. if ($questions->isEmpty()) {
  957. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  958. return $grouped;
  959. }
  960. $sortedQuestions = $questions
  961. ->sortBy(function ($q, int $idx) {
  962. $number = $q->question_number ?? $idx + 1;
  963. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  964. });
  965. foreach ($sortedQuestions as $idx => $question) {
  966. $kpCode = $question->knowledge_point ?? '';
  967. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  968. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  969. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  970. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  971. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  972. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  973. $normalizedType = $this->normalizeQuestionType($typeRaw);
  974. $number = $question->question_number ?? ($idx + 1);
  975. $payload = [
  976. 'question_number' => $number,
  977. 'question_text' => is_array($question->question_text)
  978. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  979. : ($question->question_text ?? ''),
  980. 'question_type' => $normalizedType,
  981. 'knowledge_point' => $kpCode,
  982. 'knowledge_point_name' => $kpName,
  983. 'score' => $question->score,
  984. 'answer' => $answer, // 正确答案
  985. 'solution' => $solution, // 解题思路
  986. 'student_answer' => $question->student_answer ?? null, // 【新增】学生答案
  987. 'correct_answer' => $answer, // 【新增】正确答案
  988. 'is_correct' => $question->is_correct ?? null, // 【新增】判分结果
  989. 'score_obtained' => $question->score_obtained ?? null, // 【新增】得分
  990. ];
  991. $grouped[$normalizedType][] = $payload;
  992. // 【调试】记录题目数据
  993. Log::debug('ExamPdfExportService: 处理题目数据', [
  994. 'paper_question_id' => $question->id,
  995. 'question_id' => $question->question_id,
  996. 'has_answer' => !empty($answer),
  997. 'has_solution' => !empty($solution),
  998. 'answer_preview' => $answer ? substr($answer, 0, 50) : null
  999. ]);
  1000. }
  1001. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  1002. // 按卷面顺序重新编号
  1003. foreach ($ordered as $i => &$q) {
  1004. $q['display_number'] = $i + 1;
  1005. }
  1006. unset($q);
  1007. return $ordered;
  1008. }
  1009. /**
  1010. * 构建PDF
  1011. */
  1012. private function buildPdf(string $html): ?string
  1013. {
  1014. Log::info('ExamPdfExportService: buildPdf开始', ['html_size' => strlen($html)]);
  1015. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  1016. Log::info('ExamPdfExportService: 创建临时HTML文件', ['tmp_html' => $tmpHtml]);
  1017. $utf8Html = $this->ensureUtf8Html($html);
  1018. file_put_contents($tmpHtml, $utf8Html);
  1019. Log::info('ExamPdfExportService: HTML文件已写入', ['tmp_html' => $tmpHtml, 'size' => filesize($tmpHtml)]);
  1020. // 仅使用Chrome渲染
  1021. Log::info('ExamPdfExportService: 开始调用renderWithChrome', ['tmp_html' => $tmpHtml]);
  1022. $chromePdf = $this->renderWithChrome($tmpHtml);
  1023. Log::info('ExamPdfExportService: renderWithChrome完成', [
  1024. 'pdf_size' => $chromePdf ? strlen($chromePdf) : 0,
  1025. 'pdf_success' => !empty($chromePdf)
  1026. ]);
  1027. @unlink($tmpHtml);
  1028. return $chromePdf;
  1029. }
  1030. /**
  1031. * 从URL生成PDF
  1032. */
  1033. private function buildPdfFromUrl(string $url): ?string
  1034. {
  1035. Log::info('ExamPdfExportService: buildPdfFromUrl开始', ['url' => $url]);
  1036. try {
  1037. $response = Http::get($url);
  1038. Log::info('ExamPdfExportService: HTTP请求完成', [
  1039. 'url' => $url,
  1040. 'status' => $response->status(),
  1041. 'successful' => $response->successful()
  1042. ]);
  1043. if (!$response->successful()) {
  1044. Log::error('ExamPdfExportService: 获取URL内容失败', [
  1045. 'url' => $url,
  1046. 'status_code' => $response->status()
  1047. ]);
  1048. return null;
  1049. }
  1050. $html = $response->body();
  1051. $htmlSize = strlen($html);
  1052. Log::info('ExamPdfExportService: 获取HTML内容成功', [
  1053. 'url' => $url,
  1054. 'html_size' => $htmlSize,
  1055. 'html_preview' => substr($html, 0, 100)
  1056. ]);
  1057. if (empty($html)) {
  1058. Log::error('ExamPdfExportService: URL返回内容为空', ['url' => $url]);
  1059. return null;
  1060. }
  1061. Log::info('ExamPdfExportService: 开始调用buildPdf', ['html_size' => $htmlSize]);
  1062. $pdfBinary = $this->buildPdf($html);
  1063. Log::info('ExamPdfExportService: buildPdf完成', [
  1064. 'pdf_size' => $pdfBinary ? strlen($pdfBinary) : 0,
  1065. 'pdf_success' => !empty($pdfBinary)
  1066. ]);
  1067. return $pdfBinary;
  1068. } catch (\Exception $e) {
  1069. Log::error('ExamPdfExportService: buildPdfFromUrl异常', [
  1070. 'url' => $url,
  1071. 'error' => $e->getMessage(),
  1072. 'trace' => $e->getTraceAsString()
  1073. ]);
  1074. return null;
  1075. }
  1076. }
  1077. /**
  1078. * 使用Chrome渲染PDF
  1079. */
  1080. private function renderWithChrome(string $htmlPath): ?string
  1081. {
  1082. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  1083. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  1084. $chromeBinary = $this->findChromeBinary();
  1085. if (!$chromeBinary) {
  1086. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  1087. return null;
  1088. }
  1089. Log::info('ExamPdfExportService: 开始Chrome渲染', [
  1090. 'html_path' => $htmlPath,
  1091. 'tmp_pdf' => $tmpPdf,
  1092. 'chrome_binary' => $chromeBinary
  1093. ]);
  1094. // 设置运行时目录
  1095. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  1096. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  1097. if (!File::exists($runtimeHome)) {
  1098. @File::makeDirectory($runtimeHome, 0755, true);
  1099. }
  1100. if (!File::exists($runtimeXdg)) {
  1101. @File::makeDirectory($runtimeXdg, 0755, true);
  1102. }
  1103. $process = new Process([
  1104. $chromeBinary,
  1105. '--headless',
  1106. '--disable-gpu',
  1107. '--no-sandbox',
  1108. '--disable-setuid-sandbox',
  1109. '--disable-dev-shm-usage',
  1110. '--no-zygote',
  1111. '--disable-features=VizDisplayCompositor',
  1112. '--disable-software-rasterizer',
  1113. '--disable-extensions',
  1114. '--disable-background-networking',
  1115. '--disable-component-update',
  1116. '--disable-client-side-phishing-detection',
  1117. '--disable-default-apps',
  1118. '--disable-domain-reliability',
  1119. '--disable-sync',
  1120. '--safebrowsing-disable-auto-update',
  1121. '--no-first-run',
  1122. '--no-default-browser-check',
  1123. '--disable-crash-reporter',
  1124. '--disable-print-preview',
  1125. '--disable-features=PrintHeaderFooter',
  1126. '--disable-features=TranslateUI',
  1127. '--disable-features=OptimizationHints',
  1128. '--disable-ipc-flooding-protection',
  1129. '--disable-background-networking',
  1130. '--disable-background-timer-throttling',
  1131. '--disable-backgrounding-occluded-windows',
  1132. '--disable-renderer-backgrounding',
  1133. '--disable-features=AudioServiceOutOfProcess',
  1134. '--user-data-dir=' . $userDataDir,
  1135. '--print-to-pdf=' . $tmpPdf,
  1136. '--print-to-pdf-no-header',
  1137. '--allow-file-access-from-files',
  1138. 'file://' . $htmlPath,
  1139. ], null, [
  1140. 'HOME' => $runtimeHome,
  1141. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  1142. ]);
  1143. // 【修复】减少超时时间,避免队列任务整体超时
  1144. // 队列任务默认60秒超时,给Chrome进程设置45秒超时
  1145. $process->setTimeout(45);
  1146. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  1147. try {
  1148. $startedAt = microtime(true);
  1149. Log::info('ExamPdfExportService: Chrome进程启动', [
  1150. 'start_time' => date('Y-m-d H:i:s', (int)$startedAt),
  1151. 'timeout' => 45
  1152. ]);
  1153. $process->start();
  1154. $pdfGenerated = false;
  1155. // 【修复】缩短轮询时间,提高响应速度
  1156. $pollStart = microtime(true);
  1157. $maxPollSeconds = 40; // 缩短到40秒(小于Chrome超时45秒)
  1158. $checkInterval = 100_000; // 100ms检查一次
  1159. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  1160. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  1161. $pdfGenerated = true;
  1162. Log::info('ExamPdfExportService: PDF文件已生成,提前终止Chrome', [
  1163. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
  1164. 'pdf_size' => filesize($tmpPdf)
  1165. ]);
  1166. $process->stop(2, $killSignal);
  1167. break;
  1168. }
  1169. usleep($checkInterval);
  1170. }
  1171. $elapsed = microtime(true) - $startedAt;
  1172. Log::info('ExamPdfExportService: Chrome轮询结束', [
  1173. 'elapsed' => round($elapsed, 2) . 's',
  1174. 'is_running' => $process->isRunning(),
  1175. 'pdf_exists' => file_exists($tmpPdf),
  1176. 'pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : 0
  1177. ]);
  1178. // 【优化】强制停止Chrome进程
  1179. if ($process->isRunning()) {
  1180. Log::warning('ExamPdfExportService: Chrome进程仍在运行,强制停止', [
  1181. 'elapsed' => round($elapsed, 2) . 's'
  1182. ]);
  1183. $process->stop(2, $killSignal);
  1184. }
  1185. $process->wait();
  1186. } catch (ProcessTimedOutException $e) {
  1187. Log::error('ExamPdfExportService: Chrome进程超时', [
  1188. 'timeout' => $e->getExceededTimeout(),
  1189. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
  1190. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0
  1191. ]);
  1192. if ($process->isRunning()) {
  1193. $process->stop(2, $killSignal);
  1194. }
  1195. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1196. } catch (ProcessSignaledException $e) {
  1197. Log::warning('ExamPdfExportService: Chrome进程被信号终止', [
  1198. 'signal' => $e->getSignal(),
  1199. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's'
  1200. ]);
  1201. if ($process->isRunning()) {
  1202. $process->stop(2, $killSignal);
  1203. }
  1204. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1205. } catch (\Throwable $e) {
  1206. Log::error('ExamPdfExportService: Chrome渲染异常', [
  1207. 'error' => $e->getMessage(),
  1208. 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
  1209. 'trace' => $e->getTraceAsString()
  1210. ]);
  1211. if ($process->isRunning()) {
  1212. $process->stop(2, $killSignal);
  1213. }
  1214. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1215. }
  1216. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1217. }
  1218. /**
  1219. * 处理Chrome进程结果
  1220. */
  1221. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  1222. {
  1223. $elapsed = $startedAt ? round(microtime(true) - $startedAt, 2) : 0;
  1224. $pdfExists = file_exists($tmpPdf);
  1225. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  1226. if (!$process->isSuccessful()) {
  1227. if ($pdfExists && $pdfSize > 0) {
  1228. Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
  1229. 'elapsed' => $elapsed . 's',
  1230. 'exit_code' => $process->getExitCode(),
  1231. 'tmp_pdf_size' => $pdfSize,
  1232. ]);
  1233. } else {
  1234. Log::error('ExamPdfExportService: Chrome渲染失败', [
  1235. 'elapsed' => $elapsed . 's',
  1236. 'exit_code' => $process->getExitCode(),
  1237. 'error' => $process->getErrorOutput(),
  1238. 'tmp_pdf_exists' => $pdfExists,
  1239. 'tmp_pdf_size' => $pdfSize
  1240. ]);
  1241. }
  1242. } else {
  1243. Log::info('ExamPdfExportService: Chrome进程正常结束', [
  1244. 'elapsed' => $elapsed . 's',
  1245. 'exit_code' => $process->getExitCode(),
  1246. 'pdf_exists' => $pdfExists,
  1247. 'pdf_size' => $pdfSize
  1248. ]);
  1249. }
  1250. // 读取PDF内容
  1251. $pdfBinary = null;
  1252. if ($pdfExists && $pdfSize > 0) {
  1253. $pdfBinary = file_get_contents($tmpPdf);
  1254. Log::info('ExamPdfExportService: PDF读取成功', [
  1255. 'size' => strlen($pdfBinary),
  1256. 'elapsed' => $elapsed . 's'
  1257. ]);
  1258. } else {
  1259. Log::error('ExamPdfExportService: PDF文件不存在或为空', [
  1260. 'tmp_pdf' => $tmpPdf,
  1261. 'exists' => $pdfExists,
  1262. 'size' => $pdfSize
  1263. ]);
  1264. }
  1265. // 【优化】确保资源正确释放,使用try-catch包装
  1266. try {
  1267. if ($pdfExists && file_exists($tmpPdf)) {
  1268. @unlink($tmpPdf);
  1269. Log::debug('ExamPdfExportService: 临时PDF文件已删除', ['path' => $tmpPdf]);
  1270. }
  1271. } catch (\Exception $e) {
  1272. Log::warning('ExamPdfExportService: 删除临时PDF文件失败', [
  1273. 'path' => $tmpPdf,
  1274. 'error' => $e->getMessage()
  1275. ]);
  1276. }
  1277. try {
  1278. if ($userDataDir && is_dir($userDataDir)) {
  1279. File::deleteDirectory($userDataDir);
  1280. Log::debug('ExamPdfExportService: Chrome用户数据目录已删除', ['path' => $userDataDir]);
  1281. }
  1282. } catch (\Exception $e) {
  1283. Log::warning('ExamPdfExportService: 删除Chrome用户数据目录失败', [
  1284. 'path' => $userDataDir,
  1285. 'error' => $e->getMessage()
  1286. ]);
  1287. }
  1288. return $pdfBinary ?: null;
  1289. }
  1290. /**
  1291. * 查找Chrome二进制文件
  1292. */
  1293. private function findChromeBinary(): ?string
  1294. {
  1295. $candidates = [
  1296. env('PDF_CHROME_BINARY'),
  1297. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  1298. '/usr/bin/google-chrome-stable',
  1299. '/usr/bin/google-chrome',
  1300. '/usr/bin/chromium-browser',
  1301. '/usr/bin/chromium',
  1302. ];
  1303. foreach ($candidates as $path) {
  1304. if ($path && is_file($path) && is_executable($path)) {
  1305. return $path;
  1306. }
  1307. }
  1308. return null;
  1309. }
  1310. /**
  1311. * 确保HTML为UTF-8编码
  1312. */
  1313. private function ensureUtf8Html(string $html): string
  1314. {
  1315. $meta = '<meta charset="UTF-8">';
  1316. if (stripos($html, '<head>') !== false) {
  1317. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  1318. }
  1319. return $meta . $html;
  1320. }
  1321. /**
  1322. * 构建知识点名称映射
  1323. */
  1324. private function buildKnowledgePointNameMap(): array
  1325. {
  1326. try {
  1327. $options = $this->questionServiceApi->getKnowledgePointOptions();
  1328. return $options ?: [];
  1329. } catch (\Throwable $e) {
  1330. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  1331. 'error' => $e->getMessage(),
  1332. ]);
  1333. return [];
  1334. }
  1335. }
  1336. /**
  1337. * 构建掌握度摘要
  1338. */
  1339. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  1340. {
  1341. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  1342. 'masteryData_count' => count($masteryData),
  1343. 'kpNameMap_count' => count($kpNameMap)
  1344. ]);
  1345. $items = [];
  1346. $total = 0;
  1347. $count = 0;
  1348. foreach ($masteryData as $row) {
  1349. $code = $row['kp_code'] ?? null;
  1350. // 【修复】使用kpNameMap转换名称为友好显示名
  1351. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  1352. $level = (float)($row['mastery_level'] ?? 0);
  1353. $delta = $row['mastery_change'] ?? null;
  1354. $items[] = [
  1355. 'kp_code' => $code,
  1356. 'kp_name' => $name,
  1357. 'mastery_level' => $level,
  1358. 'mastery_change' => $delta,
  1359. ];
  1360. $total += $level;
  1361. $count++;
  1362. }
  1363. $average = $count > 0 ? round($total / $count, 2) : null;
  1364. // 按掌握度从低到高排序
  1365. if (!empty($items)) {
  1366. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  1367. }
  1368. $result = [
  1369. 'items' => $items,
  1370. 'average' => $average,
  1371. 'weak_list' => array_slice($items, 0, 5),
  1372. ];
  1373. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  1374. 'total_count' => $count,
  1375. 'items_count' => count($items)
  1376. ]);
  1377. return $result;
  1378. }
  1379. /**
  1380. * 标准化题型
  1381. */
  1382. private function normalizeQuestionType(string $type): string
  1383. {
  1384. $t = strtolower(trim($type));
  1385. return match (true) {
  1386. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  1387. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  1388. default => 'answer',
  1389. };
  1390. }
  1391. /**
  1392. * 保存PDF URL到数据库
  1393. */
  1394. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  1395. {
  1396. try {
  1397. $paper = Paper::where('paper_id', $paperId)->first();
  1398. if ($paper) {
  1399. $paper->update([$field => $url]);
  1400. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  1401. 'paper_id' => $paperId,
  1402. 'field' => $field,
  1403. 'url' => $url,
  1404. ]);
  1405. }
  1406. } catch (\Throwable $e) {
  1407. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  1408. 'paper_id' => $paperId,
  1409. 'field' => $field,
  1410. 'error' => $e->getMessage(),
  1411. ]);
  1412. }
  1413. }
  1414. /**
  1415. * 保存学情分析PDF URL
  1416. */
  1417. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  1418. {
  1419. try {
  1420. if ($recordId) {
  1421. // OCR记录
  1422. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  1423. if ($ocrRecord) {
  1424. $ocrRecord->update(['analysis_pdf_url' => $url]);
  1425. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  1426. 'record_id' => $recordId,
  1427. 'paper_id' => $paperId,
  1428. 'student_id' => $studentId,
  1429. 'url' => $url,
  1430. ]);
  1431. }
  1432. } else {
  1433. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  1434. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  1435. ->where('student_id', $studentId)
  1436. ->where('paper_id', $paperId)
  1437. ->update([
  1438. 'analysis_pdf_url' => $url,
  1439. 'updated_at' => now(),
  1440. ]);
  1441. if ($updated) {
  1442. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  1443. 'student_id' => $studentId,
  1444. 'paper_id' => $paperId,
  1445. 'url' => $url,
  1446. 'updated_rows' => $updated,
  1447. ]);
  1448. } else {
  1449. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  1450. 'student_id' => $studentId,
  1451. 'paper_id' => $paperId,
  1452. ]);
  1453. }
  1454. // 学生记录 - 使用新的 student_reports 表(备用)
  1455. \App\Models\StudentReport::updateOrCreate(
  1456. [
  1457. 'student_id' => $studentId,
  1458. 'report_type' => 'exam_analysis',
  1459. 'paper_id' => $paperId,
  1460. ],
  1461. [
  1462. 'pdf_url' => $url,
  1463. 'generation_status' => 'completed',
  1464. 'generated_at' => now(),
  1465. 'updated_at' => now(),
  1466. ]
  1467. );
  1468. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  1469. 'student_id' => $studentId,
  1470. 'paper_id' => $paperId,
  1471. 'url' => $url,
  1472. ]);
  1473. }
  1474. } catch (\Throwable $e) {
  1475. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  1476. 'paper_id' => $paperId,
  1477. 'student_id' => $studentId,
  1478. 'record_id' => $recordId,
  1479. 'error' => $e->getMessage(),
  1480. ]);
  1481. }
  1482. }
  1483. /**
  1484. * 【修复】处理父节点掌握度数据
  1485. * 1. 过滤掉掌握度为0或null的父节点
  1486. * 2. 将kp_code转换为友好的kp_name
  1487. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  1488. */
  1489. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
  1490. {
  1491. $processed = [];
  1492. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  1493. // 兼容不同数据结构:可能是数组或数字
  1494. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  1495. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  1496. // 过滤零值和空值
  1497. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1498. continue;
  1499. }
  1500. // 获取友好名称
  1501. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1502. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1503. $processed[$kpCode] = [
  1504. 'kp_code' => $kpCode,
  1505. 'kp_name' => $kpName,
  1506. 'mastery_level' => round(floatval($masteryLevel), 4),
  1507. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1508. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1509. // 【修复】只获取本次考试涉及的子节点
  1510. 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
  1511. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1512. ];
  1513. }
  1514. // 按掌握度降序排序
  1515. uasort($processed, function($a, $b) {
  1516. return $b['mastery_level'] <=> $a['mastery_level'];
  1517. });
  1518. return $processed;
  1519. }
  1520. /**
  1521. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1522. */
  1523. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
  1524. {
  1525. $children = [];
  1526. try {
  1527. $childCodes = DB::connection('mysql')
  1528. ->table('knowledge_points')
  1529. ->where('parent_kp_code', $parentKpCode)
  1530. ->pluck('kp_code')
  1531. ->toArray();
  1532. foreach ($childCodes as $childCode) {
  1533. // 只包含本次考试涉及的知识点
  1534. if (in_array($childCode, $examKpCodes)) {
  1535. $children[] = [
  1536. 'kp_code' => $childCode,
  1537. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1538. ];
  1539. }
  1540. }
  1541. } catch (\Exception $e) {
  1542. Log::warning('获取子知识点失败', [
  1543. 'parent_kp_code' => $parentKpCode,
  1544. 'error' => $e->getMessage(),
  1545. ]);
  1546. }
  1547. return $children;
  1548. }
  1549. /**
  1550. * 计算知识点层级深度
  1551. */
  1552. private function calculateKnowledgePointLevel(string $kpCode): int
  1553. {
  1554. // 根据kp_code前缀判断层级深度
  1555. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  1556. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  1557. return 1; // 一级分类,如 M, S, E, G
  1558. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  1559. return 2; // 二级分类,如 M01, S02
  1560. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  1561. return 3; // 三级分类,如 M01A, S02B
  1562. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  1563. return 4; // 四级分类,如 M01A1
  1564. }
  1565. return 1; // 默认一级
  1566. }
  1567. /**
  1568. * 构建题目数据(用于PDF生成)
  1569. */
  1570. private function buildQuestionsData(Paper $paper): array
  1571. {
  1572. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  1573. $questionsData = [];
  1574. foreach ($paperQuestions as $pq) {
  1575. $questionsData[] = [
  1576. 'id' => $pq->question_bank_id,
  1577. 'kp_code' => $pq->knowledge_point,
  1578. 'question_type' => $pq->question_type ?? 'answer',
  1579. 'stem' => $pq->question_text ?? '题目内容缺失',
  1580. 'solution' => $pq->solution ?? '',
  1581. 'answer' => $pq->correct_answer ?? '',
  1582. 'difficulty' => $pq->difficulty ?? 0.5,
  1583. 'score' => $pq->score ?? 5,
  1584. 'tags' => '',
  1585. 'content' => $pq->question_text ?? '',
  1586. ];
  1587. }
  1588. // 获取完整题目详情
  1589. if (!empty($questionsData)) {
  1590. $questionIds = array_column($questionsData, 'id');
  1591. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  1592. $responseData = $questionsResponse['data'] ?? [];
  1593. if (!empty($responseData)) {
  1594. $responseDataMap = [];
  1595. foreach ($responseData as $respQ) {
  1596. $responseDataMap[$respQ['id']] = $respQ;
  1597. }
  1598. $questionsData = array_map(function($q) use ($responseDataMap) {
  1599. if (isset($responseDataMap[$q['id']])) {
  1600. $apiData = $responseDataMap[$q['id']];
  1601. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  1602. $q['content'] = $q['stem'];
  1603. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  1604. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  1605. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  1606. $q['options'] = $apiData['options'] ?? [];
  1607. }
  1608. return $q;
  1609. }, $questionsData);
  1610. }
  1611. }
  1612. // 按题型分类
  1613. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  1614. foreach ($questionsData as $q) {
  1615. $type = $this->determineQuestionType($q);
  1616. $classified[$type][] = (object) $q;
  1617. }
  1618. return $classified;
  1619. }
  1620. /**
  1621. * 获取学生信息
  1622. */
  1623. private function getStudentInfo(?string $studentId): array
  1624. {
  1625. if (!$studentId) {
  1626. return [
  1627. 'name' => '未知学生',
  1628. 'grade' => '未知年级',
  1629. 'class' => '未知班级'
  1630. ];
  1631. }
  1632. try {
  1633. $student = DB::table('students')
  1634. ->where('student_id', $studentId)
  1635. ->first();
  1636. if ($student) {
  1637. return [
  1638. 'name' => $student->name ?? $studentId,
  1639. 'grade' => $student->grade ?? '未知',
  1640. 'class' => $student->class ?? '未知'
  1641. ];
  1642. }
  1643. } catch (\Exception $e) {
  1644. Log::warning('获取学生信息失败', [
  1645. 'student_id' => $studentId,
  1646. 'error' => $e->getMessage()
  1647. ]);
  1648. }
  1649. return [
  1650. 'name' => $studentId,
  1651. 'grade' => '未知',
  1652. 'class' => '未知'
  1653. ];
  1654. }
  1655. /**
  1656. * 获取教师信息
  1657. */
  1658. private function getTeacherInfo(?string $teacherId): array
  1659. {
  1660. if (!$teacherId) {
  1661. return [
  1662. 'name' => '未知老师',
  1663. 'subject' => '数学'
  1664. ];
  1665. }
  1666. try {
  1667. $teacher = DB::table('teachers')
  1668. ->where('teacher_id', $teacherId)
  1669. ->first();
  1670. if ($teacher) {
  1671. return [
  1672. 'name' => $teacher->name ?? $teacherId,
  1673. 'subject' => $teacher->subject ?? '数学'
  1674. ];
  1675. }
  1676. } catch (\Exception $e) {
  1677. Log::warning('获取教师信息失败', [
  1678. 'teacher_id' => $teacherId,
  1679. 'error' => $e->getMessage()
  1680. ]);
  1681. }
  1682. return [
  1683. 'name' => $teacherId,
  1684. 'subject' => '数学'
  1685. ];
  1686. }
  1687. /**
  1688. * 判断题目类型
  1689. */
  1690. private function determineQuestionType(array $question): string
  1691. {
  1692. $stem = $question['stem'] ?? $question['content'] ?? '';
  1693. $tags = $question['tags'] ?? '';
  1694. // 根据题干内容判断选择题
  1695. if (is_string($stem)) {
  1696. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1697. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1698. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1699. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1700. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  1701. if ($optionCount >= 2) {
  1702. return 'choice';
  1703. }
  1704. // 检查是否有填空标记
  1705. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  1706. return 'fill';
  1707. }
  1708. }
  1709. // 根据已有类型字段判断
  1710. if (!empty($question['question_type'])) {
  1711. $type = strtolower(trim($question['question_type']));
  1712. if (in_array($type, ['choice', '选择题'])) return 'choice';
  1713. if (in_array($type, ['fill', '填空题'])) return 'fill';
  1714. if (in_array($type, ['answer', '解答题'])) return 'answer';
  1715. }
  1716. // 默认返回解答题
  1717. return 'answer';
  1718. }
  1719. }