ExamPdfExportService.php 60 KB

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