ExamPdfController.php 20 KB

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