ExamPdfController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Services\QuestionBankService;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Log;
  8. class ExamPdfController extends Controller
  9. {
  10. /**
  11. * 根据题目类型字段或内容判断题型
  12. */
  13. private function determineQuestionType(array $question): string
  14. {
  15. // 0. 如果题目已有明确类型,直接返回
  16. if (!empty($question['question_type'])) {
  17. $type = $question['question_type'];
  18. if ($type === 'choice' || $type === '选择题') return 'choice';
  19. if ($type === 'fill' || $type === '填空题') return 'fill';
  20. if ($type === 'answer' || $type === '解答题') return 'answer';
  21. }
  22. if (!empty($question['type'])) {
  23. $type = $question['type'];
  24. if ($type === 'choice' || $type === '选择题') return 'choice';
  25. if ($type === 'fill' || $type === '填空题') return 'fill';
  26. if ($type === 'answer' || $type === '解答题') return 'answer';
  27. }
  28. $tags = $question['tags'] ?? '';
  29. $stem = $question['stem'] ?? $question['content'] ?? '';
  30. $skills = $question['skills'] ?? [];
  31. // 1. 根据技能点判断
  32. if (is_array($skills)) {
  33. $skillsStr = implode(',', $skills);
  34. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  35. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  36. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  37. }
  38. // 2. 根据标签判断
  39. if (is_string($tags)) {
  40. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  41. return 'choice';
  42. }
  43. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  44. return 'fill';
  45. }
  46. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  47. return 'answer';
  48. }
  49. }
  50. // 3. 根据题干内容判断 - 必须有明确的选项格式才是选择题
  51. if (is_string($stem)) {
  52. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少3个)
  53. $hasOptionA = preg_match('/\bA\s*[\.、\:]/', $stem) || preg_match('/\(A\)/', $stem);
  54. $hasOptionB = preg_match('/\bB\s*[\.、\:]/', $stem) || preg_match('/\(B\)/', $stem);
  55. $hasOptionC = preg_match('/\bC\s*[\.、\:]/', $stem) || preg_match('/\(C\)/', $stem);
  56. $hasOptionD = preg_match('/\bD\s*[\.、\:]/', $stem) || preg_match('/\(D\)/', $stem);
  57. // 至少有3个选项才认为是选择题
  58. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0);
  59. if ($optionCount >= 3) {
  60. return 'choice';
  61. }
  62. }
  63. // 4. 填空题特征:连续下划线或明显的填空括号
  64. if (is_string($stem)) {
  65. // 检查填空题特征:连续下划线
  66. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  67. return 'fill';
  68. }
  69. // 空括号填空
  70. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  71. return 'fill';
  72. }
  73. }
  74. // 5. 根据题干长度和内容判断
  75. if (is_string($stem)) {
  76. // 有证明、解答、计算、求证等关键词的是解答题
  77. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  78. return 'answer';
  79. }
  80. }
  81. // 默认是解答题(更安全的默认值)
  82. return 'answer';
  83. }
  84. /**
  85. * 从题目内容中提取选项
  86. */
  87. private function extractOptions(string $content): array
  88. {
  89. $options = [];
  90. // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
  91. // 支持格式:A.-1 / A. -1 / A、-1 / A:-1
  92. $pattern = '/([A-D])[\.、:.:]\s*(.+?)(?=\s*[A-D][\.、:.:]|$)/su';
  93. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  94. foreach ($matches as $match) {
  95. $optionText = trim($match[2]);
  96. // 移除末尾的换行和空白
  97. $optionText = preg_replace('/\s+$/', '', $optionText);
  98. // 清理 LaTeX 格式但保留内容
  99. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  100. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  101. if (!empty($optionText)) {
  102. $options[] = $optionText;
  103. }
  104. }
  105. }
  106. // 2. 如果上面没提取到,尝试按换行分割
  107. if (empty($options)) {
  108. $lines = preg_split('/[\r\n]+/', $content);
  109. foreach ($lines as $line) {
  110. $line = trim($line);
  111. if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  112. $optionText = trim($match[2]);
  113. if (!empty($optionText)) {
  114. $options[] = $optionText;
  115. }
  116. }
  117. }
  118. }
  119. Log::debug('选项提取结果', [
  120. 'content_preview' => mb_substr($content, 0, 150),
  121. 'options_count' => count($options),
  122. 'options' => $options
  123. ]);
  124. return $options;
  125. }
  126. /**
  127. * 分离题干内容和选项
  128. */
  129. private function separateStemAndOptions(string $content): array
  130. {
  131. // 检测是否有选项(支持多种格式)
  132. $hasOptions = preg_match('/[A-D][\.、:.:]/u', $content);
  133. if (!$hasOptions) {
  134. return [$content, []];
  135. }
  136. // 提取选项
  137. $options = $this->extractOptions($content);
  138. // 如果提取到选项,分离题干
  139. if (!empty($options)) {
  140. // 找到第一个选项的位置,之前的内容是题干
  141. if (preg_match('/^(.+?)(?=[A-D][\.、:.:])/su', $content, $match)) {
  142. $stem = trim($match[1]);
  143. } else {
  144. // 如果正则失败,尝试按位置分割
  145. $stem = $content;
  146. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  147. $pos = mb_strpos($content, $marker);
  148. if ($pos !== false && $pos > 0) {
  149. $stem = trim(mb_substr($content, 0, $pos));
  150. break;
  151. }
  152. }
  153. }
  154. // 移除末尾的括号或空白
  155. $stem = preg_replace('/()\s*$/', '', $stem);
  156. $stem = trim($stem);
  157. return [$stem, $options];
  158. }
  159. return [$content, []];
  160. }
  161. /**
  162. * 根据题型获取默认分数
  163. */
  164. private function getQuestionScore(string $type): int
  165. {
  166. switch ($type) {
  167. case 'choice':
  168. return 5; // 选择题5分
  169. case 'fill':
  170. return 5; // 填空题5分
  171. case 'answer':
  172. return 10; // 解答题10分
  173. default:
  174. return 5;
  175. }
  176. }
  177. /**
  178. * 获取学生信息
  179. */
  180. private function getStudentInfo(?string $studentId): array
  181. {
  182. if (!$studentId) {
  183. return [
  184. 'name' => '未知学生',
  185. 'grade' => '未知年级',
  186. 'class' => '未知班级'
  187. ];
  188. }
  189. try {
  190. $student = DB::table('students')
  191. ->where('student_id', $studentId)
  192. ->first();
  193. if ($student) {
  194. return [
  195. 'name' => $student->name ?? $studentId,
  196. 'grade' => $student->grade ?? '未知',
  197. 'class' => $student->class ?? '未知'
  198. ];
  199. }
  200. } catch (\Exception $e) {
  201. Log::warning('获取学生信息失败', [
  202. 'student_id' => $studentId,
  203. 'error' => $e->getMessage()
  204. ]);
  205. }
  206. return [
  207. 'name' => $studentId,
  208. 'grade' => '未知',
  209. 'class' => '未知'
  210. ];
  211. }
  212. /**
  213. * 为 PDF 预览筛选题目(简化版)
  214. */
  215. private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
  216. {
  217. if (count($questions) <= $targetCount) {
  218. return $questions;
  219. }
  220. // 1. 按题型分类题目
  221. $categorizedQuestions = [
  222. 'choice' => [],
  223. 'fill' => [],
  224. 'answer' => [],
  225. ];
  226. foreach ($questions as $question) {
  227. $type = $this->determineQuestionType($question);
  228. if (!isset($categorizedQuestions[$type])) {
  229. $type = 'answer';
  230. }
  231. $categorizedQuestions[$type][] = $question;
  232. }
  233. // 2. 默认题型配比
  234. $typeRatio = [
  235. '选择题' => 50, // 50%
  236. '填空题' => 30, // 30%
  237. '解答题' => 20, // 20%
  238. ];
  239. // 3. 根据配比选择题目
  240. $selectedQuestions = [];
  241. foreach ($typeRatio as $type => $ratio) {
  242. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  243. $countForType = floor($targetCount * $ratio / 100);
  244. if ($countForType > 0 && !empty($categorizedQuestions[$typeKey])) {
  245. $availableCount = count($categorizedQuestions[$typeKey]);
  246. $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
  247. // 随机选择题目
  248. $keys = array_keys($categorizedQuestions[$typeKey]);
  249. shuffle($keys);
  250. $selectedKeys = array_slice($keys, 0, $takeCount);
  251. foreach ($selectedKeys as $key) {
  252. $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
  253. }
  254. }
  255. }
  256. // 4. 如果数量不足,随机补充
  257. while (count($selectedQuestions) < $targetCount) {
  258. $randomQuestion = $questions[array_rand($questions)];
  259. if (!in_array($randomQuestion, $selectedQuestions)) {
  260. $selectedQuestions[] = $randomQuestion;
  261. }
  262. }
  263. // 5. 限制数量并打乱
  264. shuffle($selectedQuestions);
  265. return array_slice($selectedQuestions, 0, $targetCount);
  266. }
  267. /**
  268. * 获取教师信息
  269. */
  270. private function getTeacherInfo(?string $teacherId): array
  271. {
  272. if (!$teacherId) {
  273. return [
  274. 'name' => '未知教师'
  275. ];
  276. }
  277. try {
  278. $teacher = DB::table('teachers')
  279. ->where('teacher_id', $teacherId)
  280. ->first();
  281. if ($teacher) {
  282. return [
  283. 'name' => $teacher->name ?? $teacherId
  284. ];
  285. }
  286. } catch (\Exception $e) {
  287. Log::warning('获取教师信息失败', [
  288. 'teacher_id' => $teacherId,
  289. 'error' => $e->getMessage()
  290. ]);
  291. }
  292. return [
  293. 'name' => $teacherId
  294. ];
  295. }
  296. public function show(Request $request, $paper_id)
  297. {
  298. // 使用 Eloquent 模型获取试卷数据
  299. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  300. if (!$paper) {
  301. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  302. $cached = Cache::get('generated_exam_' . $paper_id);
  303. if ($cached) {
  304. Log::info('从缓存获取试卷数据', [
  305. 'paper_id' => $paper_id,
  306. 'cached_count' => count($cached['questions'] ?? []),
  307. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type')
  308. ]);
  309. // 构造临时 Paper 对象
  310. $paper = (object)[
  311. 'paper_id' => $paper_id,
  312. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  313. 'student_id' => $cached['student_id'] ?? null,
  314. 'teacher_id' => $cached['teacher_id'] ?? null,
  315. ];
  316. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  317. $questionsData = $cached['questions'] ?? [];
  318. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  319. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  320. // 为 demo 试卷获取完整的题目详情(包括选项)
  321. if (!empty($questionsData)) {
  322. $questionBankService = app(QuestionBankService::class);
  323. $questionIds = array_column($questionsData, 'id');
  324. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  325. $responseData = $questionsResponse['data'] ?? [];
  326. if (!empty($responseData)) {
  327. $responseDataMap = [];
  328. foreach ($responseData as $respQ) {
  329. $responseDataMap[$respQ['id']] = $respQ;
  330. }
  331. // 合并题库数据
  332. $questionsData = array_map(function($q) use ($responseDataMap) {
  333. if (isset($responseDataMap[$q['id']])) {
  334. $apiData = $responseDataMap[$q['id']];
  335. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  336. // 分离题干和选项
  337. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  338. $q['stem'] = $stem;
  339. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  340. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  341. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  342. $q['options'] = $apiData['options'] ?? $extractedOptions; // 优先使用API选项,备选提取的选项
  343. }
  344. return $q;
  345. }, $questionsData);
  346. }
  347. }
  348. if (count($questionsData) > $totalQuestions) {
  349. Log::info('PDF预览时发现题目过多,进行筛选', [
  350. 'paper_id' => $paper_id,
  351. 'cached_count' => count($questionsData),
  352. 'required_count' => $totalQuestions
  353. ]);
  354. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  355. Log::info('筛选后题目数据', [
  356. 'paper_id' => $paper_id,
  357. 'filtered_count' => count($questionsData),
  358. 'filtered_types' => array_column($questionsData, 'question_type')
  359. ]);
  360. }
  361. } else {
  362. abort(404, '试卷未找到');
  363. }
  364. } else {
  365. // 获取试卷题目
  366. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  367. ->orderBy('question_number')
  368. ->get();
  369. Log::info('从数据库获取题目', [
  370. 'paper_id' => $paper_id,
  371. 'question_count' => $paperQuestions->count()
  372. ]);
  373. // 将 paper_questions 表的数据转换为题库格式
  374. $questionsData = [];
  375. foreach ($paperQuestions as $pq) {
  376. $questionsData[] = [
  377. 'id' => $pq->question_bank_id,
  378. 'kp_code' => $pq->knowledge_point,
  379. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  380. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  381. 'difficulty' => $pq->difficulty ?? 0.5,
  382. 'tags' => '',
  383. 'content' => $pq->question_text ?? '',
  384. ];
  385. }
  386. Log::info('paper_questions表原始数据', [
  387. 'paper_id' => $paper_id,
  388. 'sample_questions' => array_slice($questionsData, 0, 3),
  389. 'all_types' => array_column($questionsData, 'question_type')
  390. ]);
  391. // 如果需要完整题目详情(stem等),可以从题库获取
  392. // 但要严格限制只获取这8道题
  393. if (!empty($questionsData)) {
  394. $questionBankService = app(QuestionBankService::class);
  395. $questionIds = array_column($questionsData, 'id');
  396. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  397. $responseData = $questionsResponse['data'] ?? [];
  398. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  399. if (!empty($responseData)) {
  400. // 创建题库返回数据的映射
  401. $responseDataMap = [];
  402. foreach ($responseData as $respQ) {
  403. $responseDataMap[$respQ['id']] = $respQ;
  404. }
  405. // 遍历所有数据库中的题目,合并题库返回的数据
  406. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  407. // 从题库API获取的详细数据(如果有)
  408. if (isset($responseDataMap[$q['id']])) {
  409. $apiData = $responseDataMap[$q['id']];
  410. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  411. // 分离题干和选项
  412. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  413. // 合并数据,优先使用题库API的 stem、answer、solution、options
  414. $q['stem'] = $stem;
  415. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  416. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  417. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  418. $q['options'] = $apiData['options'] ?? $extractedOptions; // 优先使用API选项,备选提取的选项
  419. }
  420. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  421. if (!isset($q['question_type']) || empty($q['question_type'])) {
  422. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  423. if ($dbQuestion && $dbQuestion->question_type) {
  424. $q['question_type'] = $dbQuestion->question_type;
  425. }
  426. }
  427. return $q;
  428. }, $questionsData);
  429. }
  430. }
  431. }
  432. // 按题型分类(使用标准的中学数学试卷格式)
  433. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  434. foreach ($questionsData as $q) {
  435. // 题库API返回的是 stem 字段,不是 content
  436. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  437. // 分离题干和选项
  438. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  439. // 如果从题库API获取了选项,优先使用
  440. $options = $q['options'] ?? $extractedOptions;
  441. $answer = $q['answer'] ?? '';
  442. $solution = $q['solution'] ?? '';
  443. // 优先使用 question_type 字段,如果没有则根据内容智能判断
  444. $type = $q['question_type'] ?? $this->determineQuestionType($q);
  445. // 详细调试:记录题目类型判断结果
  446. Log::info('题目类型判断', [
  447. 'question_id' => $q['id'] ?? '',
  448. 'has_question_type' => isset($q['question_type']),
  449. 'question_type_value' => $q['question_type'] ?? null,
  450. 'tags' => $q['tags'] ?? '',
  451. 'stem_length' => mb_strlen($content),
  452. 'stem_preview' => mb_substr($content, 0, 100),
  453. 'has_extracted_options' => !empty($extractedOptions),
  454. 'extracted_options_count' => count($extractedOptions),
  455. 'has_api_options' => isset($q['options']) && !empty($q['options']),
  456. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  457. 'final_options_count' => count($options),
  458. 'determined_type' => $type
  459. ]);
  460. if (!isset($questions[$type])) {
  461. $type = 'answer';
  462. }
  463. $qData = (object)[
  464. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  465. 'content' => $content,
  466. 'answer' => $answer,
  467. 'solution' => $solution,
  468. 'difficulty' => $q['difficulty'] ?? 0.5,
  469. 'kp_code' => $q['kp_code'] ?? '',
  470. 'tags' => $q['tags'] ?? '',
  471. 'options' => $options, // 使用分离后的选项
  472. 'score' => $q['score'] ?? $this->getQuestionScore($type), // 优先使用生成时分配的分数
  473. ];
  474. $questions[$type][] = $qData;
  475. }
  476. // 调试:记录最终分类结果
  477. Log::info('最终分类结果', [
  478. 'paper_id' => $paper_id,
  479. 'choice_count' => count($questions['choice']),
  480. 'fill_count' => count($questions['fill']),
  481. 'answer_count' => count($questions['answer']),
  482. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer'])
  483. ]);
  484. // 渲染视图
  485. return view('pdf.exam-paper', [
  486. 'paper' => $paper,
  487. 'questions' => $questions,
  488. 'student' => $this->getStudentInfo($paper->student_id),
  489. 'teacher' => $this->getTeacherInfo($paper->teacher_id)
  490. ]);
  491. }
  492. }