ExamPdfController.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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. * 1. {"A": "0", "B": "5", "C": "-3", "D": "12"} -> ["0", "5", "-3", "12"]
  14. * 2. [["label": "A", "text": "选项A"], ...] -> ["选项A", "选项B", ...]
  15. * 3. ["A", "B", "C", "D"] -> ["A", "B", "C", "D"]
  16. */
  17. private function normalizeOptions($options): array
  18. {
  19. if (empty($options)) {
  20. return [];
  21. }
  22. // 如果是对象格式 {"A": "值1", "B": "值2", ...}
  23. if (is_array($options) && !isset($options[0])) {
  24. return array_values($options);
  25. }
  26. // 如果是AI生成格式 [{"label": "A", "text": "选项A"}, ...]
  27. if (is_array($options) && isset($options[0]) && is_array($options[0])) {
  28. // 提取text字段,如果不存在则使用整个数组元素
  29. $normalized = [];
  30. foreach ($options as $opt) {
  31. if (isset($opt['text'])) {
  32. $normalized[] = $opt['text'];
  33. } elseif (isset($opt['value'])) {
  34. $normalized[] = $opt['value'];
  35. } else {
  36. // 如果既没有text也没有value,取数组的第一个值
  37. $normalized[] = is_array($opt) ? (string) reset($opt) : (string) $opt;
  38. }
  39. }
  40. return $normalized;
  41. }
  42. // 如果已经是简单数组格式 ["A", "B", "C", "D"]
  43. if (is_array($options)) {
  44. return array_values($options);
  45. }
  46. // 其他情况返回空数组
  47. return [];
  48. }
  49. /**
  50. * 根据题目内容或类型字段判断题型
  51. */
  52. private function determineQuestionType(array $question): string
  53. {
  54. // 优先根据题目内容判断(而不是数据库字段)
  55. $stem = $question['stem'] ?? $question['content'] ?? '';
  56. $tags = $question['tags'] ?? '';
  57. $skills = $question['skills'] ?? [];
  58. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  59. if (is_string($stem)) {
  60. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  61. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  62. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  63. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  64. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  65. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  66. // 至少有2个选项就认为是选择题(降低阈值)
  67. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  68. if ($optionCount >= 2) {
  69. return 'choice';
  70. }
  71. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  72. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  73. return 'choice';
  74. }
  75. }
  76. // 2. 根据技能点判断
  77. if (is_array($skills)) {
  78. $skillsStr = implode(',', $skills);
  79. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  80. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  81. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  82. }
  83. // 3. 根据题目已有类型字段判断(作为后备)
  84. if (!empty($question['question_type'])) {
  85. $type = strtolower(trim($question['question_type']));
  86. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  87. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  88. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  89. }
  90. if (!empty($question['type'])) {
  91. $type = strtolower(trim($question['type']));
  92. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  93. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  94. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  95. }
  96. // 4. 根据标签判断
  97. if (is_string($tags)) {
  98. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  99. return 'choice';
  100. }
  101. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  102. return 'fill';
  103. }
  104. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  105. return 'answer';
  106. }
  107. }
  108. // 5. 填空题特征:连续下划线或明显的填空括号
  109. if (is_string($stem)) {
  110. // 检查填空题特征:连续下划线
  111. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  112. return 'fill';
  113. }
  114. // 空括号填空
  115. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  116. return 'fill';
  117. }
  118. }
  119. // 6. 根据题干内容关键词判断
  120. if (is_string($stem)) {
  121. // 有证明、解答、计算、求证等关键词的是解答题
  122. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  123. return 'answer';
  124. }
  125. }
  126. // 默认是解答题(更安全的默认值)
  127. return 'answer';
  128. }
  129. private function normalizeQuestionTypeValue(string $type): string
  130. {
  131. $type = trim($type);
  132. $lower = strtolower($type);
  133. if (in_array($lower, ['choice', 'single_choice', 'multiple_choice'], true)) {
  134. return 'choice';
  135. }
  136. if (in_array($lower, ['fill', 'blank', 'fill_in_the_blank'], true)) {
  137. return 'fill';
  138. }
  139. if (in_array($lower, ['answer', 'calculation', 'word_problem', 'proof'], true)) {
  140. return 'answer';
  141. }
  142. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  143. return 'choice';
  144. }
  145. if (in_array($type, ['FILL', 'FILL_IN_THE_BLANK'], true)) {
  146. return 'fill';
  147. }
  148. if (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  149. return 'answer';
  150. }
  151. if (in_array($type, ['选择题'], true)) {
  152. return 'choice';
  153. }
  154. if (in_array($type, ['填空题'], true)) {
  155. return 'fill';
  156. }
  157. if (in_array($type, ['解答题', '计算题'], true)) {
  158. return 'answer';
  159. }
  160. return $lower ?: 'answer';
  161. }
  162. /**
  163. * 从题目内容中提取选项
  164. */
  165. private function extractOptions(string $content): array
  166. {
  167. $options = [];
  168. // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
  169. // 支持格式:A.-1 / A. -1 / A、-1 / A:-1
  170. $pattern = '/([A-D])[\.、:.:]\s*(.+?)(?=\s*[A-D][\.、:.:]|$)/su';
  171. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  172. foreach ($matches as $match) {
  173. $optionText = trim($match[2]);
  174. // 移除末尾的换行和空白
  175. $optionText = preg_replace('/\s+$/', '', $optionText);
  176. // 清理 LaTeX 格式但保留内容
  177. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  178. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  179. if (!empty($optionText)) {
  180. $options[] = $optionText;
  181. }
  182. }
  183. }
  184. // 2. 如果上面没提取到,尝试按换行分割
  185. if (empty($options)) {
  186. $lines = preg_split('/[\r\n]+/', $content);
  187. foreach ($lines as $line) {
  188. $line = trim($line);
  189. if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  190. $optionText = trim($match[2]);
  191. if (!empty($optionText)) {
  192. $options[] = $optionText;
  193. }
  194. }
  195. }
  196. }
  197. Log::debug('选项提取结果', [
  198. 'content_preview' => mb_substr($content, 0, 150),
  199. 'options_count' => count($options),
  200. 'options' => $options
  201. ]);
  202. return $options;
  203. }
  204. /**
  205. * 分离题干内容和选项
  206. */
  207. private function separateStemAndOptions(string $content): array
  208. {
  209. // 检测是否有选项(支持多种格式)
  210. $hasOptions = preg_match('/[A-D][\.、:.:]/u', $content);
  211. if (!$hasOptions) {
  212. return [$content, []];
  213. }
  214. // 提取选项
  215. $options = $this->extractOptions($content);
  216. // 如果提取到选项,分离题干
  217. if (!empty($options)) {
  218. // 找到第一个选项的位置,之前的内容是题干
  219. if (preg_match('/^(.+?)(?=[A-D][\.、:.:])/su', $content, $match)) {
  220. $stem = trim($match[1]);
  221. } else {
  222. // 如果正则失败,尝试按位置分割
  223. $stem = $content;
  224. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  225. $pos = mb_strpos($content, $marker);
  226. if ($pos !== false && $pos > 0) {
  227. $stem = trim(mb_substr($content, 0, $pos));
  228. break;
  229. }
  230. }
  231. }
  232. // 移除末尾的括号或空白
  233. $stem = preg_replace('/()\s*$/', '', $stem);
  234. $stem = trim($stem);
  235. return [$stem, $options];
  236. }
  237. return [$content, []];
  238. }
  239. /**
  240. * 根据题型获取默认分数
  241. */
  242. private function getQuestionScore(string $type): int
  243. {
  244. switch ($type) {
  245. case 'choice':
  246. return 5; // 选择题5分
  247. case 'fill':
  248. return 5; // 填空题5分
  249. case 'answer':
  250. return 10; // 解答题10分
  251. default:
  252. return 5;
  253. }
  254. }
  255. /**
  256. * 获取学生信息
  257. */
  258. private function getStudentInfo(?string $studentId): array
  259. {
  260. if (!$studentId) {
  261. return [
  262. 'name' => '未知学生',
  263. 'grade' => '未知年级',
  264. 'class' => '未知班级'
  265. ];
  266. }
  267. try {
  268. $student = DB::table('students')
  269. ->where('student_id', $studentId)
  270. ->first();
  271. if ($student) {
  272. return [
  273. 'name' => $student->name ?? $studentId,
  274. 'grade' => $student->grade ?? '未知',
  275. 'class' => $student->class ?? '未知'
  276. ];
  277. }
  278. } catch (\Exception $e) {
  279. Log::warning('获取学生信息失败', [
  280. 'student_id' => $studentId,
  281. 'error' => $e->getMessage()
  282. ]);
  283. }
  284. return [
  285. 'name' => $studentId,
  286. 'grade' => '未知',
  287. 'class' => '未知'
  288. ];
  289. }
  290. /**
  291. * 为 PDF 预览筛选题目(简化版)
  292. */
  293. private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
  294. {
  295. if (count($questions) <= $targetCount) {
  296. return $questions;
  297. }
  298. // 1. 按题型分类题目
  299. $categorizedQuestions = [
  300. 'choice' => [],
  301. 'fill' => [],
  302. 'answer' => [],
  303. ];
  304. foreach ($questions as $question) {
  305. $type = $this->determineQuestionType($question);
  306. if (!isset($categorizedQuestions[$type])) {
  307. $type = 'answer';
  308. }
  309. $categorizedQuestions[$type][] = $question;
  310. }
  311. // 2. 默认题型配比
  312. $typeRatio = [
  313. '选择题' => 50, // 50%
  314. '填空题' => 30, // 30%
  315. '解答题' => 20, // 20%
  316. ];
  317. // 3. 根据配比选择题目
  318. $selectedQuestions = [];
  319. foreach ($typeRatio as $type => $ratio) {
  320. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  321. $countForType = floor($targetCount * $ratio / 100);
  322. if ($countForType > 0 && !empty($categorizedQuestions[$typeKey])) {
  323. $availableCount = count($categorizedQuestions[$typeKey]);
  324. $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
  325. // 随机选择题目
  326. $keys = array_keys($categorizedQuestions[$typeKey]);
  327. shuffle($keys);
  328. $selectedKeys = array_slice($keys, 0, $takeCount);
  329. foreach ($selectedKeys as $key) {
  330. $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
  331. }
  332. }
  333. }
  334. // 4. 如果数量不足,随机补充
  335. while (count($selectedQuestions) < $targetCount) {
  336. $randomQuestion = $questions[array_rand($questions)];
  337. if (!in_array($randomQuestion, $selectedQuestions)) {
  338. $selectedQuestions[] = $randomQuestion;
  339. }
  340. }
  341. // 5. 限制数量并打乱
  342. shuffle($selectedQuestions);
  343. return array_slice($selectedQuestions, 0, $targetCount);
  344. }
  345. /**
  346. * 获取教师信息
  347. */
  348. private function getTeacherInfo(?string $teacherId): array
  349. {
  350. if (!$teacherId) {
  351. return [
  352. 'name' => '未知教师'
  353. ];
  354. }
  355. try {
  356. $teacher = DB::table('teachers')
  357. ->where('teacher_id', $teacherId)
  358. ->first();
  359. if ($teacher) {
  360. return [
  361. 'name' => $teacher->name ?? $teacherId
  362. ];
  363. }
  364. } catch (\Exception $e) {
  365. Log::warning('获取教师信息失败', [
  366. 'teacher_id' => $teacherId,
  367. 'error' => $e->getMessage()
  368. ]);
  369. }
  370. return [
  371. 'name' => $teacherId
  372. ];
  373. }
  374. public function show(Request $request, $paper_id)
  375. {
  376. // 获取是否显示答案的参数,默认为true
  377. $includeAnswer = $request->query('answer', 'true') !== 'false';
  378. // 使用 Eloquent 模型获取试卷数据
  379. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  380. if (!$paper) {
  381. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  382. $cached = Cache::get('generated_exam_' . $paper_id);
  383. if ($cached) {
  384. Log::info('从缓存获取试卷数据', [
  385. 'paper_id' => $paper_id,
  386. 'cached_count' => count($cached['questions'] ?? []),
  387. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type')
  388. ]);
  389. // 构造临时 Paper 对象
  390. $paper = (object)[
  391. 'paper_id' => $paper_id,
  392. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  393. 'student_id' => $cached['student_id'] ?? null,
  394. 'teacher_id' => $cached['teacher_id'] ?? null,
  395. ];
  396. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  397. $questionsData = $cached['questions'] ?? [];
  398. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  399. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  400. // 为 demo 试卷获取完整的题目详情(包括选项)
  401. if (!empty($questionsData)) {
  402. $questionBankService = app(QuestionBankService::class);
  403. $questionIds = array_column($questionsData, 'id');
  404. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  405. $responseData = $questionsResponse['data'] ?? [];
  406. if (!empty($responseData)) {
  407. $responseDataMap = [];
  408. foreach ($responseData as $respQ) {
  409. $responseDataMap[$respQ['id']] = $respQ;
  410. }
  411. // 合并题库数据
  412. $questionsData = array_map(function($q) use ($responseDataMap) {
  413. if (isset($responseDataMap[$q['id']])) {
  414. $apiData = $responseDataMap[$q['id']];
  415. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  416. // 分离题干和选项
  417. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  418. $q['stem'] = $stem;
  419. $q['content'] = $stem; // 同时设置content字段
  420. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  421. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  422. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  423. // 优先使用API选项,支持多种数据格式
  424. $apiOptions = $apiData['options'] ?? null;
  425. if (!empty($apiOptions)) {
  426. // 标准化options格式为数组值列表
  427. $q['options'] = $this->normalizeOptions($apiOptions);
  428. Log::debug('使用标准化API options', [
  429. 'question_id' => $q['id'],
  430. 'raw_options' => $apiOptions,
  431. 'normalized_options' => $q['options']
  432. ]);
  433. } else {
  434. // 备选:从题干中提取的选项
  435. $q['options'] = $extractedOptions;
  436. Log::debug('使用提取的options', [
  437. 'question_id' => $q['id'],
  438. 'extracted_options' => $extractedOptions
  439. ]);
  440. }
  441. }
  442. return $q;
  443. }, $questionsData);
  444. }
  445. }
  446. if (count($questionsData) > $totalQuestions) {
  447. Log::info('PDF预览时发现题目过多,进行筛选', [
  448. 'paper_id' => $paper_id,
  449. 'cached_count' => count($questionsData),
  450. 'required_count' => $totalQuestions
  451. ]);
  452. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  453. Log::info('筛选后题目数据', [
  454. 'paper_id' => $paper_id,
  455. 'filtered_count' => count($questionsData),
  456. 'filtered_types' => array_column($questionsData, 'question_type')
  457. ]);
  458. }
  459. } else {
  460. abort(404, '试卷未找到');
  461. }
  462. } else {
  463. // 获取试卷题目
  464. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  465. ->orderBy('question_number')
  466. ->get();
  467. Log::info('从数据库获取题目', [
  468. 'paper_id' => $paper_id,
  469. 'question_count' => $paperQuestions->count()
  470. ]);
  471. // 将 paper_questions 表的数据转换为题库格式
  472. $questionsData = [];
  473. foreach ($paperQuestions as $pq) {
  474. $questionsData[] = [
  475. 'id' => $pq->question_bank_id,
  476. 'kp_code' => $pq->knowledge_point,
  477. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  478. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  479. 'solution' => $pq->solution ?? '', // 保存解题思路!
  480. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  481. 'difficulty' => $pq->difficulty ?? 0.5,
  482. 'score' => $pq->score ?? 5, // 包含已计算的分值
  483. 'tags' => '',
  484. 'content' => $pq->question_text ?? '',
  485. ];
  486. }
  487. Log::info('paper_questions表原始数据', [
  488. 'paper_id' => $paper_id,
  489. 'sample_questions' => array_slice($questionsData, 0, 3),
  490. 'all_types' => array_column($questionsData, 'question_type')
  491. ]);
  492. // 如果需要完整题目详情(stem等),可以从题库获取
  493. // 但要严格限制只获取这8道题
  494. if (!empty($questionsData)) {
  495. $questionBankService = app(QuestionBankService::class);
  496. $questionIds = array_column($questionsData, 'id');
  497. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  498. $responseData = $questionsResponse['data'] ?? [];
  499. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  500. if (!empty($responseData)) {
  501. // 创建题库返回数据的映射
  502. $responseDataMap = [];
  503. foreach ($responseData as $respQ) {
  504. $responseDataMap[$respQ['id']] = $respQ;
  505. }
  506. // 遍历所有数据库中的题目,合并题库返回的数据
  507. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  508. // 从题库API获取的详细数据(如果有)
  509. if (isset($responseDataMap[$q['id']])) {
  510. $apiData = $responseDataMap[$q['id']];
  511. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  512. // 分离题干和选项
  513. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  514. // 合并数据,优先使用题库API的 stem、answer、solution、options
  515. $q['stem'] = $stem;
  516. $q['content'] = $stem; // 同时设置content字段
  517. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  518. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  519. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  520. // 优先使用API选项,支持多种数据格式
  521. $apiOptions = $apiData['options'] ?? null;
  522. if (!empty($apiOptions)) {
  523. // 标准化options格式为数组值列表
  524. $q['options'] = $this->normalizeOptions($apiOptions);
  525. Log::debug('使用标准化API options', [
  526. 'question_id' => $q['id'],
  527. 'raw_options' => $apiOptions,
  528. 'normalized_options' => $q['options']
  529. ]);
  530. } else {
  531. // 备选:从题干中提取的选项
  532. $q['options'] = $extractedOptions;
  533. Log::debug('使用提取的options', [
  534. 'question_id' => $q['id'],
  535. 'extracted_options' => $extractedOptions
  536. ]);
  537. }
  538. }
  539. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  540. if (!isset($q['question_type']) || empty($q['question_type'])) {
  541. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  542. if ($dbQuestion && $dbQuestion->question_type) {
  543. $q['question_type'] = $dbQuestion->question_type;
  544. }
  545. }
  546. return $q;
  547. }, $questionsData);
  548. }
  549. }
  550. }
  551. // 按题型分类(使用标准的中学数学试卷格式)
  552. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  553. foreach ($questionsData as $q) {
  554. // 题库API返回的是 stem 字段,不是 content
  555. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  556. // 分离题干和选项
  557. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  558. // 如果从题库API获取了选项,优先使用
  559. $options = $q['options'] ?? $extractedOptions;
  560. $answer = $q['answer'] ?? '';
  561. $solution = $q['solution'] ?? '';
  562. // 优先使用 question_type 字段,如果没有则根据内容智能判断
  563. $type = isset($q['question_type'])
  564. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  565. : $this->determineQuestionType($q);
  566. // 详细调试:记录题目类型判断结果
  567. Log::info('题目类型判断', [
  568. 'question_id' => $q['id'] ?? '',
  569. 'has_question_type' => isset($q['question_type']),
  570. 'question_type_value' => $q['question_type'] ?? null,
  571. 'tags' => $q['tags'] ?? '',
  572. 'stem_length' => mb_strlen($content),
  573. 'stem_preview' => mb_substr($content, 0, 100),
  574. 'has_extracted_options' => !empty($extractedOptions),
  575. 'extracted_options_count' => count($extractedOptions),
  576. 'has_api_options' => isset($q['options']) && !empty($q['options']),
  577. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  578. 'final_options_count' => count($options),
  579. 'determined_type' => $type
  580. ]);
  581. if (!isset($questions[$type])) {
  582. $type = 'answer';
  583. }
  584. // 统一处理数学公式和选项数据
  585. $questionData = [
  586. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  587. 'content' => $content,
  588. 'stem' => $content, // 同时提供stem字段
  589. 'answer' => $answer,
  590. 'solution' => $solution,
  591. 'difficulty' => $q['difficulty'] ?? 0.5,
  592. 'kp_code' => $q['kp_code'] ?? '',
  593. 'tags' => $q['tags'] ?? '',
  594. 'options' => $options, // 使用分离后的选项
  595. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  596. 'question_type' => $type,
  597. ];
  598. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  599. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  600. $questionData['math_processed'] = true; // 添加标记
  601. $qData = (object) $questionData;
  602. $questions[$type][] = $qData;
  603. }
  604. // 调试:记录最终分类结果
  605. Log::info('最终分类结果', [
  606. 'paper_id' => $paper_id,
  607. 'choice_count' => count($questions['choice']),
  608. 'fill_count' => count($questions['fill']),
  609. 'answer_count' => count($questions['answer']),
  610. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer'])
  611. ]);
  612. // 渲染视图
  613. return view('pdf.exam-paper', [
  614. 'paper' => $paper,
  615. 'questions' => $questions,
  616. 'student' => $this->getStudentInfo($paper->student_id),
  617. 'teacher' => $this->getTeacherInfo($paper->teacher_id),
  618. 'includeAnswer' => $includeAnswer
  619. ]);
  620. }
  621. /**
  622. * 判卷视图:题目前带方框,题后附“正确答案+解题思路”
  623. */
  624. public function showGrading(Request $request, $paper_id)
  625. {
  626. // 复用现有逻辑获取题目分类
  627. $includeAnswer = true;
  628. // 直接调用 show 的前置逻辑(简化复用)
  629. $request->merge(['answer' => 'true']);
  630. // 复用 show() 内逻辑获取 questions/paper
  631. // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
  632. // 这里直接复制 show 的主体以保持兼容
  633. // 使用 Eloquent 模型获取试卷数据
  634. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  635. if (!$paper) {
  636. $cached = Cache::get('generated_exam_' . $paper_id);
  637. if (!$cached) {
  638. abort(404, '试卷未找到');
  639. }
  640. $paper = (object)[
  641. 'paper_id' => $paper_id,
  642. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  643. 'student_id' => $cached['student_id'] ?? null,
  644. 'teacher_id' => $cached['teacher_id'] ?? null,
  645. ];
  646. $questionsData = $cached['questions'] ?? [];
  647. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  648. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  649. if (!empty($questionsData)) {
  650. $questionBankService = app(QuestionBankService::class);
  651. $questionIds = array_column($questionsData, 'id');
  652. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  653. $responseData = $questionsResponse['data'] ?? [];
  654. if (!empty($responseData)) {
  655. $responseDataMap = [];
  656. foreach ($responseData as $respQ) {
  657. $responseDataMap[$respQ['id']] = $respQ;
  658. }
  659. $questionsData = array_map(function($q) use ($responseDataMap) {
  660. if (isset($responseDataMap[$q['id']])) {
  661. $apiData = $responseDataMap[$q['id']];
  662. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  663. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  664. $q['stem'] = $stem;
  665. $q['content'] = $stem; // 同时设置content字段
  666. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  667. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  668. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  669. // 优先使用API选项,支持多种数据格式
  670. $apiOptions = $apiData['options'] ?? null;
  671. if (!empty($apiOptions)) {
  672. // 标准化options格式为数组值列表
  673. $q['options'] = $this->normalizeOptions($apiOptions);
  674. Log::debug('使用标准化API options', [
  675. 'question_id' => $q['id'],
  676. 'raw_options' => $apiOptions,
  677. 'normalized_options' => $q['options']
  678. ]);
  679. } else {
  680. // 备选:从题干中提取的选项
  681. $q['options'] = $extractedOptions;
  682. Log::debug('使用提取的options', [
  683. 'question_id' => $q['id'],
  684. 'extracted_options' => $extractedOptions
  685. ]);
  686. }
  687. }
  688. return $q;
  689. }, $questionsData);
  690. }
  691. }
  692. if (count($questionsData) > $totalQuestions) {
  693. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  694. }
  695. } else {
  696. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  697. ->orderBy('question_number')
  698. ->get();
  699. $questionsData = [];
  700. foreach ($paperQuestions as $pq) {
  701. $questionsData[] = [
  702. 'id' => $pq->question_bank_id,
  703. 'kp_code' => $pq->knowledge_point,
  704. 'question_type' => $pq->question_type ?? 'answer',
  705. 'stem' => $pq->question_text ?? '题目内容缺失',
  706. 'solution' => $pq->solution ?? '', // 保存解题思路!
  707. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  708. 'difficulty' => $pq->difficulty ?? 0.5,
  709. 'score' => $pq->score ?? 5,
  710. 'tags' => '',
  711. 'content' => $pq->question_text ?? '',
  712. ];
  713. }
  714. if (!empty($questionsData)) {
  715. $questionBankService = app(QuestionBankService::class);
  716. $questionIds = array_column($questionsData, 'id');
  717. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  718. $responseData = $questionsResponse['data'] ?? [];
  719. if (!empty($responseData)) {
  720. $responseDataMap = [];
  721. foreach ($responseData as $respQ) {
  722. $responseDataMap[$respQ['id']] = $respQ;
  723. }
  724. $questionsData = array_map(function($q) use ($responseDataMap, $paperQuestions) {
  725. if (isset($responseDataMap[$q['id']])) {
  726. $apiData = $responseDataMap[$q['id']];
  727. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  728. list($stem, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  729. $q['stem'] = $stem;
  730. $q['content'] = $stem; // 同时设置content字段
  731. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  732. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  733. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  734. // 优先使用API选项,支持多种数据格式
  735. $apiOptions = $apiData['options'] ?? null;
  736. if (!empty($apiOptions)) {
  737. // 标准化options格式为数组值列表
  738. $q['options'] = $this->normalizeOptions($apiOptions);
  739. Log::debug('使用标准化API options', [
  740. 'question_id' => $q['id'],
  741. 'raw_options' => $apiOptions,
  742. 'normalized_options' => $q['options']
  743. ]);
  744. } else {
  745. // 备选:从题干中提取的选项
  746. $q['options'] = $extractedOptions;
  747. Log::debug('使用提取的options', [
  748. 'question_id' => $q['id'],
  749. 'extracted_options' => $extractedOptions
  750. ]);
  751. }
  752. }
  753. if (!isset($q['question_type']) || empty($q['question_type'])) {
  754. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  755. if ($dbQuestion && $dbQuestion->question_type) {
  756. $q['question_type'] = $dbQuestion->question_type;
  757. }
  758. }
  759. return $q;
  760. }, $questionsData);
  761. }
  762. }
  763. }
  764. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  765. foreach ($questionsData as $q) {
  766. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  767. list($content, $extractedOptions) = $this->separateStemAndOptions($rawContent);
  768. $options = $q['options'] ?? $extractedOptions;
  769. $answer = $q['answer'] ?? '';
  770. $solution = $q['solution'] ?? '';
  771. $type = isset($q['question_type'])
  772. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  773. : $this->determineQuestionType($q);
  774. if (!isset($questions[$type])) {
  775. $type = 'answer';
  776. }
  777. // 统一处理数学公式和选项数据
  778. $questionData = [
  779. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  780. 'content' => $content,
  781. 'stem' => $content, // 同时提供stem字段
  782. 'answer' => $answer,
  783. 'solution' => $solution,
  784. 'difficulty' => $q['difficulty'] ?? 0.5,
  785. 'kp_code' => $q['kp_code'] ?? '',
  786. 'tags' => $q['tags'] ?? '',
  787. 'options' => $options,
  788. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  789. 'question_type' => $type,
  790. ];
  791. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  792. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  793. $questionData['math_processed'] = true; // 添加标记
  794. $qData = (object) $questionData;
  795. $questions[$type][] = $qData;
  796. }
  797. return view('pdf.exam-grading', [
  798. 'paper' => $paper,
  799. 'questions' => $questions,
  800. 'student' => $this->getStudentInfo($paper->student_id),
  801. 'teacher' => $this->getTeacherInfo($paper->teacher_id),
  802. 'includeAnswer' => true,
  803. ]);
  804. }
  805. }