ExamPdfExportService.php 78 KB

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