ExamPdfExportService.php 71 KB

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