| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957 |
- <?php
- namespace App\Services;
- use App\DTO\ExamAnalysisDataDto;
- use App\DTO\ReportPayloadDto;
- use App\Models\Paper;
- use App\Models\PaperQuestion;
- use App\Models\Student;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\File;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Facades\URL;
- use Symfony\Component\Process\Exception\ProcessSignaledException;
- use Symfony\Component\Process\Exception\ProcessTimedOutException;
- use Symfony\Component\Process\Process;
- /**
- * PDF导出服务(重构版)
- * 负责生成试卷PDF、判卷PDF和学情报告PDF
- */
- class ExamPdfExportService
- {
- public function __construct(
- private readonly LearningAnalyticsService $learningAnalyticsService,
- private readonly QuestionBankService $questionBankService,
- private readonly QuestionServiceApi $questionServiceApi,
- private readonly PdfStorageService $pdfStorageService,
- private readonly MasteryCalculator $masteryCalculator,
- private readonly PdfMerger $pdfMerger
- ) {}
- /**
- * 确保exams目录存在
- */
- private function ensureExamsDirectory(): bool
- {
- $examsDir = storage_path("app/public/exams");
- if (!is_dir($examsDir)) {
- Log::info('ExamPdfExportService: 创建exams目录', ['path' => $examsDir]);
- if (!mkdir($examsDir, 0755, true)) {
- Log::error('ExamPdfExportService: 创建exams目录失败', ['path' => $examsDir]);
- return false;
- }
- Log::info('ExamPdfExportService: exams目录创建成功', ['path' => $examsDir]);
- }
- return true;
- }
- /**
- * 生成试卷 PDF(不含答案)
- */
- public function generateExamPdf(string $paperId): ?string
- {
- Log::info('generateExamPdf 开始:', ['paper_id' => $paperId]);
- // 返回页面URL(用于数据库保存)
- $pageUrl = route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
- Log::info('generateExamPdf 页面URL:', ['paper_id' => $paperId, 'url' => $pageUrl]);
- // 将页面URL写入数据库
- $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $pageUrl);
- // 生成PDF文件(用于合并,不上传云存储)
- $pdfPath = storage_path("app/public/exams/{$paperId}_exam.pdf");
- // 【修复】确保exams目录存在
- if (!$this->ensureExamsDirectory()) {
- return null;
- }
- Log::info('ExamPdfExportService: 开始生成试卷PDF', ['path' => $pdfPath, 'url' => $pageUrl]);
- $pdfBinary = $this->buildPdfFromUrl($pageUrl);
- if (!$pdfBinary) {
- Log::error('ExamPdfExportService: 生成试卷PDF失败', ['url' => $pageUrl]);
- return null;
- }
- Log::info('ExamPdfExportService: PDF生成成功,开始写入文件', ['path' => $pdfPath, 'size' => strlen($pdfBinary)]);
- $result = file_put_contents($pdfPath, $pdfBinary);
- if ($result === false) {
- Log::error('ExamPdfExportService: 写入试卷PDF文件失败', ['path' => $pdfPath]);
- return null;
- }
- // 【关键修复】验证文件是否真的写入成功
- if (!file_exists($pdfPath)) {
- Log::error('ExamPdfExportService: 文件写入后不存在', ['path' => $pdfPath, 'result' => $result]);
- return null;
- }
- Log::info('ExamPdfExportService: 试卷PDF文件写入成功', ['path' => $pdfPath, 'size' => $result]);
- // 返回页面URL(不是PDF URL)
- return $pageUrl;
- }
- /**
- * 生成判卷 PDF(含答案与解析)
- */
- public function generateGradingPdf(string $paperId): ?string
- {
- Log::info('generateGradingPdf 开始:', ['paper_id' => $paperId]);
- // 返回页面URL(用于数据库保存)
- $pageUrl = route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
- Log::info('generateGradingPdf 页面URL:', ['paper_id' => $paperId, 'url' => $pageUrl]);
- // 将页面URL写入数据库
- $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $pageUrl);
- // 生成PDF文件(用于合并,不上传云存储)
- $pdfPath = storage_path("app/public/exams/{$paperId}_grading.pdf");
- // 【修复】确保exams目录存在
- if (!$this->ensureExamsDirectory()) {
- return null;
- }
- Log::info('ExamPdfExportService: 开始生成判卷PDF', ['path' => $pdfPath, 'url' => $pageUrl]);
- $pdfBinary = $this->buildPdfFromUrl($pageUrl);
- if (!$pdfBinary) {
- Log::error('ExamPdfExportService: 生成判卷PDF失败', ['url' => $pageUrl]);
- return null;
- }
- Log::info('ExamPdfExportService: 判卷PDF生成成功,开始写入文件', ['path' => $pdfPath, 'size' => strlen($pdfBinary)]);
- $result = file_put_contents($pdfPath, $pdfBinary);
- if ($result === false) {
- Log::error('ExamPdfExportService: 写入判卷PDF文件失败', ['path' => $pdfPath]);
- return null;
- }
- // 【关键修复】验证文件是否真的写入成功
- if (!file_exists($pdfPath)) {
- Log::error('ExamPdfExportService: 判卷文件写入后不存在', ['path' => $pdfPath, 'result' => $result]);
- return null;
- }
- Log::info('ExamPdfExportService: 判卷PDF文件写入成功', ['path' => $pdfPath, 'size' => $result]);
- // 返回页面URL(不是PDF URL)
- return $pageUrl;
- }
- /**
- * 生成合并PDF(试卷 + 判卷)
- * 先分别生成两个PDF,然后合并
- * 【优化】添加进度回调支持和快速合并模式
- * 【修复】优化临时文件清理逻辑,确保合并成功后才删除源文件
- */
- public function generateMergedPdf(string $paperId, ?callable $progressCallback = null): ?string
- {
- Log::info('generateMergedPdf 开始:', ['paper_id' => $paperId]);
- // 【新增】快速幂等性检查:如果all_pdf_url已存在,直接返回
- $existingPaper = \App\Models\Paper::where('paper_id', $paperId)->first();
- if ($existingPaper && $existingPaper->all_pdf_url) {
- Log::info('【快速返回】合并PDF已存在,无需重新生成', [
- 'paper_id' => $paperId,
- 'existing_url' => $existingPaper->all_pdf_url
- ]);
- if ($progressCallback) {
- $progressCallback(100, '合并PDF已存在,直接返回');
- }
- return $existingPaper->all_pdf_url;
- }
- if ($progressCallback) {
- $progressCallback(0, '准备合并PDF...');
- }
- $tempDir = storage_path("app/temp");
- if (!is_dir($tempDir)) {
- mkdir($tempDir, 0755, true);
- }
- $examPdfPath = null;
- $gradingPdfPath = null;
- $mergedPdfPath = null;
- $mergeSuccess = false;
- $uploadSuccess = false;
- try {
- // 【修复】不重复生成PDF,直接使用已有的文件
- // 假设PDF已经通过generateExamPdf和generateGradingPdf生成过了
- // 获取数据库中的页面URL(用于记录)
- $paper = \App\Models\Paper::where('paper_id', $paperId)->first();
- $examPdfUrl = $paper?->exam_pdf_url;
- $gradingPdfUrl = $paper?->grading_pdf_url;
- if (!$examPdfUrl || !$gradingPdfUrl) {
- Log::warning('ExamPdfExportService: 未找到PDF页面URL,可能尚未生成', [
- 'paper_id' => $paperId,
- 'exam_pdf_url' => $examPdfUrl,
- 'grading_pdf_url' => $gradingPdfUrl
- ]);
- }
- Log::info('使用本地PDF文件进行合并', [
- 'exam_url' => $examPdfUrl,
- 'grading_url' => $gradingPdfUrl
- ]);
- if ($progressCallback) {
- $progressCallback(10, '验证PDF文件...');
- }
- // 直接使用本地PDF文件
- $examPdfPath = storage_path("app/public/exams/{$paperId}_exam.pdf");
- $gradingPdfPath = storage_path("app/public/exams/{$paperId}_grading.pdf");
- // 验证文件是否存在
- Log::info('ExamPdfExportService: 检查PDF文件是否存在', [
- 'exam_pdf' => $examPdfPath,
- 'exam_exists' => file_exists($examPdfPath),
- 'grading_pdf' => $gradingPdfPath,
- 'grading_exists' => file_exists($gradingPdfPath)
- ]);
- if (!file_exists($examPdfPath)) {
- Log::error('ExamPdfExportService: 试卷PDF文件不存在', [
- 'path' => $examPdfUrl,
- 'local_path' => $examPdfPath,
- 'directory_exists' => is_dir(dirname($examPdfPath)),
- 'directory_contents' => is_dir(dirname($examPdfPath)) ? scandir(dirname($examPdfPath)) : null
- ]);
- return null;
- }
- if (!file_exists($gradingPdfPath)) {
- Log::error('ExamPdfExportService: 判卷PDF文件不存在', [
- 'path' => $gradingPdfUrl,
- 'local_path' => $gradingPdfPath,
- 'directory_exists' => is_dir(dirname($gradingPdfPath)),
- 'directory_contents' => is_dir(dirname($gradingPdfPath)) ? scandir(dirname($gradingPdfPath)) : null
- ]);
- return null;
- }
- $examSize = filesize($examPdfPath);
- $gradingSize = filesize($gradingPdfPath);
- Log::info('PDF文件验证成功', [
- 'exam_pdf' => $examPdfPath,
- 'grading_pdf' => $gradingPdfPath,
- 'exam_size' => $examSize,
- 'grading_size' => $gradingSize,
- 'total_size' => $examSize + $gradingSize
- ]);
- if ($examSize < 1000 || $gradingSize < 1000) {
- Log::warning('ExamPdfExportService: PDF文件过小,可能生成不完整', [
- 'exam_size' => $examSize,
- 'grading_size' => $gradingSize
- ]);
- }
- if ($progressCallback) {
- $progressCallback(20, '开始合并PDF文件...');
- }
- // 【优化】合并PDF文件 - 使用快速合并模式
- $mergedPdfPath = $tempDir . "/{$paperId}_merged.pdf";
- $merged = $this->pdfMerger->mergeWithProgress([$examPdfPath, $gradingPdfPath], $mergedPdfPath, $progressCallback);
- if (!$merged) {
- Log::error('ExamPdfExportService: PDF文件合并失败', [
- 'tool' => $this->pdfMerger->getMergeTool(),
- 'exam_pdf' => $examPdfPath,
- 'grading_pdf' => $gradingPdfPath,
- 'output_pdf' => $mergedPdfPath
- ]);
- return null;
- }
- // 【新增】验证合并后的PDF内容
- if (!file_exists($mergedPdfPath)) {
- Log::error('ExamPdfExportService: 合并后PDF文件不存在', ['path' => $mergedPdfPath]);
- return null;
- }
- $mergedSize = filesize($mergedPdfPath);
- Log::info('ExamPdfExportService: 合并PDF验证', [
- 'merged_pdf' => $mergedPdfPath,
- 'merged_size' => $mergedSize,
- 'expected_min_size' => max($examSize, $gradingSize) + 1000,
- 'size_valid' => $mergedSize > max($examSize, $gradingSize)
- ]);
- // 验证合并后的PDF大小是否合理(应该大于任一源文件)
- if ($mergedSize <= max($examSize, $gradingSize)) {
- Log::warning('ExamPdfExportService: 合并PDF大小异常,可能合并失败', [
- 'merged_size' => $mergedSize,
- 'exam_size' => $examSize,
- 'grading_size' => $gradingSize,
- 'max_source_size' => max($examSize, $gradingSize)
- ]);
- }
- $mergeSuccess = true;
- if ($progressCallback) {
- $progressCallback(80, '上传合并PDF...');
- }
- // 读取合并后的PDF内容并上传到云存储
- $mergedPdfContent = file_get_contents($mergedPdfPath);
- if (strlen($mergedPdfContent) < 1000) {
- Log::error('ExamPdfExportService: 合并PDF内容过小,上传失败', [
- 'content_size' => strlen($mergedPdfContent),
- 'file_size' => $mergedSize
- ]);
- return null;
- }
- $path = "exams/{$paperId}_all.pdf";
- $mergedUrl = $this->pdfStorageService->put($path, $mergedPdfContent);
- if (!$mergedUrl) {
- Log::error('ExamPdfExportService: 保存合并PDF失败', ['path' => $path]);
- return null;
- }
- Log::info('ExamPdfExportService: 合并PDF上传成功', [
- 'url' => $mergedUrl,
- 'content_size' => strlen($mergedPdfContent),
- 'file_size' => $mergedSize
- ]);
- $uploadSuccess = true;
- // 保存到数据库的all_pdf_url字段
- $this->saveAllPdfUrlToDatabase($paperId, $mergedUrl);
- Log::info('generateMergedPdf 完成:', [
- 'paper_id' => $paperId,
- 'url' => $mergedUrl,
- 'tool' => $this->pdfMerger->getMergeTool(),
- 'exam_size' => $examSize,
- 'grading_size' => $gradingSize,
- 'merged_size' => $mergedSize
- ]);
- return $mergedUrl;
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: 生成合并PDF失败', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- if ($progressCallback) {
- $progressCallback(-1, '合并PDF失败: ' . $e->getMessage());
- }
- return null;
- } finally {
- // 【修复】优化临时文件清理逻辑:
- // 1. 合并失败时不删除源文件,便于重试
- // 2. 合并成功后不立即删除源文件,保留2小时用于调试
- // 3. 保留合并后的文件30分钟用于调试
- if ($mergeSuccess && $uploadSuccess) {
- // 【优化】合并成功且上传成功,不立即删除源文件
- // 改为设置未来删除时间,让源文件保留2小时
- $sourceFiles = [$examPdfPath, $gradingPdfPath];
- foreach ($sourceFiles as $file) {
- if ($file && file_exists($file)) {
- // 设置2小时后删除
- $deletionTime = time() + 7200; // 2小时 = 7200秒
- @touch($file, $deletionTime);
- Log::info('源PDF文件将在2小时后自动删除', [
- 'path' => $file,
- 'deletion_time' => date('Y-m-d H:i:s', $deletionTime)
- ]);
- }
- }
- // 保留合并文件30分钟后删除
- if ($mergedPdfPath && file_exists($mergedPdfPath)) {
- $deletionTime = time() + 1800; // 30分钟后
- @touch($mergedPdfPath, $deletionTime);
- Log::info('合并PDF文件保留30分钟用于调试', [
- 'path' => $mergedPdfPath,
- 'deletion_time' => date('Y-m-d H:i:s', $deletionTime)
- ]);
- }
- } else {
- // 合并失败或上传失败,保留所有文件用于调试
- Log::warning('PDF合并未完全成功,保留临时文件用于调试', [
- 'merge_success' => $mergeSuccess,
- 'upload_success' => $uploadSuccess,
- 'exam_pdf' => $examPdfPath,
- 'grading_pdf' => $gradingPdfPath,
- 'merged_pdf' => $mergedPdfPath,
- 'exam_exists' => $examPdfPath ? file_exists($examPdfPath) : false,
- 'grading_exists' => $gradingPdfPath ? file_exists($gradingPdfPath) : false,
- 'merged_exists' => $mergedPdfPath ? file_exists($mergedPdfPath) : false
- ]);
- }
- Log::debug('PDF合并流程完成', [
- 'merge_success' => $mergeSuccess,
- 'upload_success' => $uploadSuccess
- ]);
- }
- }
- /**
- * 将URL转换为本地文件路径
- */
- private function convertUrlToPath(string $url): ?string
- {
- // 如果是本地存储,URL格式类似:/storage/exams/paper_id_exam.pdf
- // 需要转换为绝对路径
- if (strpos($url, '/storage/') === 0) {
- return public_path(ltrim($url, '/'));
- }
- // 如果是完整路径,直接返回
- if (strpos($url, '/') === 0 && file_exists($url)) {
- return $url;
- }
- // 如果是相对路径,转换为绝对路径
- $path = public_path($url);
- if (file_exists($path)) {
- return $path;
- }
- return null;
- }
- /**
- * 保存合并PDF URL到数据库
- */
- private function saveAllPdfUrlToDatabase(string $paperId, string $url): void
- {
- try {
- \App\Models\Paper::where('paper_id', $paperId)->update([
- 'all_pdf_url' => $url
- ]);
- Log::debug('保存all_pdf_url成功', ['paper_id' => $paperId, 'url' => $url]);
- } catch (\Exception $e) {
- Log::error('保存all_pdf_url失败', [
- 'paper_id' => $paperId,
- 'url' => $url,
- 'error' => $e->getMessage()
- ]);
- throw $e;
- }
- }
- /**
- * 生成学情分析 PDF
- */
- public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
- {
- if (function_exists('set_time_limit')) {
- @set_time_limit(240);
- }
- try {
- // 【调试】打印输入参数
- Log::info('ExamPdfExportService: 开始生成学情分析PDF', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'record_id' => $recordId,
- ]);
- // 构建分析数据
- $analysisData = $this->buildAnalysisData($paperId, $studentId);
- if (!$analysisData) {
- Log::warning('ExamPdfExportService: buildAnalysisData返回空数据', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- ]);
- return null;
- }
- Log::info('ExamPdfExportService: buildAnalysisData返回数据', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'analysisData_keys' => array_keys($analysisData),
- 'mastery_count' => count($analysisData['mastery']['items'] ?? []),
- 'questions_count' => count($analysisData['questions'] ?? []),
- ]);
- // 创建DTO
- $dto = ExamAnalysisDataDto::fromArray($analysisData);
- $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
- // 【调试】打印传给模板的数据
- $templateData = $payloadDto->toArray();
- Log::info('ExamPdfExportService: 传给模板的数据', [
- 'paper' => $templateData['paper'] ?? null,
- 'student' => $templateData['student'] ?? null,
- 'mastery' => $templateData['mastery'] ?? null,
- 'parent_mastery_levels' => $templateData['parent_mastery_levels'] ?? null, // 新增:检查父节点掌握度
- 'questions_count' => count($templateData['questions'] ?? []),
- 'insights_count' => count($templateData['question_insights'] ?? []),
- 'recommendations_count' => count($templateData['recommendations'] ?? []),
- ]);
- // 渲染HTML
- $html = view('exam-analysis.pdf-report', $templateData)->render();
- if (!$html) {
- Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
- return null;
- }
- // 生成PDF
- $pdfBinary = $this->buildPdf($html);
- if (!$pdfBinary) {
- return null;
- }
- // 保存PDF
- $version = time();
- $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
- $url = $this->pdfStorageService->put($path, $pdfBinary);
- if (!$url) {
- Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
- return null;
- }
- // 保存URL到数据库
- $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
- return $url;
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'record_id' => $recordId,
- 'error' => $e->getMessage(),
- 'exception' => get_class($e),
- 'trace' => $e->getTraceAsString(),
- ]);
- return null;
- }
- }
- /**
- * 渲染并存储试卷PDF
- */
- private function renderAndStoreExamPdf(
- string $paperId,
- bool $includeAnswer,
- string $suffix,
- bool $useGradingView = false
- ): ?string {
- // 放宽脚本执行时间
- if (function_exists('set_time_limit')) {
- @set_time_limit(240);
- }
- try {
- $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
- if (!$html) {
- Log::error('ExamPdfExportService: 渲染HTML为空', [
- 'paper_id' => $paperId,
- 'include_answer' => $includeAnswer,
- 'use_grading_view' => $useGradingView,
- ]);
- return null;
- }
- $pdfBinary = $this->buildPdf($html);
- if (!$pdfBinary) {
- Log::error('ExamPdfExportService: buildPdf为空', [
- 'paper_id' => $paperId,
- 'include_answer' => $includeAnswer,
- 'use_grading_view' => $useGradingView,
- ]);
- return null;
- }
- $path = "exams/{$paperId}_{$suffix}.pdf";
- $url = $this->pdfStorageService->put($path, $pdfBinary);
- if (!$url) {
- Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
- return null;
- }
- return $url;
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: 生成PDF失败', [
- 'paper_id' => $paperId,
- 'suffix' => $suffix,
- 'error' => $e->getMessage(),
- 'exception' => get_class($e),
- 'trace' => $e->getTraceAsString(),
- ]);
- return null;
- }
- }
- /**
- * 渲染试卷HTML(重构版)
- */
- private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
- {
- // 直接构造请求URL,使用路由生成HTML
- $routeName = $useGradingView
- ? 'filament.admin.auth.intelligent-exam.grading'
- : 'filament.admin.auth.intelligent-exam.pdf';
- $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
- // 使用HTTP客户端获取渲染后的HTML
- try {
- $response = Http::get($url);
- if ($response->successful()) {
- $html = $response->body();
- if (!empty(trim($html))) {
- return $this->ensureUtf8Html($html);
- } else {
- Log::warning('ExamPdfExportService: HTTP返回的HTML为空,使用备用方案', [
- 'paper_id' => $paperId,
- 'url' => $url,
- ]);
- }
- }
- } catch (\Exception $e) {
- Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage(),
- ]);
- }
- // 备用方案:直接渲染视图(如果路由不可用)
- try {
- $paper = Paper::with('questions')->find($paperId);
- if (!$paper) {
- Log::error('ExamPdfExportService: 试卷不存在,备用方案无法渲染', [
- 'paper_id' => $paperId,
- 'include_answer' => $includeAnswer,
- 'use_grading_view' => $useGradingView,
- ]);
- return null;
- }
- // 检查试卷是否有题目
- if ($paper->questions->isEmpty()) {
- Log::error('ExamPdfExportService: 试卷没有题目数据', [
- 'paper_id' => $paperId,
- 'question_count' => 0,
- ]);
- return null;
- }
- $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
- $html = view($viewName, compact('paper'))->render();
- if (empty(trim($html))) {
- Log::error('ExamPdfExportService: 视图渲染结果为空', [
- 'paper_id' => $paperId,
- 'view_name' => $viewName,
- 'question_count' => $paper->questions->count(),
- ]);
- return null;
- }
- return $this->ensureUtf8Html($html);
- } catch (\Exception $e) {
- Log::error('ExamPdfExportService: 备用方案渲染失败', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- return null;
- }
- }
- /**
- * 构建分析数据(重构版)
- * 优先使用本地MySQL数据,减少API依赖
- */
- private function buildAnalysisData(string $paperId, string $studentId): ?array
- {
- // 【关键调试】确认方法被调用
- Log::warning('ExamPdfExportService: buildAnalysisData方法被调用了!', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'timestamp' => now()->toISOString()
- ]);
- $paper = Paper::with(['questions' => function ($query) {
- $query->orderBy('question_number')->orderBy('id');
- }])->find($paperId);
- if (!$paper) {
- Log::warning('ExamPdfExportService: 未找到试卷,将尝试仅基于分析数据生成PDF', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- ]);
- // 【修复】即使试卷不存在,也尝试基于分析数据生成PDF
- $paper = new \stdClass();
- $paper->paper_id = $paperId;
- $paper->paper_name = "学情分析报告_{$studentId}_{$paperId}";
- $paper->question_count = 0;
- $paper->total_score = 0;
- $paper->created_at = now();
- $paper->questions = collect();
- }
- $student = Student::find($studentId);
- $studentInfo = [
- 'id' => $student?->student_id ?? $studentId,
- 'name' => $student?->name ?? $studentId,
- 'grade' => $student?->grade ?? '未知年级',
- 'class' => $student?->class_name ?? '未知班级',
- ];
- // 【修改】直接从本地数据库获取分析数据(不再调用API)
- $analysisData = [];
- // 首先尝试从paper->analysis_id获取
- if (!empty($paper->analysis_id)) {
- Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'analysis_id' => $paper->analysis_id
- ]);
- $analysisRecord = \DB::table('exam_analysis_results')
- ->where('id', $paper->analysis_id)
- ->where('student_id', $studentId)
- ->first();
- if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
- $analysisData = json_decode($analysisRecord->analysis_data, true);
- Log::info('ExamPdfExportService: 成功获取本地分析数据(通过analysis_id)', [
- 'data_size' => strlen($analysisRecord->analysis_data)
- ]);
- } else {
- Log::warning('ExamPdfExportService: 未找到本地分析数据,将尝试其他方式', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'analysis_id' => $paper->analysis_id
- ]);
- }
- }
- // 如果没有analysis_id或未找到数据,直接从exam_analysis_results表查询
- if (empty($analysisData)) {
- Log::info('ExamPdfExportService: 直接从exam_analysis_results表查询分析数据', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId
- ]);
- $analysisRecord = \DB::table('exam_analysis_results')
- ->where('paper_id', $paperId)
- ->where('student_id', $studentId)
- ->first();
- if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
- $analysisData = json_decode($analysisRecord->analysis_data, true);
- Log::info('ExamPdfExportService: 成功获取本地分析数据(直接查询)', [
- 'data_size' => strlen($analysisRecord->analysis_data),
- 'question_count' => count($analysisData['question_analysis'] ?? [])
- ]);
- } else {
- Log::warning('ExamPdfExportService: 未找到任何分析数据,将使用空数据', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId
- ]);
- }
- }
- // 【修复】优先使用analysisData中的knowledge_point_analysis数据
- $masteryData = [];
- $parentMasteryLevels = []; // 新增:父节点掌握度数据
- Log::info('ExamPdfExportService: 开始处理掌握度数据', [
- 'student_id' => $studentId,
- 'analysisData_keys' => array_keys($analysisData),
- 'has_knowledge_point_analysis' => !empty($analysisData['knowledge_point_analysis']),
- ]);
- if (!empty($analysisData['knowledge_point_analysis'])) {
- // 将knowledge_point_analysis转换为buildMasterySummary期望的格式
- foreach ($analysisData['knowledge_point_analysis'] as $kp) {
- $masteryData[] = [
- 'kp_code' => $kp['kp_id'] ?? null,
- 'kp_name' => $kp['kp_id'] ?? '未知知识点',
- 'mastery_level' => $kp['mastery_level'] ?? 0,
- 'mastery_change' => $kp['change'] ?? null,
- ];
- }
- // 【修复】基于所有兄弟节点历史数据计算父节点掌握度,并获取掌握度变化
- try {
- // 获取本次考试涉及的知识点代码列表
- $examKpCodes = array_column($masteryData, 'kp_code');
- Log::info('ExamPdfExportService: 本次考试涉及的知识点', [
- 'count' => count($examKpCodes),
- 'kp_codes' => $examKpCodes
- ]);
- // 获取上一个快照的数据(用于计算变化)
- // 如果没有其他试卷的记录,使用同一试卷的上一次快照
- $lastSnapshot = DB::connection('mysql')
- ->table('knowledge_point_mastery_snapshots')
- ->where('student_id', $studentId)
- ->where('paper_id', $paper->paper_id)
- ->where('snapshot_id', '!=', "snap_{$paper->paper_id}_" . date('YmdHis'))
- ->latest('snapshot_time')
- ->first();
- $previousMasteryData = [];
- if ($lastSnapshot) {
- $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
- foreach ($previousMasteryJson as $kpCode => $data) {
- $previousMasteryData[$kpCode] = [
- 'current_mastery' => $data['current_mastery'] ?? 0,
- 'previous_mastery' => $data['previous_mastery'] ?? null,
- ];
- }
- Log::info('ExamPdfExportService: 获取到上一次快照数据', [
- 'snapshot_time' => $lastSnapshot->snapshot_time,
- 'kp_count' => count($previousMasteryData)
- ]);
- }
- // 为当前知识点添加变化数据
- foreach ($masteryData as &$item) {
- $kpCode = $item['kp_code'];
- if (isset($previousMasteryData[$kpCode])) {
- $previous = floatval($previousMasteryData[$kpCode]['previous_mastery'] ?? 0);
- $current = floatval($item['mastery_level']);
- $item['mastery_change'] = $current - $previous;
- }
- }
- unset($item); // 解除引用
- // 获取所有父节点掌握度
- $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
- $allParentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? [];
- // 计算与本次考试相关的父节点掌握度(基于所有兄弟节点)
- $parentMasteryLevels = [];
- // 【修复】使用数据库查询正确匹配父子关系,而不是字符串前缀
- foreach ($allParentMasteryLevels as $parentKpCode => $parentMastery) {
- // 查询这个父节点的所有子节点
- $childNodes = DB::connection('mysql')
- ->table('knowledge_points')
- ->where('parent_kp_code', $parentKpCode)
- ->pluck('kp_code')
- ->toArray();
- // 检查是否有子节点在本次考试中出现
- $relevantChildren = array_intersect($examKpCodes, $childNodes);
- if (!empty($relevantChildren)) {
- // 【修复】计算父节点变化:基于所有子节点的平均变化
- $childChanges = [];
- foreach ($relevantChildren as $childKpCode) {
- $previousChild = $previousMasteryData[$childKpCode]['previous_mastery'] ?? null;
- $currentChild = null;
- foreach ($masteryData as $item) {
- if ($item['kp_code'] === $childKpCode) {
- $currentChild = $item['mastery_level'];
- break;
- }
- }
- if ($previousChild !== null && $currentChild !== null) {
- $childChanges[] = floatval($currentChild) - floatval($previousChild);
- }
- }
- $avgChange = !empty($childChanges) ? array_sum($childChanges) / count($childChanges) : null;
- // 获取父节点中文名称
- $parentKpInfo = DB::connection('mysql')
- ->table('knowledge_points')
- ->where('kp_code', $parentKpCode)
- ->first();
- $parentMasteryLevels[$parentKpCode] = [
- 'kp_code' => $parentKpCode,
- 'kp_name' => $parentKpInfo->name ?? $parentKpCode,
- 'mastery_level' => $parentMastery,
- 'mastery_percentage' => round($parentMastery * 100, 1),
- 'mastery_change' => $avgChange,
- 'children' => $relevantChildren,
- ];
- }
- }
- Log::info('ExamPdfExportService: 过滤后的父节点掌握度', [
- 'all_parent_count' => count($allParentMasteryLevels),
- 'filtered_parent_count' => count($parentMasteryLevels),
- 'filtered_codes' => array_keys($parentMasteryLevels)
- ]);
- } catch (\Exception $e) {
- Log::warning('ExamPdfExportService: 获取父节点掌握度失败', [
- 'error' => $e->getMessage()
- ]);
- }
- Log::info('ExamPdfExportService: 使用analysisData中的掌握度数据', [
- 'count' => count($masteryData),
- 'masteryData_sample' => !empty($masteryData) ? array_slice($masteryData, 0, 2) : []
- ]);
- } else {
- // 如果没有knowledge_point_analysis,使用MasteryCalculator获取多层级掌握度概览
- try {
- Log::info('ExamPdfExportService: 获取学生多层级掌握度概览', [
- 'student_id' => $studentId
- ]);
- $masteryOverview = $this->masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);
- $masteryData = $masteryOverview['details'] ?? [];
- $parentMasteryLevels = $masteryOverview['parent_mastery_levels'] ?? []; // 获取父节点掌握度
- // 【修复】将对象数组转换为关联数组(避免 stdClass 对象访问错误)
- if (!empty($masteryData) && is_array($masteryData)) {
- $masteryData = array_map(function($item) {
- if (is_object($item)) {
- return [
- 'kp_code' => $item->kp_code ?? null,
- 'kp_name' => $item->kp_name ?? null,
- 'mastery_level' => floatval($item->mastery_level ?? 0),
- 'mastery_change' => $item->mastery_change !== null ? floatval($item->mastery_change) : null,
- ];
- }
- return $item;
- }, $masteryData);
- }
- // 【修复】获取快照数据以计算掌握度变化
- $lastSnapshot = DB::connection('mysql')
- ->table('knowledge_point_mastery_snapshots')
- ->where('student_id', $studentId)
- ->latest('snapshot_time')
- ->first();
- if ($lastSnapshot) {
- $previousMasteryJson = json_decode($lastSnapshot->mastery_data, true);
- foreach ($masteryData as &$item) {
- $kpCode = $item['kp_code'];
- if (isset($previousMasteryJson[$kpCode])) {
- $previous = floatval($previousMasteryJson[$kpCode]['previous_mastery'] ?? 0);
- $current = floatval($item['mastery_level']);
- $item['mastery_change'] = $current - $previous;
- }
- }
- unset($item);
- }
- Log::info('ExamPdfExportService: 成功获取多层级掌握度数据', [
- 'count' => count($masteryData),
- 'parent_count' => count($parentMasteryLevels)
- ]);
- } catch (\Exception $e) {
- Log::error('ExamPdfExportService: 获取掌握度数据失败', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 【修改】使用本地方法获取学习路径推荐(替代API调用)
- $recommendations = [];
- try {
- Log::info('ExamPdfExportService: 获取学习路径推荐', [
- 'student_id' => $studentId
- ]);
- $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
- $recommendations = $learningPaths['recommendations'] ?? [];
- Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
- 'count' => count($recommendations)
- ]);
- } catch (\Exception $e) {
- Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- }
- // 获取知识点名称映射
- $kpNameMap = $this->buildKnowledgePointNameMap();
- Log::info('ExamPdfExportService: 获取知识点名称映射', [
- 'kpNameMap_count' => count($kpNameMap),
- 'kpNameMap_keys_sample' => !empty($kpNameMap) ? array_slice(array_keys($kpNameMap), 0, 5) : []
- ]);
- // 【修复】直接从MySQL数据库获取题目详情(不通过API)
- $questionDetails = $this->getQuestionDetailsFromMySQL($paper);
- // 处理题目数据
- $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
- // 【关键调试】查看buildMasterySummary的返回结果
- $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
- Log::info('ExamPdfExportService: buildMasterySummary返回结果', [
- 'masteryData_count' => count($masteryData),
- 'kpNameMap_count' => count($kpNameMap),
- 'masterySummary_keys' => array_keys($masterySummary),
- 'masterySummary_items_count' => count($masterySummary['items'] ?? []),
- 'masterySummary_items_sample' => !empty($masterySummary['items']) ? array_slice($masterySummary['items'], 0, 2) : []
- ]);
- // 【修复】处理父节点掌握度数据:过滤零值、转换名称、构建层级关系
- $examKpCodes = array_column($masteryData, 'kp_code'); // 本次考试涉及的知识点
- $processedParentMastery = $this->processParentMasteryLevels($parentMasteryLevels, $kpNameMap, $examKpCodes);
- Log::info('ExamPdfExportService: 处理后的父节点掌握度', [
- 'raw_count' => count($parentMasteryLevels),
- 'processed_count' => count($processedParentMastery),
- 'processed_sample' => !empty($processedParentMastery) ? array_slice($processedParentMastery, 0, 3) : []
- ]);
- return [
- 'paper' => [
- 'id' => $paper->paper_id,
- 'name' => $paper->paper_name,
- 'total_questions' => $paper->question_count,
- 'total_score' => $paper->total_score,
- 'created_at' => $paper->created_at,
- ],
- 'student' => $studentInfo,
- 'questions' => $questions,
- 'mastery' => $masterySummary,
- 'parent_mastery_levels' => $processedParentMastery, // 【修复】使用处理后的父节点数据
- 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
- 'recommendations' => $recommendations,
- 'analysis_data' => $analysisData,
- ];
- }
- /**
- * 【修复】直接从PaperQuestion表获取题目详情(不通过API)
- */
- private function getQuestionDetailsFromMySQL(Paper $paper): array
- {
- $details = [];
- Log::info('ExamPdfExportService: 从PaperQuestion表查询题目详情', [
- 'paper_id' => $paper->paper_id,
- 'question_count' => $paper->questions->count()
- ]);
- foreach ($paper->questions as $pq) {
- try {
- // 【关键修复】直接从PaperQuestion对象获取solution和correct_answer
- $detail = [
- 'id' => $pq->question_id,
- 'content' => $pq->question_text,
- 'question_type' => $pq->question_type,
- 'answer' => $pq->correct_answer ?? null, // 【修复】从PaperQuestion获取正确答案
- 'solution' => $pq->solution ?? null, // 【修复】从PaperQuestion获取解题思路
- ];
- $details[(string) ($pq->question_id ?? $pq->id)] = $detail;
- Log::debug('ExamPdfExportService: 成功获取题目详情', [
- 'paper_question_id' => $pq->id,
- 'question_id' => $pq->question_id,
- 'has_answer' => !empty($pq->correct_answer),
- 'has_solution' => !empty($pq->solution),
- 'answer_preview' => $pq->correct_answer ? substr($pq->correct_answer, 0, 50) : null
- ]);
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: 获取题目详情失败', [
- 'paper_question_id' => $pq->id,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- return $details;
- }
- /**
- * 处理题目数据(用于报告)
- */
- private function processQuestionsForReport($paper, array $questionDetails, array $kpNameMap): array
- {
- $grouped = [
- 'choice' => [],
- 'fill' => [],
- 'answer' => [],
- ];
- // 【修复】处理空的试卷(questions可能不存在)
- $questions = $paper->questions ?? collect();
- if ($questions->isEmpty()) {
- Log::info('ExamPdfExportService: 试卷没有题目,返回空数组');
- return $grouped;
- }
- $sortedQuestions = $questions
- ->sortBy(function ($q, int $idx) {
- $number = $q->question_number ?? $idx + 1;
- return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
- });
- foreach ($sortedQuestions as $idx => $question) {
- $kpCode = $question->knowledge_point ?? '';
- $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
- // 【修复】直接从PaperQuestion对象获取solution和correct_answer
- $answer = $question->correct_answer ?? null; // 直接从PaperQuestion获取
- $solution = $question->solution ?? null; // 直接从PaperQuestion获取
- $detail = $questionDetails[(string) ($question->question_id ?? $question->id)] ?? [];
- $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
- $normalizedType = $this->normalizeQuestionType($typeRaw);
- $number = $question->question_number ?? ($idx + 1);
- $payload = [
- 'question_number' => $number,
- 'question_text' => is_array($question->question_text)
- ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
- : ($question->question_text ?? ''),
- 'question_type' => $normalizedType,
- 'knowledge_point' => $kpCode,
- 'knowledge_point_name' => $kpName,
- 'score' => $question->score,
- 'answer' => $answer, // 正确答案
- 'solution' => $solution, // 解题思路
- 'student_answer' => $question->student_answer ?? null, // 【新增】学生答案
- 'correct_answer' => $answer, // 【新增】正确答案
- 'is_correct' => $question->is_correct ?? null, // 【新增】判分结果
- 'score_obtained' => $question->score_obtained ?? null, // 【新增】得分
- ];
- $grouped[$normalizedType][] = $payload;
- // 【调试】记录题目数据
- Log::debug('ExamPdfExportService: 处理题目数据', [
- 'paper_question_id' => $question->id,
- 'question_id' => $question->question_id,
- 'has_answer' => !empty($answer),
- 'has_solution' => !empty($solution),
- 'answer_preview' => $answer ? substr($answer, 0, 50) : null
- ]);
- }
- $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
- // 按卷面顺序重新编号
- foreach ($ordered as $i => &$q) {
- $q['display_number'] = $i + 1;
- }
- unset($q);
- return $ordered;
- }
- /**
- * 构建PDF
- */
- private function buildPdf(string $html): ?string
- {
- Log::info('ExamPdfExportService: buildPdf开始', ['html_size' => strlen($html)]);
- $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
- Log::info('ExamPdfExportService: 创建临时HTML文件', ['tmp_html' => $tmpHtml]);
- $utf8Html = $this->ensureUtf8Html($html);
- file_put_contents($tmpHtml, $utf8Html);
- Log::info('ExamPdfExportService: HTML文件已写入', ['tmp_html' => $tmpHtml, 'size' => filesize($tmpHtml)]);
- // 仅使用Chrome渲染
- Log::info('ExamPdfExportService: 开始调用renderWithChrome', ['tmp_html' => $tmpHtml]);
- $chromePdf = $this->renderWithChrome($tmpHtml);
- Log::info('ExamPdfExportService: renderWithChrome完成', [
- 'pdf_size' => $chromePdf ? strlen($chromePdf) : 0,
- 'pdf_success' => !empty($chromePdf)
- ]);
- @unlink($tmpHtml);
- return $chromePdf;
- }
- /**
- * 从URL生成PDF
- */
- private function buildPdfFromUrl(string $url): ?string
- {
- Log::info('ExamPdfExportService: buildPdfFromUrl开始', ['url' => $url]);
- try {
- $response = Http::get($url);
- Log::info('ExamPdfExportService: HTTP请求完成', [
- 'url' => $url,
- 'status' => $response->status(),
- 'successful' => $response->successful()
- ]);
- if (!$response->successful()) {
- Log::error('ExamPdfExportService: 获取URL内容失败', [
- 'url' => $url,
- 'status_code' => $response->status()
- ]);
- return null;
- }
- $html = $response->body();
- $htmlSize = strlen($html);
- Log::info('ExamPdfExportService: 获取HTML内容成功', [
- 'url' => $url,
- 'html_size' => $htmlSize,
- 'html_preview' => substr($html, 0, 100)
- ]);
- if (empty($html)) {
- Log::error('ExamPdfExportService: URL返回内容为空', ['url' => $url]);
- return null;
- }
- Log::info('ExamPdfExportService: 开始调用buildPdf', ['html_size' => $htmlSize]);
- $pdfBinary = $this->buildPdf($html);
- Log::info('ExamPdfExportService: buildPdf完成', [
- 'pdf_size' => $pdfBinary ? strlen($pdfBinary) : 0,
- 'pdf_success' => !empty($pdfBinary)
- ]);
- return $pdfBinary;
- } catch (\Exception $e) {
- Log::error('ExamPdfExportService: buildPdfFromUrl异常', [
- 'url' => $url,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 使用Chrome渲染PDF
- */
- private function renderWithChrome(string $htmlPath): ?string
- {
- $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
- $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
- $chromeBinary = $this->findChromeBinary();
- if (!$chromeBinary) {
- Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
- return null;
- }
- Log::info('ExamPdfExportService: 开始Chrome渲染', [
- 'html_path' => $htmlPath,
- 'tmp_pdf' => $tmpPdf,
- 'chrome_binary' => $chromeBinary
- ]);
- // 设置运行时目录
- $runtimeHome = sys_get_temp_dir() . '/chrome-home';
- $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
- if (!File::exists($runtimeHome)) {
- @File::makeDirectory($runtimeHome, 0755, true);
- }
- if (!File::exists($runtimeXdg)) {
- @File::makeDirectory($runtimeXdg, 0755, true);
- }
- $process = new Process([
- $chromeBinary,
- '--headless',
- '--disable-gpu',
- '--no-sandbox',
- '--disable-setuid-sandbox',
- '--disable-dev-shm-usage',
- '--no-zygote',
- '--disable-features=VizDisplayCompositor',
- '--disable-software-rasterizer',
- '--disable-extensions',
- '--disable-background-networking',
- '--disable-component-update',
- '--disable-client-side-phishing-detection',
- '--disable-default-apps',
- '--disable-domain-reliability',
- '--disable-sync',
- '--safebrowsing-disable-auto-update',
- '--no-first-run',
- '--no-default-browser-check',
- '--disable-crash-reporter',
- '--disable-print-preview',
- '--disable-features=PrintHeaderFooter',
- '--disable-features=TranslateUI',
- '--disable-features=OptimizationHints',
- '--disable-ipc-flooding-protection',
- '--disable-background-networking',
- '--disable-background-timer-throttling',
- '--disable-backgrounding-occluded-windows',
- '--disable-renderer-backgrounding',
- '--disable-features=AudioServiceOutOfProcess',
- '--user-data-dir=' . $userDataDir,
- '--print-to-pdf=' . $tmpPdf,
- '--print-to-pdf-no-header',
- '--allow-file-access-from-files',
- 'file://' . $htmlPath,
- ], null, [
- 'HOME' => $runtimeHome,
- 'XDG_RUNTIME_DIR' => $runtimeXdg,
- ]);
- // 【修复】减少超时时间,避免队列任务整体超时
- // 队列任务默认60秒超时,给Chrome进程设置45秒超时
- $process->setTimeout(45);
- $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
- try {
- $startedAt = microtime(true);
- Log::info('ExamPdfExportService: Chrome进程启动', [
- 'start_time' => date('Y-m-d H:i:s', (int)$startedAt),
- 'timeout' => 45
- ]);
- $process->start();
- $pdfGenerated = false;
- // 【修复】缩短轮询时间,提高响应速度
- $pollStart = microtime(true);
- $maxPollSeconds = 40; // 缩短到40秒(小于Chrome超时45秒)
- $checkInterval = 100_000; // 100ms检查一次
- while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
- if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
- $pdfGenerated = true;
- Log::info('ExamPdfExportService: PDF文件已生成,提前终止Chrome', [
- 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
- 'pdf_size' => filesize($tmpPdf)
- ]);
- $process->stop(2, $killSignal);
- break;
- }
- usleep($checkInterval);
- }
- $elapsed = microtime(true) - $startedAt;
- Log::info('ExamPdfExportService: Chrome轮询结束', [
- 'elapsed' => round($elapsed, 2) . 's',
- 'is_running' => $process->isRunning(),
- 'pdf_exists' => file_exists($tmpPdf),
- 'pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : 0
- ]);
- // 【优化】强制停止Chrome进程
- if ($process->isRunning()) {
- Log::warning('ExamPdfExportService: Chrome进程仍在运行,强制停止', [
- 'elapsed' => round($elapsed, 2) . 's'
- ]);
- $process->stop(2, $killSignal);
- }
- $process->wait();
- } catch (ProcessTimedOutException $e) {
- Log::error('ExamPdfExportService: Chrome进程超时', [
- 'timeout' => $e->getExceededTimeout(),
- 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
- 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : 0
- ]);
- if ($process->isRunning()) {
- $process->stop(2, $killSignal);
- }
- return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
- } catch (ProcessSignaledException $e) {
- Log::warning('ExamPdfExportService: Chrome进程被信号终止', [
- 'signal' => $e->getSignal(),
- 'elapsed' => round(microtime(true) - $startedAt, 2) . 's'
- ]);
- if ($process->isRunning()) {
- $process->stop(2, $killSignal);
- }
- return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: Chrome渲染异常', [
- 'error' => $e->getMessage(),
- 'elapsed' => round(microtime(true) - $startedAt, 2) . 's',
- 'trace' => $e->getTraceAsString()
- ]);
- if ($process->isRunning()) {
- $process->stop(2, $killSignal);
- }
- return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
- }
- return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
- }
- /**
- * 处理Chrome进程结果
- */
- private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
- {
- $elapsed = $startedAt ? round(microtime(true) - $startedAt, 2) : 0;
- $pdfExists = file_exists($tmpPdf);
- $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
- if (!$process->isSuccessful()) {
- if ($pdfExists && $pdfSize > 0) {
- Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
- 'elapsed' => $elapsed . 's',
- 'exit_code' => $process->getExitCode(),
- 'tmp_pdf_size' => $pdfSize,
- ]);
- } else {
- Log::error('ExamPdfExportService: Chrome渲染失败', [
- 'elapsed' => $elapsed . 's',
- 'exit_code' => $process->getExitCode(),
- 'error' => $process->getErrorOutput(),
- 'tmp_pdf_exists' => $pdfExists,
- 'tmp_pdf_size' => $pdfSize
- ]);
- }
- } else {
- Log::info('ExamPdfExportService: Chrome进程正常结束', [
- 'elapsed' => $elapsed . 's',
- 'exit_code' => $process->getExitCode(),
- 'pdf_exists' => $pdfExists,
- 'pdf_size' => $pdfSize
- ]);
- }
- // 读取PDF内容
- $pdfBinary = null;
- if ($pdfExists && $pdfSize > 0) {
- $pdfBinary = file_get_contents($tmpPdf);
- Log::info('ExamPdfExportService: PDF读取成功', [
- 'size' => strlen($pdfBinary),
- 'elapsed' => $elapsed . 's'
- ]);
- } else {
- Log::error('ExamPdfExportService: PDF文件不存在或为空', [
- 'tmp_pdf' => $tmpPdf,
- 'exists' => $pdfExists,
- 'size' => $pdfSize
- ]);
- }
- // 【优化】确保资源正确释放,使用try-catch包装
- try {
- if ($pdfExists && file_exists($tmpPdf)) {
- @unlink($tmpPdf);
- Log::debug('ExamPdfExportService: 临时PDF文件已删除', ['path' => $tmpPdf]);
- }
- } catch (\Exception $e) {
- Log::warning('ExamPdfExportService: 删除临时PDF文件失败', [
- 'path' => $tmpPdf,
- 'error' => $e->getMessage()
- ]);
- }
- try {
- if ($userDataDir && is_dir($userDataDir)) {
- File::deleteDirectory($userDataDir);
- Log::debug('ExamPdfExportService: Chrome用户数据目录已删除', ['path' => $userDataDir]);
- }
- } catch (\Exception $e) {
- Log::warning('ExamPdfExportService: 删除Chrome用户数据目录失败', [
- 'path' => $userDataDir,
- 'error' => $e->getMessage()
- ]);
- }
- return $pdfBinary ?: null;
- }
- /**
- * 查找Chrome二进制文件
- */
- private function findChromeBinary(): ?string
- {
- $candidates = [
- env('PDF_CHROME_BINARY'),
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- '/usr/bin/google-chrome-stable',
- '/usr/bin/google-chrome',
- '/usr/bin/chromium-browser',
- '/usr/bin/chromium',
- ];
- foreach ($candidates as $path) {
- if ($path && is_file($path) && is_executable($path)) {
- return $path;
- }
- }
- return null;
- }
- /**
- * 确保HTML为UTF-8编码
- */
- private function ensureUtf8Html(string $html): string
- {
- $meta = '<meta charset="UTF-8">';
- if (stripos($html, '<head>') !== false) {
- return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
- }
- return $meta . $html;
- }
- /**
- * 构建知识点名称映射
- */
- private function buildKnowledgePointNameMap(): array
- {
- try {
- $options = $this->questionServiceApi->getKnowledgePointOptions();
- return $options ?: [];
- } catch (\Throwable $e) {
- Log::warning('ExamPdfExportService: 获取知识点名称失败', [
- 'error' => $e->getMessage(),
- ]);
- return [];
- }
- }
- /**
- * 构建掌握度摘要
- */
- private function buildMasterySummary(array $masteryData, array $kpNameMap): array
- {
- Log::info('ExamPdfExportService: buildMasterySummary开始处理', [
- 'masteryData_count' => count($masteryData),
- 'kpNameMap_count' => count($kpNameMap)
- ]);
- $items = [];
- $total = 0;
- $count = 0;
- foreach ($masteryData as $row) {
- $code = $row['kp_code'] ?? null;
- // 【修复】使用kpNameMap转换名称为友好显示名
- $name = $kpNameMap[$code] ?? $row['kp_name'] ?? $code ?: '未知知识点';
- $level = (float)($row['mastery_level'] ?? 0);
- $delta = $row['mastery_change'] ?? null;
- $items[] = [
- 'kp_code' => $code,
- 'kp_name' => $name,
- 'mastery_level' => $level,
- 'mastery_change' => $delta,
- ];
- $total += $level;
- $count++;
- }
- $average = $count > 0 ? round($total / $count, 2) : null;
- // 按掌握度从低到高排序
- if (!empty($items)) {
- usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
- }
- $result = [
- 'items' => $items,
- 'average' => $average,
- 'weak_list' => array_slice($items, 0, 5),
- ];
- Log::info('ExamPdfExportService: buildMasterySummary完成', [
- 'total_count' => $count,
- 'items_count' => count($items)
- ]);
- return $result;
- }
- /**
- * 标准化题型
- */
- private function normalizeQuestionType(string $type): string
- {
- $t = strtolower(trim($type));
- return match (true) {
- str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
- str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
- default => 'answer',
- };
- }
- /**
- * 保存PDF URL到数据库
- */
- private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
- {
- try {
- $paper = Paper::where('paper_id', $paperId)->first();
- if ($paper) {
- $paper->update([$field => $url]);
- Log::info('ExamPdfExportService: PDF URL已写入数据库', [
- 'paper_id' => $paperId,
- 'field' => $field,
- 'url' => $url,
- ]);
- }
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: 写入PDF URL失败', [
- 'paper_id' => $paperId,
- 'field' => $field,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- /**
- * 保存学情分析PDF URL
- */
- private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
- {
- try {
- if ($recordId) {
- // OCR记录
- $ocrRecord = \App\Models\OCRRecord::find($recordId);
- if ($ocrRecord) {
- $ocrRecord->update(['analysis_pdf_url' => $url]);
- Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
- 'record_id' => $recordId,
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'url' => $url,
- ]);
- }
- } else {
- // 【修复】同时更新 exam_analysis_results 表和分析报告表
- $updated = \DB::connection('mysql')->table('exam_analysis_results')
- ->where('student_id', $studentId)
- ->where('paper_id', $paperId)
- ->update([
- 'analysis_pdf_url' => $url,
- 'updated_at' => now(),
- ]);
- if ($updated) {
- Log::info('ExamPdfExportService: 学情分析PDF URL已写入exam_analysis_results表', [
- 'student_id' => $studentId,
- 'paper_id' => $paperId,
- 'url' => $url,
- 'updated_rows' => $updated,
- ]);
- } else {
- Log::warning('ExamPdfExportService: 未找到要更新的学情分析记录', [
- 'student_id' => $studentId,
- 'paper_id' => $paperId,
- ]);
- }
- // 学生记录 - 使用新的 student_reports 表(备用)
- \App\Models\StudentReport::updateOrCreate(
- [
- 'student_id' => $studentId,
- 'report_type' => 'exam_analysis',
- 'paper_id' => $paperId,
- ],
- [
- 'pdf_url' => $url,
- 'generation_status' => 'completed',
- 'generated_at' => now(),
- 'updated_at' => now(),
- ]
- );
- Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表(备用)', [
- 'student_id' => $studentId,
- 'paper_id' => $paperId,
- 'url' => $url,
- ]);
- }
- } catch (\Throwable $e) {
- Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
- 'paper_id' => $paperId,
- 'student_id' => $studentId,
- 'record_id' => $recordId,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- /**
- * 【修复】处理父节点掌握度数据
- * 1. 过滤掉掌握度为0或null的父节点
- * 2. 将kp_code转换为友好的kp_name
- * 3. 构建父子层级关系(只显示本次考试相关的子节点)
- */
- private function processParentMasteryLevels(array $parentMasteryLevels, array $kpNameMap, array $examKpCodes = []): array
- {
- $processed = [];
- foreach ($parentMasteryLevels as $kpCode => $masteryData) {
- // 兼容不同数据结构:可能是数组或数字
- $masteryLevel = is_array($masteryData) ? ($masteryData['mastery_level'] ?? 0) : $masteryData;
- $masteryChange = is_array($masteryData) ? ($masteryData['mastery_change'] ?? null) : null;
- // 过滤零值和空值
- if ($masteryLevel === null || $masteryLevel === 0.0 || $masteryLevel <= 0.001) {
- continue;
- }
- // 获取友好名称
- $kpName = $kpNameMap[$kpCode] ?? $kpCode;
- // 构建父节点数据,包含子节点信息(只显示本次考试相关的)
- $processed[$kpCode] = [
- 'kp_code' => $kpCode,
- 'kp_name' => $kpName,
- 'mastery_level' => round(floatval($masteryLevel), 4),
- 'mastery_percentage' => round(floatval($masteryLevel) * 100, 2),
- 'mastery_change' => $masteryChange !== null ? round(floatval($masteryChange), 4) : null,
- // 【修复】只获取本次考试涉及的子节点
- 'children' => $this->getChildKnowledgePoints($kpCode, $kpNameMap, $examKpCodes),
- 'level' => $this->calculateKnowledgePointLevel($kpCode),
- ];
- }
- // 按掌握度降序排序
- uasort($processed, function($a, $b) {
- return $b['mastery_level'] <=> $a['mastery_level'];
- });
- return $processed;
- }
- /**
- * 【修复】获取子知识点列表(只返回本次考试涉及的)
- */
- private function getChildKnowledgePoints(string $parentKpCode, array $kpNameMap, array $examKpCodes = []): array
- {
- $children = [];
- try {
- $childCodes = DB::connection('mysql')
- ->table('knowledge_points')
- ->where('parent_kp_code', $parentKpCode)
- ->pluck('kp_code')
- ->toArray();
- foreach ($childCodes as $childCode) {
- // 只包含本次考试涉及的知识点
- if (in_array($childCode, $examKpCodes)) {
- $children[] = [
- 'kp_code' => $childCode,
- 'kp_name' => $kpNameMap[$childCode] ?? $childCode,
- ];
- }
- }
- } catch (\Exception $e) {
- Log::warning('获取子知识点失败', [
- 'parent_kp_code' => $parentKpCode,
- 'error' => $e->getMessage(),
- ]);
- }
- return $children;
- }
- /**
- * 计算知识点层级深度
- */
- private function calculateKnowledgePointLevel(string $kpCode): int
- {
- // 根据kp_code前缀判断层级深度
- // 例如: M (1级) -> M01 (2级) -> M01A (3级)
- if (preg_match('/^[A-Z]+$/', $kpCode)) {
- return 1; // 一级分类,如 M, S, E, G
- } elseif (preg_match('/^[A-Z]+\d+$/', $kpCode)) {
- return 2; // 二级分类,如 M01, S02
- } elseif (preg_match('/^[A-Z]+\d+[A-Z]+$/', $kpCode)) {
- return 3; // 三级分类,如 M01A, S02B
- } elseif (preg_match('/^[A-Z]+\d+[A-Z]+\d+$/', $kpCode)) {
- return 4; // 四级分类,如 M01A1
- }
- return 1; // 默认一级
- }
- /**
- * 构建题目数据(用于PDF生成)
- */
- private function buildQuestionsData(Paper $paper): array
- {
- $paperQuestions = $paper->questions()->orderBy('question_number')->get();
- $questionsData = [];
- foreach ($paperQuestions as $pq) {
- $questionsData[] = [
- 'id' => $pq->question_bank_id,
- 'kp_code' => $pq->knowledge_point,
- 'question_type' => $pq->question_type ?? 'answer',
- 'stem' => $pq->question_text ?? '题目内容缺失',
- 'solution' => $pq->solution ?? '',
- 'answer' => $pq->correct_answer ?? '',
- 'difficulty' => $pq->difficulty ?? 0.5,
- 'score' => $pq->score ?? 5,
- 'tags' => '',
- 'content' => $pq->question_text ?? '',
- ];
- }
- // 获取完整题目详情
- if (!empty($questionsData)) {
- $questionIds = array_column($questionsData, 'id');
- $questionsResponse = $this->questionServiceApi->getQuestionsByIds($questionIds);
- $responseData = $questionsResponse['data'] ?? [];
- if (!empty($responseData)) {
- $responseDataMap = [];
- foreach ($responseData as $respQ) {
- $responseDataMap[$respQ['id']] = $respQ;
- }
- $questionsData = array_map(function($q) use ($responseDataMap) {
- if (isset($responseDataMap[$q['id']])) {
- $apiData = $responseDataMap[$q['id']];
- $q['stem'] = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
- $q['content'] = $q['stem'];
- $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
- $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
- $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
- $q['options'] = $apiData['options'] ?? [];
- }
- return $q;
- }, $questionsData);
- }
- }
- // 按题型分类
- $classified = ['choice' => [], 'fill' => [], 'answer' => []];
- foreach ($questionsData as $q) {
- $type = $this->determineQuestionType($q);
- $classified[$type][] = (object) $q;
- }
- return $classified;
- }
- /**
- * 获取学生信息
- */
- private function getStudentInfo(?string $studentId): array
- {
- if (!$studentId) {
- return [
- 'name' => '未知学生',
- 'grade' => '未知年级',
- 'class' => '未知班级'
- ];
- }
- try {
- $student = DB::table('students')
- ->where('student_id', $studentId)
- ->first();
- if ($student) {
- return [
- 'name' => $student->name ?? $studentId,
- 'grade' => $student->grade ?? '未知',
- 'class' => $student->class ?? '未知'
- ];
- }
- } catch (\Exception $e) {
- Log::warning('获取学生信息失败', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- }
- return [
- 'name' => $studentId,
- 'grade' => '未知',
- 'class' => '未知'
- ];
- }
- /**
- * 获取教师信息
- */
- private function getTeacherInfo(?string $teacherId): array
- {
- if (!$teacherId) {
- return [
- 'name' => '未知老师',
- 'subject' => '数学'
- ];
- }
- try {
- $teacher = DB::table('teachers')
- ->where('teacher_id', $teacherId)
- ->first();
- if ($teacher) {
- return [
- 'name' => $teacher->name ?? $teacherId,
- 'subject' => $teacher->subject ?? '数学'
- ];
- }
- } catch (\Exception $e) {
- Log::warning('获取教师信息失败', [
- 'teacher_id' => $teacherId,
- 'error' => $e->getMessage()
- ]);
- }
- return [
- 'name' => $teacherId,
- 'subject' => '数学'
- ];
- }
- /**
- * 判断题目类型
- */
- private function determineQuestionType(array $question): string
- {
- $stem = $question['stem'] ?? $question['content'] ?? '';
- $tags = $question['tags'] ?? '';
- // 根据题干内容判断选择题
- if (is_string($stem)) {
- $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
- $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
- $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
- $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
- $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
- if ($optionCount >= 2) {
- return 'choice';
- }
- // 检查是否有填空标记
- if (preg_match('/(\s*)|\(\s*\)/', $stem)) {
- return 'fill';
- }
- }
- // 根据已有类型字段判断
- if (!empty($question['question_type'])) {
- $type = strtolower(trim($question['question_type']));
- if (in_array($type, ['choice', '选择题'])) return 'choice';
- if (in_array($type, ['fill', '填空题'])) return 'fill';
- if (in_array($type, ['answer', '解答题'])) return 'answer';
- }
- // 默认返回解答题
- return 'answer';
- }
- }
|