ExamPdfController.php 16 KB

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