ExamPdfExportService.php 76 KB

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