ExamPdfExportService.php 63 KB

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