ExamPdfExportService.php 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  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. // 只有当 $paper 是 Paper 模型时才查询题目详情
  747. $questionDetails = ($paper instanceof \App\Models\Paper)
  748. ? $this->getQuestionDetailsFromMySQL($paper)
  749. : [];
  750. // 处理题目数据
  751. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  752. // 【关键调试】查看buildMasterySummary的返回结果
  753. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  754. Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
  755. 'masteryData_count' => count($masteryData),
  756. 'kpNameMap_count' => count($kpNameMap),
  757. 'masterySummary_keys' => array_keys($masterySummary),
  758. 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
  759. 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
  760. ]);
  761. // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
  762. $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
  763. $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
  764. Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
  765. 'raw_count' => count($parentMasteryLevels),
  766. 'processed_count' => count($processedParentMastery),
  767. 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
  768. ]);
  769. return [
  770. 'paper' => [
  771. 'id' => $paper->paper_id,
  772. 'name' => $paper->paper_name,
  773. 'total_questions' => $paper->question_count,
  774. 'total_score' => $paper->total_score,
  775. 'created_at' => $paper->created_at,
  776. ],
  777. 'student' => $studentInfo,
  778. 'questions' => $questions,
  779. 'mastery' => $masterySummary,
  780. 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
  781. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  782. 'recommendations' => $recommendations,
  783. 'analysis_data' => $analysisData,
  784. ];
  785. }
  786. /**
  787. * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
  788. */
  789. private function getQuestionDetailsFromMySQL(Paper $paper): array
  790. {
  791. $details = [];
  792. Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
  793. 'paper_id' => $paper->paper_id,
  794. 'question_count' => $paper->questions->count()
  795. ]);
  796. foreach ($paper->questions as $pq) {
  797. try {
  798. // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
  799. $detail = [
  800. 'id' => $pq->question_id,
  801. 'content' => $pq->question_text,
  802. 'question_type' => $pq->question_type,
  803. 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
  804. 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
  805. ];
  806. $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
  807. Log::debug('ExamPdfExportService: 成功获取题目详情', [
  808. 'paper_question_id' => $pq->id,
  809. 'question_id' => $pq->question_id,
  810. 'has_answer' => !empty($pq->correct_answer),
  811. 'has_solution' => !empty($pq->solution),
  812. 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
  813. ]);
  814. } catch (\Throwable $e) {
  815. Log::error('ExamPdfExportService: 获取题目详情失败', [
  816. 'paper_question_id' => $pq->id,
  817. 'error' => $e->getMessage(),
  818. ]);
  819. }
  820. }
  821. return $details;
  822. }
  823. /**
  824. * 处理题目数据(用于报告)
  825. */
  826. private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
  827. {
  828. $grouped = [
  829. 'choice' => [],
  830. 'fill' => [],
  831. 'answer' => [],
  832. ];
  833. // 【修复】处理空的试卷(questions可能不存在)
  834. $questions = $paper->questions ?? collect();
  835. if ($questions->isEmpty()) {
  836. Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
  837. return $grouped;
  838. }
  839. $sortedQuestions = $questions
  840. ->sortBy(function ($q, int $idx) {
  841. $number = $q->question_number ?? $idx + 1;
  842. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  843. });
  844. foreach ($sortedQuestions as $idx => $question) {
  845. $kpCode = $question->knowledge_point ?? '';
  846. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  847. // 【修复】直接从PaperQuestion对象获取solution和correct_answer
  848. $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
  849. $solution = $question->solution ?? null; // 直接从PaperQuestion获取
  850. $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
  851. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  852. $normalizedType = $this->normalizeQuestionType($typeRaw);
  853. $number = $question->question_number ?? ($idx + 1);
  854. $payload = [
  855. 'question_number' => $number,
  856. 'question_text' => is_array($question->question_text)
  857. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  858. : ($question->question_text ?? ''),
  859. 'question_type' => $normalizedType,
  860. 'knowledge_point' => $kpCode,
  861. 'knowledge_point_name' => $kpName,
  862. 'score' => $question->score,
  863. 'answer' => $answer, // 正确答案
  864. 'solution' => $solution, // 解题思路
  865. 'student_answer' => $question->student_answer ?? null, // 【新增】学生答案
  866. 'correct_answer' => $answer, // 【新增】正确答案
  867. 'is_correct' => $question->is_correct ?? null, // 【新增】判分结果
  868. 'score_obtained' => $question->score_obtained ?? null, // 【新增】得分
  869. ];
  870. $grouped[$normalizedType][] = $payload;
  871. // 【调试】记录题目数据
  872. Log::debug('ExamPdfExportService: 处理题目数据', [
  873. 'paper_question_id' => $question->id,
  874. 'question_id' => $question->question_id,
  875. 'has_answer' => !empty($answer),
  876. 'has_solution' => !empty($solution),
  877. 'answer_preview' => $answer ? substr($answer, 0, 50) : null
  878. ]);
  879. }
  880. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  881. // 按卷面顺序重新编号
  882. foreach ($ordered as $i => &$q) {
  883. $q['display_number'] = $i + 1;
  884. }
  885. unset($q);
  886. return $ordered;
  887. }
  888. /**
  889. * 构建PDF
  890. */
  891. private function buildPdf(string $html): ?string
  892. {
  893. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  894. $utf8Html = $this->ensureUtf8Html($html);
  895. $written = file_put_contents($tmpHtml, $utf8Html);
  896. Log::warning('ExamPdfExportService: [调试] HTML文件已创建', [
  897. 'path' => $tmpHtml,
  898. 'html_length' => strlen($utf8Html),
  899. 'written_bytes' => $written,
  900. 'file_exists' => file_exists($tmpHtml),
  901. 'file_size' => file_exists($tmpHtml) ? filesize($tmpHtml) : 0,
  902. ]);
  903. // 仅使用Chrome渲染
  904. $chromePdf = $this->renderWithChrome($tmpHtml);
  905. @unlink($tmpHtml);
  906. return $chromePdf;
  907. }
  908. /**
  909. * 使用Chrome渲染PDF
  910. */
  911. private function renderWithChrome(string $htmlPath): ?string
  912. {
  913. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  914. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  915. $chromeBinary = $this->findChromeBinary();
  916. if (!$chromeBinary) {
  917. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  918. return null;
  919. }
  920. // 设置运行时目录
  921. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  922. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  923. if (!File::exists($runtimeHome)) {
  924. @File::makeDirectory($runtimeHome, 0755, true);
  925. }
  926. if (!File::exists($runtimeXdg)) {
  927. @File::makeDirectory($runtimeXdg, 0755, true);
  928. }
  929. $process = new Process([
  930. $chromeBinary,
  931. '--headless=new', // 【优化】使用新渲染引擎
  932. '--disable-gpu',
  933. '--no-sandbox',
  934. '--disable-setuid-sandbox',
  935. '--disable-dev-shm-usage',
  936. '--disable-web-security',
  937. '--disable-features=VizDisplayCompositor',
  938. '--disable-extensions',
  939. // '--disable-background-networking', // 注释掉,可能阻止必要的网络请求
  940. '--disable-component-update',
  941. '--disable-client-side-phishing-detection',
  942. '--disable-default-apps',
  943. '--disable-domain-reliability',
  944. '--disable-sync',
  945. '--no-first-run',
  946. '--no-default-browser-check',
  947. '--disable-crash-reporter',
  948. '--disable-print-preview',
  949. '--disable-features=TranslateUI',
  950. '--disable-features=OptimizationHints',
  951. '--disable-ipc-flooding-protection',
  952. '--disable-background-timer-throttling',
  953. '--disable-backgrounding-occluded-windows',
  954. '--disable-renderer-backgrounding',
  955. '--disable-features=AudioServiceOutOfProcess',
  956. '--disable-gpu-sandbox',
  957. '--disable-software-rasterizer',
  958. '--disable-background-mode',
  959. '--disable-extensions-http-throttling',
  960. '--disable-ipc-flooding-protection',
  961. '--disable-features=Dbus', // 禁用 dbus
  962. // 【关键修复】添加虚拟时间预算,让Chrome有足够时间加载CDN资源和执行JS
  963. '--virtual-time-budget=30000', // 30秒虚拟时间用于加载外部资源
  964. '--run-all-compositor-stages-before-draw', // 确保所有渲染完成后再生成PDF
  965. '--user-data-dir=' . $userDataDir,
  966. '--print-to-pdf=' . $tmpPdf,
  967. '--print-to-pdf-no-header',
  968. '--allow-file-access-from-files',
  969. '--font-render-hinting=none', // 【优化】禁用字体渲染提示
  970. '--disable-font-antialiasing',
  971. 'file://' . $htmlPath,
  972. ], null, [
  973. 'HOME' => $runtimeHome,
  974. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  975. ]);
  976. $process->setTimeout(90); // 【修复】增加超时时间到90秒
  977. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  978. Log::warning('ExamPdfExportService: [调试] Chrome命令准备执行', [
  979. 'chrome_binary' => $chromeBinary,
  980. 'html_path' => $htmlPath,
  981. 'html_exists' => file_exists($htmlPath),
  982. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0,
  983. 'pdf_path' => $tmpPdf,
  984. 'user_data_dir' => $userDataDir,
  985. ]);
  986. try {
  987. $startedAt = microtime(true);
  988. $process->start();
  989. $pdfGenerated = false;
  990. // 轮询检测PDF是否生成
  991. $pollStart = microtime(true);
  992. $maxPollSeconds = 80; // 【修复】增加轮询超时到80秒
  993. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  994. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  995. $pdfGenerated = true;
  996. Log::info('ExamPdfExportService: PDF生成成功,提前终止Chrome进程', [
  997. 'elapsed' => round(microtime(true) - $startedAt, 2),
  998. 'pdf_size' => filesize($tmpPdf),
  999. ]);
  1000. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1001. break;
  1002. }
  1003. usleep(100_000); // 【优化】从200ms减少到100ms
  1004. }
  1005. if ($process->isRunning()) {
  1006. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1007. }
  1008. // 【优化】删除不必要的wait()调用,避免重复等待
  1009. // $process->wait();
  1010. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  1011. if ($process->isRunning()) {
  1012. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1013. }
  1014. Log::warning('ExamPdfExportService: Chrome进程超时或被信号中断', [
  1015. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1016. 'exception' => get_class($e),
  1017. ]);
  1018. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  1019. } catch (\Throwable $e) {
  1020. if ($process->isRunning()) {
  1021. $process->stop(3, $killSignal); // 【优化】减少停止等待时间
  1022. }
  1023. Log::error('ExamPdfExportService: Chrome进程异常', [
  1024. 'elapsed' => round((microtime(true) - $startedAt), 2),
  1025. 'error' => $e->getMessage(),
  1026. ]);
  1027. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1028. }
  1029. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  1030. }
  1031. /**
  1032. * 处理Chrome进程结果
  1033. */
  1034. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  1035. {
  1036. $pdfExists = file_exists($tmpPdf);
  1037. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  1038. $elapsed = $startedAt ? round((microtime(true) - $startedAt), 2) : null;
  1039. // 【优化】即使进程未成功,只要PDF存在且大小合理就返回
  1040. if ($pdfExists && $pdfSize > 1000) { // 至少1KB
  1041. Log::info('ExamPdfExportService: PDF生成成功', [
  1042. 'elapsed' => $elapsed,
  1043. 'pdf_size' => $pdfSize,
  1044. 'exit_code' => $process->getExitCode(),
  1045. 'is_successful' => $process->isSuccessful(),
  1046. ]);
  1047. $pdfBinary = file_get_contents($tmpPdf);
  1048. @unlink($tmpPdf);
  1049. File::deleteDirectory($userDataDir);
  1050. return $pdfBinary;
  1051. }
  1052. // 如果PDF不存在或太小,记录错误
  1053. Log::error('ExamPdfExportService: Chrome渲染失败', [
  1054. 'elapsed' => $elapsed,
  1055. 'pdf_exists' => $pdfExists,
  1056. 'pdf_size' => $pdfSize,
  1057. 'exit_code' => $process->getExitCode(),
  1058. 'error' => $process->getErrorOutput(),
  1059. 'output' => $process->getOutput(),
  1060. ]);
  1061. @unlink($tmpPdf);
  1062. File::deleteDirectory($userDataDir);
  1063. return null;
  1064. }
  1065. /**
  1066. * 查找Chrome二进制文件
  1067. */
  1068. private function findChromeBinary(): ?string
  1069. {
  1070. $candidates = [
  1071. env('PDF_CHROME_BINARY'),
  1072. env('CHROME_BIN'), // Docker Alpine 环境变量
  1073. '/usr/bin/chromium-browser', // Alpine Linux
  1074. '/usr/bin/chromium',
  1075. '/usr/bin/google-chrome-stable',
  1076. '/usr/bin/google-chrome',
  1077. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS
  1078. ];
  1079. foreach ($candidates as $path) {
  1080. if ($path && is_file($path) && is_executable($path)) {
  1081. return $path;
  1082. }
  1083. }
  1084. return null;
  1085. }
  1086. /**
  1087. * 确保HTML为UTF-8编码,并内联外部资源
  1088. */
  1089. private function ensureUtf8Html(string $html): string
  1090. {
  1091. $meta = '<meta charset="UTF-8">';
  1092. if (stripos($html, '<head>') !== false) {
  1093. $html = preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  1094. } else {
  1095. $html = $meta . $html;
  1096. }
  1097. // 【关键修复】内联KaTeX CSS,避免Chrome在容器中加载CDN资源超时
  1098. $html = $this->inlineExternalResources($html);
  1099. return $html;
  1100. }
  1101. /**
  1102. * 将CDN资源替换为内联资源
  1103. * 【关键修复】避免Chrome在容器中加载CDN资源超时
  1104. */
  1105. private function inlineExternalResources(string $html): string
  1106. {
  1107. // 【调试】记录HTML内容信息
  1108. Log::warning('ExamPdfExportService: inlineExternalResources', [
  1109. 'html_length' => strlen($html),
  1110. 'has_katex_cdn' => strpos($html, 'cdn.jsdelivr.net/npm/katex') !== false,
  1111. 'html_head_preview' => substr($html, 0, 1000),
  1112. ]);
  1113. // 检查是否包含KaTeX CDN链接
  1114. if (strpos($html, 'cdn.jsdelivr.net/npm/katex') === false) {
  1115. Log::warning('ExamPdfExportService: HTML中没有KaTeX CDN链接,跳过内联');
  1116. return $html;
  1117. }
  1118. try {
  1119. // 读取本地KaTeX CSS文件并内联
  1120. $katexCssPath = public_path('css/katex/katex.min.css');
  1121. if (file_exists($katexCssPath)) {
  1122. $katexCss = file_get_contents($katexCssPath);
  1123. // 修复字体路径:将相对路径改为绝对路径(使用data URI或绝对路径)
  1124. // KaTeX CSS中的字体引用格式: url(fonts/KaTeX_xxx.woff2)
  1125. $fontsDir = public_path('css/katex/fonts');
  1126. $katexCss = preg_replace_callback(
  1127. '/url\(["\']?fonts\/([^"\')\s]+)["\']?\)/i',
  1128. function ($matches) use ($fontsDir) {
  1129. $fontFile = $fontsDir . '/' . $matches[1];
  1130. if (file_exists($fontFile)) {
  1131. // 将字体转换为data URI(适用于PDF生成)
  1132. $fontData = base64_encode(file_get_contents($fontFile));
  1133. $mimeType = str_ends_with($matches[1], '.woff2') ? 'font/woff2' : 'font/woff';
  1134. return 'url(data:' . $mimeType . ';base64,' . $fontData . ')';
  1135. }
  1136. return $matches[0];
  1137. },
  1138. $katexCss
  1139. );
  1140. // 替换CDN CSS链接为内联样式
  1141. $html = preg_replace(
  1142. '/<link[^>]*href=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.css["\'][^>]*>/i',
  1143. '<style type="text/css">' . $katexCss . '</style>',
  1144. $html
  1145. );
  1146. Log::info('ExamPdfExportService: KaTeX CSS已内联(含字体data URI)');
  1147. }
  1148. // 读取本地KaTeX JS并内联
  1149. $katexJsPath = public_path('js/katex.min.js');
  1150. $autoRenderJsPath = public_path('js/auto-render.min.js');
  1151. if (file_exists($katexJsPath)) {
  1152. $katexJs = file_get_contents($katexJsPath);
  1153. $html = preg_replace(
  1154. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*katex\.min\.js["\'][^>]*><\/script>/i',
  1155. '<script type="text/javascript">' . $katexJs . '</script>',
  1156. $html
  1157. );
  1158. }
  1159. if (file_exists($autoRenderJsPath)) {
  1160. $autoRenderJs = file_get_contents($autoRenderJsPath);
  1161. $html = preg_replace(
  1162. '/<script[^>]*src=["\']https:\/\/cdn\.jsdelivr\.net\/npm\/katex[^"\']*auto-render[^"\']*["\'][^>]*><\/script>/i',
  1163. '<script type="text/javascript">' . $autoRenderJs . '</script>',
  1164. $html
  1165. );
  1166. }
  1167. // 【关键修复】使用服务端预渲染,而不是依赖客户端 JavaScript
  1168. // Chrome headless 的 --print-to-pdf 不会等待 JS 执行完成
  1169. // 所以我们使用 Node.js KaTeX 在服务端预渲染所有公式
  1170. // 1. 移除所有 KaTeX JavaScript(不再需要,因为使用服务端渲染)
  1171. // 移除内联的 katex.min.js
  1172. $html = preg_replace(
  1173. '/<script[^>]*type=["\']text\/javascript["\'][^>]*>[\s\S]*?katex[\s\S]*?<\/script>/i',
  1174. '<!-- KaTeX JS removed, using server-side rendering -->',
  1175. $html
  1176. );
  1177. // 移除 DOMContentLoaded 监听器
  1178. $html = preg_replace(
  1179. '/<script[^>]*>[\s\S]*?document\.addEventListener[\s\S]*?DOMContentLoaded[\s\S]*?<\/script>/i',
  1180. '<!-- DOMContentLoaded removed -->',
  1181. $html
  1182. );
  1183. // 2. 使用 KatexRenderer 进行服务端预渲染
  1184. if ($this->katexRenderer) {
  1185. $beforeLength = strlen($html);
  1186. $html = $this->katexRenderer->renderHtml($html);
  1187. $afterLength = strlen($html);
  1188. Log::info('ExamPdfExportService: LaTeX 公式服务端预渲染完成', [
  1189. 'before_length' => $beforeLength,
  1190. 'after_length' => $afterLength,
  1191. 'size_change' => $afterLength - $beforeLength,
  1192. ]);
  1193. } else {
  1194. Log::warning('ExamPdfExportService: KatexRenderer 未初始化,跳过预渲染');
  1195. }
  1196. } catch (\Exception $e) {
  1197. Log::warning('ExamPdfExportService: 内联资源处理失败,保留原始HTML', [
  1198. 'error' => $e->getMessage()
  1199. ]);
  1200. }
  1201. return $html;
  1202. }
  1203. /**
  1204. * 【新增】合并两个HTML页面,插入分页符
  1205. * 保留原始页面样式和结构,只在中间插入分页符
  1206. */
  1207. private function mergeHtmlWithPageBreak(string $examHtml, string $gradingHtml): ?string
  1208. {
  1209. try {
  1210. // 确保HTML编码正确
  1211. $examHtml = $this->ensureUtf8Html($examHtml);
  1212. $gradingHtml = $this->ensureUtf8Html($gradingHtml);
  1213. // 提取body内容
  1214. $examBody = $this->extractBodyContent($examHtml);
  1215. $gradingBody = $this->extractBodyContent($gradingHtml);
  1216. if (empty($examBody) || empty($gradingBody)) {
  1217. Log::error('ExamPdfExportService: HTML内容提取失败', [
  1218. 'exam_body_length' => strlen($examBody),
  1219. 'grading_body_length' => strlen($gradingBody)
  1220. ]);
  1221. return null;
  1222. }
  1223. // 提取head内容(保留原始样式和meta信息)
  1224. $examHead = $this->extractHeadContent($examHtml);
  1225. // 构建统一HTML文档(保留原始结构)
  1226. $unifiedHtml = $this->buildUnifiedHtmlWithOriginalStructure($examHead, $examBody, $gradingBody);
  1227. Log::info('HTML合并成功(保留原始样式)', [
  1228. 'exam_length' => strlen($examBody),
  1229. 'grading_length' => strlen($gradingBody),
  1230. 'unified_length' => strlen($unifiedHtml),
  1231. 'head_length' => strlen($examHead)
  1232. ]);
  1233. return $unifiedHtml;
  1234. } catch (\Throwable $e) {
  1235. Log::error('mergeHtmlWithPageBreak 失败', [
  1236. 'error' => $e->getMessage(),
  1237. 'trace' => $e->getTraceAsString()
  1238. ]);
  1239. return null;
  1240. }
  1241. }
  1242. /**
  1243. * 【新增】提取HTML的body内容
  1244. */
  1245. private function extractBodyContent(string $html): string
  1246. {
  1247. // 匹配body标签内容
  1248. if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $matches)) {
  1249. return $matches[1];
  1250. }
  1251. // 如果没有body标签,返回整个HTML
  1252. return $html;
  1253. }
  1254. /**
  1255. * 【新增】提取HTML的head内容
  1256. * 保留原始页面的样式和meta信息
  1257. */
  1258. private function extractHeadContent(string $html): string
  1259. {
  1260. // 匹配head标签内容
  1261. if (preg_match('/<head[^>]*>(.*)<\/head>/is', $html, $matches)) {
  1262. return $matches[1];
  1263. }
  1264. // 如果没有head标签,返回默认meta
  1265. return '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
  1266. }
  1267. /**
  1268. * 【新增】构建统一的HTML文档(保留原始结构)
  1269. * 保留第一个HTML的完整head和样式,只在body之间插入分页符
  1270. */
  1271. private function buildUnifiedHtmlWithOriginalStructure(string $examHead, string $examBody, string $gradingBody): string
  1272. {
  1273. // 保留原始head内容,添加分页符样式
  1274. $headContent = $examHead . '
  1275. <style>
  1276. /* 分页符样式 - 插入到原始样式之后 */
  1277. .page-break {
  1278. page-break-before: always;
  1279. page-break-after: always;
  1280. break-before: page;
  1281. break-after: page;
  1282. }
  1283. /* 确保分页符在打印时生效 */
  1284. @media print {
  1285. .page-break {
  1286. page-break-before: always;
  1287. }
  1288. }
  1289. </style>';
  1290. return '<!DOCTYPE html>
  1291. <html lang="zh-CN">
  1292. <head>
  1293. ' . $headContent . '
  1294. </head>
  1295. <body>
  1296. <!-- 第一部分:试卷(不含答案) -->
  1297. ' . $examBody . '
  1298. <!-- 分页符:第二部分从这里开始 -->
  1299. <div class="page-break"></div>
  1300. <!-- 第二部分:判卷(含答案与解析) -->
  1301. ' . $gradingBody . '
  1302. </body>
  1303. </html>';
  1304. }
  1305. /**
  1306. * 【新增】获取PDF通用样式
  1307. */
  1308. private function getCommonPdfStyles(): string
  1309. {
  1310. return '
  1311. * {
  1312. margin: 0;
  1313. padding: 0;
  1314. box-sizing: border-box;
  1315. }
  1316. body {
  1317. font-family: "Microsoft YaHei", "SimHei", Arial, sans-serif;
  1318. font-size: 14px;
  1319. line-height: 1.6;
  1320. color: #333;
  1321. background: #fff;
  1322. }
  1323. .paper-container {
  1324. max-width: 210mm;
  1325. margin: 0 auto;
  1326. padding: 20mm;
  1327. background: white;
  1328. }
  1329. .paper-header {
  1330. text-align: center;
  1331. margin-bottom: 30px;
  1332. padding-bottom: 15px;
  1333. border-bottom: 2px solid #333;
  1334. }
  1335. .paper-title {
  1336. font-size: 24px;
  1337. font-weight: bold;
  1338. margin-bottom: 10px;
  1339. }
  1340. .paper-info {
  1341. font-size: 14px;
  1342. color: #666;
  1343. }
  1344. .question {
  1345. margin-bottom: 30px;
  1346. padding: 20px;
  1347. border: 1px solid #ddd;
  1348. border-radius: 5px;
  1349. }
  1350. .question-number {
  1351. font-weight: bold;
  1352. margin-bottom: 10px;
  1353. }
  1354. .question-stem {
  1355. margin-bottom: 15px;
  1356. }
  1357. .options {
  1358. list-style: none;
  1359. margin-left: 20px;
  1360. }
  1361. .options li {
  1362. margin-bottom: 8px;
  1363. }
  1364. .answer-section {
  1365. margin-top: 20px;
  1366. padding-top: 15px;
  1367. border-top: 1px solid #eee;
  1368. }
  1369. .answer-label {
  1370. font-weight: bold;
  1371. color: #d9534f;
  1372. }
  1373. .solution {
  1374. margin-top: 10px;
  1375. padding: 10px;
  1376. background: #f5f5f5;
  1377. border-left: 4px solid #5bc0de;
  1378. }
  1379. ';
  1380. }
  1381. /**
  1382. * 构建知识点名称映射
  1383. */
  1384. private function buildKnowledgePointNameMap(): array
  1385. {
  1386. try {
  1387. $options = $this->questionServiceApi->getKnowledgePointOptions();
  1388. return $options ?: [];
  1389. } catch (\Throwable $e) {
  1390. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  1391. 'error' => $e->getMessage(),
  1392. ]);
  1393. return [];
  1394. }
  1395. }
  1396. /**
  1397. * 构建掌握度摘要
  1398. */
  1399. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  1400. {
  1401. Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
  1402. 'masteryData_count' => count($masteryData),
  1403. 'kpNameMap_count' => count($kpNameMap)
  1404. ]);
  1405. $items = [];
  1406. $total = 0;
  1407. $count = 0;
  1408. foreach ($masteryData as $row) {
  1409. $code = $row['kp_code'] ?? null;
  1410. // 【修复】使用kpNameMap转换名称为友好显示名
  1411. $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
  1412. $level = (float)($row['mastery_level'] ?? 0);
  1413. $delta = $row['mastery_change'] ?? null;
  1414. $items[] = [
  1415. 'kp_code' => $code,
  1416. 'kp_name' => $name,
  1417. 'mastery_level' => $level,
  1418. 'mastery_change' => $delta,
  1419. ];
  1420. $total += $level;
  1421. $count++;
  1422. }
  1423. $average = $count > 0 ? round($total / $count, 2) : null;
  1424. // 按掌握度从低到高排序
  1425. if (!empty($items)) {
  1426. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  1427. }
  1428. $result = [
  1429. 'items' => $items,
  1430. 'average' => $average,
  1431. 'weak_list' => array_slice($items, 0, 5),
  1432. ];
  1433. Log::info('ExamPdfExportService: buildMasterySummary完成', [
  1434. 'total_count' => $count,
  1435. 'items_count' => count($items)
  1436. ]);
  1437. return $result;
  1438. }
  1439. /**
  1440. * 标准化题型
  1441. */
  1442. private function normalizeQuestionType(string $type): string
  1443. {
  1444. $t = strtolower(trim($type));
  1445. return match (true) {
  1446. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  1447. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  1448. default => 'answer',
  1449. };
  1450. }
  1451. /**
  1452. * 保存PDF URL到数据库
  1453. */
  1454. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  1455. {
  1456. try {
  1457. $paper = Paper::where('paper_id', $paperId)->first();
  1458. if ($paper) {
  1459. $paper->update([$field => $url]);
  1460. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  1461. 'paper_id' => $paperId,
  1462. 'field' => $field,
  1463. 'url' => $url,
  1464. ]);
  1465. }
  1466. } catch (\Throwable $e) {
  1467. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  1468. 'paper_id' => $paperId,
  1469. 'field' => $field,
  1470. 'error' => $e->getMessage(),
  1471. ]);
  1472. }
  1473. }
  1474. /**
  1475. * 保存学情分析PDF URL
  1476. */
  1477. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  1478. {
  1479. try {
  1480. if ($recordId) {
  1481. // OCR记录
  1482. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  1483. if ($ocrRecord) {
  1484. $ocrRecord->update(['analysis_pdf_url' => $url]);
  1485. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  1486. 'record_id' => $recordId,
  1487. 'paper_id' => $paperId,
  1488. 'student_id' => $studentId,
  1489. 'url' => $url,
  1490. ]);
  1491. }
  1492. } else {
  1493. // 【修复】同时更新 exam_analysis_results 表和分析报告表
  1494. $updated = \DB::connection('mysql')->table('exam_analysis_results')
  1495. ->where('student_id', $studentId)
  1496. ->where('paper_id', $paperId)
  1497. ->update([
  1498. 'analysis_pdf_url' => $url,
  1499. 'updated_at' => now(),
  1500. ]);
  1501. if ($updated) {
  1502. Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
  1503. 'student_id' => $studentId,
  1504. 'paper_id' => $paperId,
  1505. 'url' => $url,
  1506. 'updated_rows' => $updated,
  1507. ]);
  1508. } else {
  1509. Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
  1510. 'student_id' => $studentId,
  1511. 'paper_id' => $paperId,
  1512. ]);
  1513. }
  1514. // 学生记录 - 使用新的 student_reports 表(备用)
  1515. \App\Models\StudentReport::updateOrCreate(
  1516. [
  1517. 'student_id' => $studentId,
  1518. 'report_type' => 'exam_analysis',
  1519. 'paper_id' => $paperId,
  1520. ],
  1521. [
  1522. 'pdf_url' => $url,
  1523. 'generation_status' => 'completed',
  1524. 'generated_at' => now(),
  1525. 'updated_at' => now(),
  1526. ]
  1527. );
  1528. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
  1529. 'student_id' => $studentId,
  1530. 'paper_id' => $paperId,
  1531. 'url' => $url,
  1532. ]);
  1533. }
  1534. } catch (\Throwable $e) {
  1535. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  1536. 'paper_id' => $paperId,
  1537. 'student_id' => $studentId,
  1538. 'record_id' => $recordId,
  1539. 'error' => $e->getMessage(),
  1540. ]);
  1541. }
  1542. }
  1543. /**
  1544. * 【修复】处理父节点掌握度数据
  1545. * 1. 过滤掉掌握度为0或null的父节点
  1546. * 2. 将kp_code转换为友好的kp_name
  1547. * 3. 构建父子层级关系(只显示本次考试相关的子节点)
  1548. */
  1549. private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
  1550. {
  1551. $processed = [];
  1552. foreach ($parentMasteryLevels as $kpCode => $masteryData) {
  1553. // 兼容不同数据结构:可能是数组或数字
  1554. $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
  1555. $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
  1556. // 过滤零值和空值
  1557. if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
  1558. continue;
  1559. }
  1560. // 获取友好名称
  1561. $kpName = $kpNameMap[$kpCode] ?? $kpCode;
  1562. // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
  1563. $processed[$kpCode] = [
  1564. 'kp_code' => $kpCode,
  1565. 'kp_name' => $kpName,
  1566. 'mastery_level' => round(floatval($masteryLevel), 4),
  1567. 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
  1568. 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
  1569. // 【修复】只获取本次考试涉及的子节点
  1570. 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
  1571. 'level' => $this->calculateKnowledgePointLevel($kpCode),
  1572. ];
  1573. }
  1574. // 按掌握度降序排序
  1575. uasort($processed, function($a, $b) {
  1576. return $b['mastery_level'] <=> $a['mastery_level'];
  1577. });
  1578. return $processed;
  1579. }
  1580. /**
  1581. * 【修复】获取子知识点列表(只返回本次考试涉及的)
  1582. */
  1583. private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
  1584. {
  1585. $children = [];
  1586. try {
  1587. $childCodes = DB::connection('mysql')
  1588. ->table('knowledge_points')
  1589. ->where('parent_kp_code', $parentKpCode)
  1590. ->pluck('kp_code')
  1591. ->toArray();
  1592. foreach ($childCodes as $childCode) {
  1593. // 只包含本次考试涉及的知识点
  1594. if (in_array($childCode, $examKpCodes)) {
  1595. $children[] = [
  1596. 'kp_code' => $childCode,
  1597. 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
  1598. ];
  1599. }
  1600. }
  1601. } catch (\Exception $e) {
  1602. Log::warning('获取子知识点失败', [
  1603. 'parent_kp_code' => $parentKpCode,
  1604. 'error' => $e->getMessage(),
  1605. ]);
  1606. }
  1607. return $children;
  1608. }
  1609. /**
  1610. * 计算知识点层级深度
  1611. */
  1612. private function calculateKnowledgePointLevel(string $kpCode): int
  1613. {
  1614. // 根据kp_code前缀判断层级深度
  1615. // 例如: M (1级) -> M01 (2级) -> M01A (3级)
  1616. if (preg_match('/^[A-Z]+$/', $kpCode)) {
  1617. return 1; // 一级分类,如 M, S, E, G
  1618. } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
  1619. return 2; // 二级分类,如 M01, S02
  1620. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
  1621. return 3; // 三级分类,如 M01A, S02B
  1622. } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
  1623. return 4; // 四级分类,如 M01A1
  1624. }
  1625. return 1; // 默认一级
  1626. }
  1627. /**
  1628. * 构建题目数据(用于PDF生成)
  1629. */
  1630. private function buildQuestionsData(Paper $paper): array
  1631. {
  1632. $paperQuestions = $paper->questions()->orderBy('question_number')->get();
  1633. $questionsData = [];
  1634. foreach ($paperQuestions as $pq) {
  1635. $questionsData[] = [
  1636. 'id' => $pq->question_bank_id,
  1637. 'kp_code' => $pq->knowledge_point,
  1638. 'question_type' => $pq->question_type ?? 'answer',
  1639. 'stem' => $pq->question_text ?? '题目内容缺失',
  1640. 'solution' => $pq->solution ?? '',
  1641. 'answer' => $pq->correct_answer ?? '',
  1642. 'difficulty' => $pq->difficulty ?? 0.5,
  1643. 'score' => $pq->score ?? 5,
  1644. 'tags' => '',
  1645. 'content' => $pq->question_text ?? '',
  1646. ];
  1647. }
  1648. // 获取完整题目详情
  1649. if (!empty($questionsData)) {
  1650. $questionIds = array_column($questionsData, 'id');
  1651. $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
  1652. $responseData = $questionsResponse['data'] ?? [];
  1653. if (!empty($responseData)) {
  1654. $responseDataMap = [];
  1655. foreach ($responseData as $respQ) {
  1656. $responseDataMap[$respQ['id']] = $respQ;
  1657. }
  1658. $questionsData = array_map(function($q) use ($responseDataMap) {
  1659. if (isset($responseDataMap[$q['id']])) {
  1660. $apiData = $responseDataMap[$q['id']];
  1661. $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  1662. $q['content'] = $q['stem'];
  1663. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  1664. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  1665. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  1666. $q['options'] = $apiData['options'] ?? [];
  1667. }
  1668. return $q;
  1669. }, $questionsData);
  1670. }
  1671. }
  1672. // 按题型分类
  1673. $classified = ['choice' => [], 'fill' => [], 'answer' => []];
  1674. foreach ($questionsData as $q) {
  1675. $type = $this->determineQuestionType($q);
  1676. $classified[$type][] = (object) $q;
  1677. }
  1678. return $classified;
  1679. }
  1680. /**
  1681. * 获取学生信息
  1682. */
  1683. private function getStudentInfo(?string $studentId): array
  1684. {
  1685. if (!$studentId) {
  1686. return [
  1687. 'name' => '未知学生',
  1688. 'grade' => '未知年级',
  1689. 'class' => '未知班级'
  1690. ];
  1691. }
  1692. try {
  1693. $student = DB::table('students')
  1694. ->where('student_id', $studentId)
  1695. ->first();
  1696. if ($student) {
  1697. return [
  1698. 'name' => $student->name ?? $studentId,
  1699. 'grade' => $student->grade ?? '未知',
  1700. 'class' => $student->class ?? '未知'
  1701. ];
  1702. }
  1703. } catch (\Exception $e) {
  1704. Log::warning('获取学生信息失败', [
  1705. 'student_id' => $studentId,
  1706. 'error' => $e->getMessage()
  1707. ]);
  1708. }
  1709. return [
  1710. 'name' => $studentId,
  1711. 'grade' => '未知',
  1712. 'class' => '未知'
  1713. ];
  1714. }
  1715. /**
  1716. * 获取教师信息
  1717. */
  1718. private function getTeacherInfo(?string $teacherId): array
  1719. {
  1720. if (!$teacherId) {
  1721. return [
  1722. 'name' => '未知老师',
  1723. 'subject' => '数学'
  1724. ];
  1725. }
  1726. try {
  1727. $teacher = DB::table('teachers')
  1728. ->where('teacher_id', $teacherId)
  1729. ->first();
  1730. if ($teacher) {
  1731. return [
  1732. 'name' => $teacher->name ?? $teacherId,
  1733. 'subject' => $teacher->subject ?? '数学'
  1734. ];
  1735. }
  1736. } catch (\Exception $e) {
  1737. Log::warning('获取教师信息失败', [
  1738. 'teacher_id' => $teacherId,
  1739. 'error' => $e->getMessage()
  1740. ]);
  1741. }
  1742. return [
  1743. 'name' => $teacherId,
  1744. 'subject' => '数学'
  1745. ];
  1746. }
  1747. /**
  1748. * 判断题目类型
  1749. */
  1750. private function determineQuestionType(array $question): string
  1751. {
  1752. $stem = $question['stem'] ?? $question['content'] ?? '';
  1753. $tags = $question['tags'] ?? '';
  1754. // 根据题干内容判断选择题
  1755. if (is_string($stem)) {
  1756. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1757. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1758. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1759. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1760. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  1761. if ($optionCount >= 2) {
  1762. return 'choice';
  1763. }
  1764. // 检查是否有填空标记
  1765. if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
  1766. return 'fill';
  1767. }
  1768. }
  1769. // 根据已有类型字段判断
  1770. if (!empty($question['question_type'])) {
  1771. $type = strtolower(trim($question['question_type']));
  1772. if (in_array($type, ['choice', '选择题'])) return 'choice';
  1773. if (in_array($type, ['fill', '填空题'])) return 'fill';
  1774. if (in_array($type, ['answer', '解答题'])) return 'answer';
  1775. }
  1776. // 默认返回解答题
  1777. return 'answer';
  1778. }
  1779. }