IntelligentExamGeneration.php 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Filament\Traits\HasUserRole;
  4. use App\Services\KnowledgeGraphService;
  5. use App\Services\LearningAnalyticsService;
  6. use App\Services\QuestionBankService;
  7. use App\Models\Student;
  8. use BackedEnum;
  9. use Filament\Notifications\Notification;
  10. use Filament\Pages\Page;
  11. use UnitEnum;
  12. use Livewire\Attributes\Computed;
  13. use Livewire\Attributes\On;
  14. use Livewire\Attributes\Reactive;
  15. use Livewire\Component;
  16. use Illuminate\Support\Facades\Cache; // Add Cache import
  17. class IntelligentExamGeneration extends Page
  18. {
  19. use HasUserRole;
  20. protected static ?string $title = '智能出卷';
  21. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document-duplicate';
  22. protected static ?string $navigationLabel = '智能出卷';
  23. protected static string|UnitEnum|null $navigationGroup = '卷子生成管理';
  24. protected static ?int $navigationSort = 1;
  25. protected string $view = 'filament.pages.intelligent-exam-generation-simple';
  26. // 基本配置
  27. public ?string $paperName = '';
  28. public ?string $paperDescription = '';
  29. public ?string $selectedGrade = '初中'; // 初中/七年级/八年级/九年级
  30. public ?string $difficultyCategory = '基础'; // 基础/进阶/竞赛
  31. public int $totalQuestions = 20;
  32. public int $totalScore = 100;
  33. public bool $includeAnswer = false; // 是否生成答案(默认不生成参考答案)
  34. // 知识点和技能点选择
  35. public array $selectedKpCodes = [];
  36. public array $selectedSkills = [];
  37. // 题型配比
  38. public array $questionTypeRatio = [
  39. '选择题' => 40, // 百分比,支持 4:2:4 或 5:2:3
  40. '填空题' => 20,
  41. '解答题' => 40,
  42. ];
  43. // 难度配比
  44. public array $difficultyRatio = [
  45. '基础' => 50, // 百分比
  46. '中等' => 35,
  47. '拔高' => 15,
  48. ];
  49. // 难度多选(空数组表示随机难度)
  50. public array $selectedDifficultyLevels = [];
  51. // 教师和学生相关
  52. public ?string $selectedTeacherId = null;
  53. public ?string $selectedStudentId = null;
  54. public bool $filterByStudentWeakness = false;
  55. // 状态
  56. public bool $isGenerating = false;
  57. public array $generatedQuestions = [];
  58. public ?string $generatedPaperId = null;
  59. #[Computed]
  60. public function canGenerate(): bool
  61. {
  62. return !$this->isGenerating
  63. && $this->totalQuestions >= 6
  64. && !empty($this->selectedTeacherId)
  65. && !empty($this->selectedStudentId);
  66. // 注意:不强制要求选择知识点,没有选择时将按年级或随机生成
  67. }
  68. public function mount(): void
  69. {
  70. // 初始化用户角色检查
  71. $this->initializeUserRole();
  72. // 如果是老师,自动选择当前老师
  73. if ($this->isTeacher) {
  74. $teacherId = $this->getCurrentTeacherId();
  75. if ($teacherId) {
  76. $this->selectedTeacherId = $teacherId;
  77. }
  78. } else {
  79. // 管理员模式:从 URL 参数获取
  80. $this->selectedTeacherId = request()->query('teacher_id', $this->selectedTeacherId);
  81. }
  82. $this->selectedStudentId = request()->query('student_id', $this->selectedStudentId);
  83. // 如果只传了 student_id,补全 teacher_id 以便学生下拉加载
  84. if ($this->selectedStudentId && !$this->selectedTeacherId) {
  85. $student = Student::find($this->selectedStudentId);
  86. if ($student && $student->teacher_id) {
  87. $this->selectedTeacherId = (string) $student->teacher_id;
  88. }
  89. }
  90. // 注意:不初始化 selectedDifficultyLevels,保持为空数组表示随机
  91. // 如果用户不选择任何难度,系统将随机生成题目
  92. }
  93. #[Computed(cache: false)]
  94. public function knowledgePoints(): array
  95. {
  96. try {
  97. $result = app(KnowledgeGraphService::class)->listKnowledgePoints(1, 1000);
  98. $knowledgePoints = $result['data'] ?? [];
  99. \Illuminate\Support\Facades\Log::info('知识点列表获取成功', [
  100. 'count' => count($knowledgePoints),
  101. 'first_item' => !empty($knowledgePoints) ? $knowledgePoints[0] : null
  102. ]);
  103. return $knowledgePoints;
  104. } catch (\Exception $e) {
  105. \Illuminate\Support\Facades\Log::error('获取知识点列表失败', [
  106. 'error' => $e->getMessage()
  107. ]);
  108. return [];
  109. }
  110. }
  111. #[Computed(cache: false)]
  112. public function skills(): array
  113. {
  114. if (empty($this->selectedKpCodes)) {
  115. return [];
  116. }
  117. $allSkills = [];
  118. foreach ($this->selectedKpCodes as $kpCode) {
  119. $kpSkills = app(KnowledgeGraphService::class)->getSkillsByKnowledgePoint($kpCode);
  120. $allSkills = array_merge($allSkills, $kpSkills);
  121. }
  122. return $allSkills;
  123. }
  124. /**
  125. * 获取当前选择的教师名称
  126. */
  127. public function getSelectedTeacherName(): string
  128. {
  129. if (empty($this->selectedTeacherId)) {
  130. return '未选择';
  131. }
  132. try {
  133. $teacher = \App\Models\Teacher::query()
  134. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  135. ->where('teachers.teacher_id', $this->selectedTeacherId)
  136. ->select(
  137. 'teachers.name',
  138. 'teachers.subject',
  139. 'u.username'
  140. )
  141. ->first();
  142. if ($teacher) {
  143. $name = trim($teacher->name ?? $this->selectedTeacherId);
  144. $subject = $teacher->subject ? " ({$teacher->subject})" : '';
  145. $username = $teacher->username ? " [{$teacher->username}]" : '';
  146. return "{$name}{$subject}{$username}";
  147. }
  148. return $this->selectedTeacherId;
  149. } catch (\Exception $e) {
  150. return $this->selectedTeacherId;
  151. }
  152. }
  153. /**
  154. * 获取当前选择的学生名称
  155. */
  156. public function getSelectedStudentName(): string
  157. {
  158. if (empty($this->selectedStudentId) || empty($this->selectedTeacherId)) {
  159. return '未选择';
  160. }
  161. try {
  162. $student = \App\Models\Student::query()
  163. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  164. ->where('students.student_id', $this->selectedStudentId)
  165. ->where('students.teacher_id', $this->selectedTeacherId)
  166. ->select(
  167. 'students.name',
  168. 'students.grade',
  169. 'students.class_name',
  170. 'u.username'
  171. )
  172. ->first();
  173. if ($student) {
  174. $name = trim($student->name ?? $this->selectedStudentId);
  175. $gradeClass = trim("{$student->grade} - {$student->class_name}");
  176. $username = $student->username ? " [{$student->username}]" : '';
  177. return "{$name} ({$gradeClass}){$username}";
  178. }
  179. return $this->selectedStudentId;
  180. } catch (\Exception $e) {
  181. return $this->selectedStudentId;
  182. }
  183. }
  184. #[Computed(cache: false)]
  185. public function teachers(): array
  186. {
  187. try {
  188. $query = \App\Models\Teacher::query()->from('teachers as t')
  189. ->leftJoin('users as u', 't.teacher_id', '=', 'u.user_id')
  190. ->select(
  191. 't.teacher_id',
  192. 't.name',
  193. 't.subject',
  194. 'u.username',
  195. 'u.email'
  196. );
  197. // 如果是老师,只返回自己
  198. if ($this->isTeacher) {
  199. $teacherId = $this->getCurrentTeacherId();
  200. if ($teacherId) {
  201. $query->where('t.teacher_id', $teacherId);
  202. }
  203. }
  204. $teachers = $query->orderBy('t.name')->get();
  205. // 如果有学生但没有对应的老师记录,添加一个"未知老师"条目
  206. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  207. $missingTeacherIds = \App\Models\Student::query()->from('students as s')
  208. ->distinct()
  209. ->whereNotIn('s.teacher_id', $teacherIds)
  210. ->pluck('teacher_id')
  211. ->toArray();
  212. // 转换 Collection 为数组以便合并和排序
  213. $teachersArray = $teachers->all();
  214. if (!empty($missingTeacherIds)) {
  215. foreach ($missingTeacherIds as $missingId) {
  216. $teachersArray[] = (object) [
  217. 'teacher_id' => $missingId,
  218. 'name' => '未知老师 (' . $missingId . ')',
  219. 'subject' => '未知',
  220. 'username' => null,
  221. 'email' => null
  222. ];
  223. }
  224. // 重新排序
  225. usort($teachersArray, function($a, $b) {
  226. return strcmp($a->name, $b->name);
  227. });
  228. return $teachersArray;
  229. }
  230. return $teachersArray;
  231. } catch (\Exception $e) {
  232. \Illuminate\Support\Facades\Log::error('加载老师列表失败', [
  233. 'error' => $e->getMessage()
  234. ]);
  235. return [];
  236. }
  237. }
  238. #[Computed(cache: false)]
  239. public function students(): array
  240. {
  241. if (empty($this->selectedTeacherId)) {
  242. return [];
  243. }
  244. try {
  245. $students = \App\Models\Student::query()->from('students as s')
  246. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  247. ->where('s.teacher_id', $this->selectedTeacherId)
  248. ->select(
  249. 's.student_id',
  250. 's.name',
  251. 's.grade',
  252. 's.class_name',
  253. 'u.username',
  254. 'u.email'
  255. )
  256. ->orderBy('s.grade')
  257. ->orderBy('s.class_name')
  258. ->orderBy('s.name')
  259. ->get()
  260. ->all();
  261. \Illuminate\Support\Facades\Log::info('智能出题页面加载学生列表', [
  262. 'teacher_id' => $this->selectedTeacherId,
  263. 'student_count' => count($students)
  264. ]);
  265. return $students;
  266. } catch (\Exception $e) {
  267. \Illuminate\Support\Facades\Log::error('加载学生列表失败', [
  268. 'teacher_id' => $this->selectedTeacherId,
  269. 'error' => $e->getMessage()
  270. ]);
  271. return [];
  272. }
  273. }
  274. #[Computed(cache: false)]
  275. public function studentWeaknesses(): array
  276. {
  277. if (!$this->selectedStudentId || !$this->filterByStudentWeakness) {
  278. \Illuminate\Support\Facades\Log::info('学生薄弱点未加载', [
  279. 'student_id' => $this->selectedStudentId,
  280. 'filter_enabled' => $this->filterByStudentWeakness
  281. ]);
  282. return [];
  283. }
  284. try {
  285. $weaknesses = app(LearningAnalyticsService::class)->getStudentWeaknesses($this->selectedStudentId);
  286. \Illuminate\Support\Facades\Log::info('获取学生薄弱点成功', [
  287. 'student_id' => $this->selectedStudentId,
  288. 'weakness_count' => count($weaknesses),
  289. 'weaknesses' => $weaknesses
  290. ]);
  291. return $weaknesses;
  292. } catch (\Exception $e) {
  293. \Illuminate\Support\Facades\Log::error('获取学生薄弱点失败', [
  294. 'student_id' => $this->selectedStudentId,
  295. 'error' => $e->getMessage()
  296. ]);
  297. return [];
  298. }
  299. }
  300. /**
  301. * 检查学生是否有薄弱知识点(用于 UI 判断)
  302. */
  303. #[Computed(cache: false)]
  304. public function hasStudentWeaknesses(): bool
  305. {
  306. if (!$this->selectedStudentId) {
  307. return false;
  308. }
  309. try {
  310. $weaknesses = app(LearningAnalyticsService::class)->getStudentWeaknesses($this->selectedStudentId);
  311. return count($weaknesses) > 0;
  312. } catch (\Exception $e) {
  313. return false;
  314. }
  315. }
  316. public function updatedSelectedTeacherId($value)
  317. {
  318. // 当教师选择变化时,清空之前选择的学生
  319. $this->selectedStudentId = null;
  320. $this->filterByStudentWeakness = false;
  321. }
  322. /**
  323. * 监听薄弱点筛选开关变化
  324. * 确保不会重置学生选择
  325. */
  326. public function updatedFilterByStudentWeakness($value)
  327. {
  328. \Illuminate\Support\Facades\Log::info('薄弱点筛选开关变化', [
  329. 'enabled' => $value,
  330. 'student_id' => $this->selectedStudentId,
  331. 'teacher_id' => $this->selectedTeacherId
  332. ]);
  333. // 不需要做任何事情,只是记录日志
  334. // 学生ID和教师ID保持不变
  335. }
  336. /**
  337. * 全选所有薄弱知识点
  338. */
  339. public function selectAllWeaknesses(): void
  340. {
  341. $weaknesses = $this->studentWeaknesses;
  342. if (empty($weaknesses)) {
  343. Notification::make()
  344. ->title('提示')
  345. ->body('暂无薄弱知识点数据')
  346. ->warning()
  347. ->send();
  348. return;
  349. }
  350. // 获取所有薄弱知识点的代码
  351. $kpCodes = array_column($weaknesses, 'kp_code');
  352. // 合并到已选择的知识点中(去重)
  353. $this->selectedKpCodes = array_unique(array_merge($this->selectedKpCodes, $kpCodes));
  354. Notification::make()
  355. ->title('成功')
  356. ->body('已全选 ' . count($kpCodes) . ' 个薄弱知识点')
  357. ->success()
  358. ->send();
  359. \Illuminate\Support\Facades\Log::info('全选薄弱知识点', [
  360. 'student_id' => $this->selectedStudentId,
  361. 'selected_kp_codes' => $kpCodes,
  362. 'total_selected' => count($this->selectedKpCodes)
  363. ]);
  364. }
  365. /**
  366. * 去重题目:基于ID和内容相似度去重
  367. */
  368. protected function deduplicateQuestions(array $questions): array
  369. {
  370. $uniqueQuestions = [];
  371. $seenIds = [];
  372. $seenStems = [];
  373. foreach ($questions as $question) {
  374. $id = $question['id'] ?? $question['question_id'] ?? null;
  375. $stem = $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '';
  376. $difficulty = $question['difficulty'] ?? 0.5;
  377. $kpCode = $question['kp_code'] ?? '';
  378. // 规范化题干:移除多余空白和换行
  379. $normalizedStem = preg_replace('/\s+/', ' ', trim($stem));
  380. $normalizedStem = preg_replace('/^\d+\.\s*/', '', $normalizedStem); // 移除题号
  381. // 创建唯一键:ID + 题干哈希 + 知识点
  382. $key = ($id ? "id:{$id}" : "stem:" . md5($normalizedStem)) . "kp:{$kpCode}";
  383. // 如果是选择题,进一步检查选项是否相同
  384. if ($this->determineQuestionType($question) === 'choice') {
  385. $options = $question['options'] ?? [];
  386. if (!empty($options) && is_array($options)) {
  387. $optionsKey = md5(implode('|', $options));
  388. $key .= "opt:{$optionsKey}";
  389. }
  390. }
  391. // 检查是否已存在
  392. if (isset($seenIds[$key]) || in_array($normalizedStem, $seenStems)) {
  393. \Illuminate\Support\Facades\Log::debug("跳过重复题目", [
  394. 'id' => $id,
  395. 'stem_preview' => mb_substr($normalizedStem, 0, 50)
  396. ]);
  397. continue;
  398. }
  399. // 记录并保留
  400. $seenIds[$key] = true;
  401. $seenStems[] = $normalizedStem;
  402. $uniqueQuestions[] = $question;
  403. }
  404. \Illuminate\Support\Facades\Log::info("题目去重完成", [
  405. 'original_count' => count($questions),
  406. 'unique_count' => count($uniqueQuestions),
  407. 'removed_count' => count($questions) - count($uniqueQuestions)
  408. ]);
  409. return array_values($uniqueQuestions);
  410. }
  411. /**
  412. * 清空所有选择的知识点
  413. */
  414. public function clearSelection(): void
  415. {
  416. $this->selectedKpCodes = [];
  417. Notification::make()
  418. ->title('成功')
  419. ->body('已清空所有选择的知识点')
  420. ->info()
  421. ->send();
  422. \Illuminate\Support\Facades\Log::info('清空知识点选择', [
  423. 'student_id' => $this->selectedStudentId
  424. ]);
  425. }
  426. public function updatedSelectedStudentId($value)
  427. {
  428. // 选择学生后,不要清空知识点选择,保持步骤3的选择有效
  429. // $this->selectedKpCodes = []; // 注释掉这行,避免清空用户选择
  430. // 如果启用了薄弱点筛选,加载但不自动勾选
  431. if ($this->filterByStudentWeakness && $value) {
  432. $weaknesses = $this->studentWeaknesses;
  433. if (empty($weaknesses)) {
  434. Notification::make()
  435. ->title('提示')
  436. ->body('该学生暂无薄弱点数据,您可以在步骤3中手动选择知识点')
  437. ->warning()
  438. ->send();
  439. } else {
  440. Notification::make()
  441. ->title('提示')
  442. ->body('已加载' . count($weaknesses) . '个薄弱知识点,您可以在下方或步骤3中选择要练习的知识点')
  443. ->info()
  444. ->send();
  445. }
  446. }
  447. }
  448. /**
  449. * 监听知识点选择变化
  450. */
  451. public function updatedSelectedKpCodes($value)
  452. {
  453. // 记录调试信息
  454. \Illuminate\Support\Facades\Log::info('selectedKpCodes updated', [
  455. 'count' => count($this->selectedKpCodes),
  456. 'codes' => $this->selectedKpCodes,
  457. 'type' => gettype($value),
  458. 'value' => $value
  459. ]);
  460. }
  461. public function generateExam()
  462. {
  463. \Illuminate\Support\Facades\Log::info('generateExam called with studentId=' . ($this->selectedStudentId ?? 'null'));
  464. $this->validate([
  465. // 'paperName' => 'required|string|max:255', // 已移除必填
  466. 'totalQuestions' => 'required|integer|min:6|max:100',
  467. 'selectedTeacherId' => 'nullable|string', // 可选老师
  468. 'selectedStudentId' => 'nullable|string', // 可选学生
  469. ]);
  470. // 确保题目数量至少6题
  471. if ($this->totalQuestions < 6) {
  472. \Illuminate\Support\Facades\Log::warning('题目数量少于6题,已自动调整为6题', ['original' => $this->totalQuestions]);
  473. $this->totalQuestions = 6;
  474. }
  475. if (empty($this->selectedTeacherId) || empty($this->selectedStudentId)) {
  476. Notification::make()
  477. ->title('请选择教师与学生')
  478. ->body('请选择出卷对应的教师与学生后再生成试卷,确保个性化规则生效。')
  479. ->danger()
  480. ->send();
  481. return;
  482. }
  483. // 若未选知识点,允许随机(后台会按年级或薄弱点补全)
  484. // 自动生成试卷名称 - 使用 paper_id 作为唯一标识
  485. if (empty($this->paperName)) {
  486. // 先生成一个临时名称,保存后会更新为真实的 paper_id
  487. $this->paperName = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
  488. }
  489. $this->isGenerating = true;
  490. try {
  491. // 使用LearningAnalyticsService进行智能出卷
  492. $learningAnalyticsService = app(LearningAnalyticsService::class);
  493. // 准备出卷参数
  494. $examParams = [
  495. 'student_id' => $this->selectedStudentId,
  496. 'grade' => $this->selectedGrade,
  497. 'total_questions' => $this->totalQuestions,
  498. 'kp_codes' => $this->selectedKpCodes,
  499. 'skills' => $this->selectedSkills,
  500. 'question_type_ratio' => $this->questionTypeRatio,
  501. 'difficulty_ratio' => $this->difficultyRatio,
  502. 'difficulty_levels' => $this->selectedDifficultyLevels,
  503. ];
  504. // 调用智能出卷API
  505. $result = $learningAnalyticsService->generateIntelligentExam($examParams);
  506. \Illuminate\Support\Facades\Log::info('智能出卷API返回结果', [
  507. 'success' => $result['success'] ?? false,
  508. 'message' => $result['message'] ?? '未知错误',
  509. 'questions_count' => count($result['questions'] ?? []),
  510. 'target_count' => $this->totalQuestions
  511. ]);
  512. if (!$result['success']) {
  513. throw new \Exception($result['message']);
  514. }
  515. $questions = $result['questions'];
  516. if (count($questions) < $this->totalQuestions) {
  517. // 题库不足时,批量生成题目(使用题库的多AI模型并行生成功能)
  518. $neededCount = $this->totalQuestions - count($questions);
  519. // 生成比需求更多的题目,储备起来供后续使用
  520. $generateCount = max($neededCount, 20); // 至少生成20道题作为储备
  521. \Illuminate\Support\Facades\Log::info("题库题目不足,需要补充 {$neededCount} 道题,准备批量生成 {$generateCount} 道题", [
  522. 'current_count' => count($questions),
  523. 'needed' => $neededCount,
  524. 'will_generate' => $generateCount
  525. ]);
  526. // 只生成一次,生成足够多的题目(题库服务支持多AI模型并行)
  527. $this->batchGenerateQuestions($generateCount);
  528. // 重新从题库获取题目
  529. $questionBankService = app(QuestionBankService::class);
  530. $params = [
  531. 'kp_codes' => implode(',', $this->selectedKpCodes),
  532. 'limit' => $this->totalQuestions * 2 // 获取更多题目用于筛选
  533. ];
  534. if (!empty($this->selectedSkills)) {
  535. $params['skills'] = implode(',', $this->selectedSkills);
  536. }
  537. if ($this->selectedStudentId) {
  538. $params['exclude_student_questions'] = $this->selectedStudentId;
  539. }
  540. $newResponse = $questionBankService->filterQuestions($params);
  541. // 合并题目并去重,只保留有解题思路的题目
  542. if (!empty($newResponse['data'])) {
  543. $existingIds = array_column($questions, 'id');
  544. foreach ($newResponse['data'] as $newQ) {
  545. // 只添加有解题思路的题目
  546. $sol = $newQ['solution'] ?? '';
  547. if (is_array($sol)) $sol = json_encode($sol, JSON_UNESCAPED_UNICODE);
  548. if (!in_array($newQ['id'], $existingIds) && !empty(trim($sol))) {
  549. $questions[] = $newQ;
  550. }
  551. }
  552. }
  553. \Illuminate\Support\Facades\Log::info("批量生成完成,当前题库题目数量: " . count($questions), [
  554. 'generated_count' => $generateCount,
  555. 'total_in_bank' => count($questions)
  556. ]);
  557. }
  558. // 2. 最终去重:确保没有重复题目
  559. $questions = $this->deduplicateQuestions($questions);
  560. \Illuminate\Support\Facades\Log::info("去重后题目数量: " . count($questions));
  561. // 3. 限制试卷题目数量为用户要求的数量
  562. if (count($questions) > $this->totalQuestions) {
  563. // 根据题型配比和难度配比对题目进行筛选和排序
  564. // 注意:如果用户未选择难度(selectedDifficultyLevels为空),则传入null表示随机难度
  565. $effectiveDifficultyCategory = !empty($this->selectedDifficultyLevels) ? $this->difficultyCategory : null;
  566. $questions = $this->selectBestQuestions(
  567. $questions,
  568. $this->totalQuestions,
  569. $effectiveDifficultyCategory,
  570. $this->totalScore,
  571. $this->questionTypeRatio
  572. );
  573. $difficultyLog = $effectiveDifficultyCategory ?? '随机';
  574. \Illuminate\Support\Facades\Log::info("从 " . count($questions) . " 道题中筛选出 " . count($questions) . " 道题,难度: {$difficultyLog}, 总分: {$this->totalScore}");
  575. }
  576. // 3. 检查题型完整性(至少保证每种题型都有题目)
  577. $checkResult = $this->ensureQuestionTypeCompleteness($questions, $this->totalQuestions);
  578. if ($checkResult['missing_types']) {
  579. \Illuminate\Support\Facades\Log::warning("检测到缺失题型,将自动生成", [
  580. 'missing_types' => $checkResult['missing_types'],
  581. 'current_count' => $checkResult['current_count']
  582. ]);
  583. // 批量生成缺失题型的题目
  584. $this->batchGenerateMissingTypes($checkResult['missing_types']);
  585. // 重新获取题目
  586. $questionBankService = app(QuestionBankService::class);
  587. $params = [
  588. 'kp_codes' => implode(',', $this->selectedKpCodes),
  589. 'limit' => $this->totalQuestions * 2
  590. ];
  591. if (!empty($this->selectedSkills)) {
  592. $params['skills'] = implode(',', $this->selectedSkills);
  593. }
  594. if ($this->selectedStudentId) {
  595. $params['exclude_student_questions'] = $this->selectedStudentId;
  596. }
  597. $newResponse = $questionBankService->filterQuestions($params);
  598. if (!empty($newResponse['data'])) {
  599. // 只保留有解题思路的题目
  600. $questionsWithSolution = array_filter($newResponse['data'], function($q) {
  601. $sol = $q['solution'] ?? '';
  602. if (is_array($sol)) $sol = json_encode($sol, JSON_UNESCAPED_UNICODE);
  603. return !empty(trim($sol));
  604. });
  605. $questions = array_merge($questions, array_values($questionsWithSolution));
  606. }
  607. // 再次筛选
  608. $effectiveDifficultyCategory = !empty($this->selectedDifficultyLevels) ? $this->difficultyCategory : null;
  609. $questions = $this->selectBestQuestions(
  610. $questions,
  611. $this->totalQuestions,
  612. $effectiveDifficultyCategory,
  613. $this->totalScore,
  614. $this->questionTypeRatio
  615. );
  616. }
  617. // 2. 最终过滤:确保所有题目都有解题思路
  618. $questions = array_filter($questions, function($q) {
  619. $solution = $q['solution'] ?? '';
  620. // 处理 solution 可能是数组的情况
  621. if (is_array($solution)) {
  622. $solution = json_encode($solution, JSON_UNESCAPED_UNICODE);
  623. }
  624. return !empty(trim($solution));
  625. });
  626. $questions = array_values($questions); // 重新索引数组
  627. \Illuminate\Support\Facades\Log::info('最终过滤后题目数量', [
  628. 'total_questions' => count($questions),
  629. 'filtered_message' => '已过滤掉没有解题思路的题目'
  630. ]);
  631. // 3. 为题目添加类型信息(如果缺失)
  632. foreach ($questions as &$question) {
  633. if (!isset($question['question_type'])) {
  634. $question['question_type'] = $this->determineQuestionType($question);
  635. \Illuminate\Support\Facades\Log::debug('为题目添加类型', [
  636. 'question_id' => $question['id'] ?? '',
  637. 'added_type' => $question['question_type']
  638. ]);
  639. }
  640. }
  641. unset($question); // 释放引用
  642. // 3. 为题目分配分数(根据题型配比和总分)
  643. $questions = $this->assignScoresToQuestions($questions, $this->totalScore, $this->questionTypeRatio);
  644. // 4. 生成试卷数据
  645. $examData = [
  646. 'paper_name' => $this->paperName,
  647. 'paper_description' => $this->paperDescription,
  648. 'difficulty_category' => $this->difficultyCategory,
  649. 'questions' => $questions,
  650. 'total_score' => $this->totalScore,
  651. 'total_questions' => count($questions),
  652. 'student_id' => $this->selectedStudentId,
  653. 'teacher_id' => $this->selectedTeacherId,
  654. ];
  655. // 4. 保存到数据库
  656. $questionBankService = app(QuestionBankService::class);
  657. $paperId = $questionBankService->saveExamToDatabase($examData);
  658. // 如果保存返回 null,使用默认占位 ID,防止 UI 不显示
  659. if (empty($paperId)) {
  660. $paperId = 'demo_' . $this->selectedStudentId . '_' . now()->format('YmdHis');
  661. }
  662. // 使用 paper_id 作为试卷名称
  663. $this->paperName = $paperId;
  664. \Illuminate\Support\Facades\Log::info('Generated paper ID: ' . $paperId);
  665. $this->generatedPaperId = $paperId;
  666. // 将生成的试卷数据缓存,以便 PDF 预览时使用(缓存 1 小时)
  667. \Illuminate\Support\Facades\Log::info('缓存试卷数据', [
  668. 'paper_id' => $paperId,
  669. 'question_count' => count($questions),
  670. 'question_types' => array_column($questions, 'question_type')
  671. ]);
  672. Cache::put('generated_exam_' . $paperId, $examData, now()->addHour());
  673. $this->generatedQuestions = $questions;
  674. $stats = $result['stats'] ?? [];
  675. $message = "已生成包含 " . count($questions) . " 道题的试卷";
  676. if (!empty($stats['weakness_targeted'])) {
  677. $message .= ",其中针对薄弱点 " . $stats['weakness_targeted'] . " 题";
  678. }
  679. Notification::make()
  680. ->title('试卷生成成功')
  681. ->body($message)
  682. ->success()
  683. ->send();
  684. } catch (\Exception $e) {
  685. // 记录错误,生成失败时不创建 paper_id,避免生成无效的 PDF 链接
  686. \Illuminate\Support\Facades\Log::error('生成试卷失败', ['error' => $e->getMessage()]);
  687. $this->generatedPaperId = null; // 不设置 paper_id,避免显示无效链接
  688. $this->generatedQuestions = [];
  689. Notification::make()
  690. ->title('试卷生成失败')
  691. ->body('错误: ' . $e->getMessage() . "\n\n请检查题目数量、知识点选择或网络连接后重试")
  692. ->danger()
  693. ->send();
  694. } finally {
  695. $this->isGenerating = false;
  696. }
  697. }
  698. /**
  699. * 批量生成题目(使用题库的多AI模型并行功能)
  700. */
  701. protected function batchGenerateQuestions(int $count)
  702. {
  703. // 增加PHP脚本执行时间到120秒,给足够时间启动异步任务和等待完成
  704. set_time_limit(120);
  705. $questionBankService = app(QuestionBankService::class);
  706. $generatedTasks = [];
  707. // 只生成一次,使用所有选中的知识点
  708. $allKpCodes = $this->selectedKpCodes;
  709. if (empty($allKpCodes)) {
  710. // 如果没有选中知识点,使用默认知识点
  711. $allKpCodes = ['R01']; // 默认知识点
  712. }
  713. // 对每个知识点生成题目
  714. foreach ($allKpCodes as $kpCode) {
  715. \Illuminate\Support\Facades\Log::info("为知识点 {$kpCode} 生成题目", [
  716. 'count' => $count,
  717. 'skills' => $this->selectedSkills
  718. ]);
  719. $result = $questionBankService->generateIntelligentQuestions([
  720. 'kp_code' => $kpCode,
  721. 'skills' => $this->selectedSkills,
  722. 'count' => $count,
  723. 'difficulty_distribution' => $this->difficultyRatio,
  724. ]);
  725. if ($result['success'] && isset($result['task_id'])) {
  726. $generatedTasks[] = [
  727. 'task_id' => $result['task_id'],
  728. 'kp_code' => $kpCode
  729. ];
  730. \Illuminate\Support\Facades\Log::info("已启动生成任务: {$result['task_id']} for {$kpCode}");
  731. } else {
  732. \Illuminate\Support\Facades\Log::warning("生成任务启动失败", [
  733. 'kp_code' => $kpCode,
  734. 'result' => $result
  735. ]);
  736. }
  737. }
  738. // 等待所有任务完成(最多等待60秒)
  739. if (!empty($generatedTasks)) {
  740. $maxWaitTime = 60; // 增加最大等待时间
  741. $startTime = time();
  742. \Illuminate\Support\Facades\Log::info("等待 {$maxWaitTime} 秒,所有生成任务完成", [
  743. 'tasks' => array_column($generatedTasks, 'task_id')
  744. ]);
  745. while (time() - $startTime < $maxWaitTime) {
  746. $allCompleted = true;
  747. $completedTasks = [];
  748. $runningTasks = [];
  749. foreach ($generatedTasks as $task) {
  750. $taskStatus = $questionBankService->getTaskStatus($task['task_id']);
  751. if (!$taskStatus) {
  752. $allCompleted = false;
  753. $runningTasks[] = $task['task_id'];
  754. continue;
  755. }
  756. $status = $taskStatus['status'] ?? '';
  757. if ($status === 'completed') {
  758. $completedTasks[] = $task['task_id'];
  759. } elseif ($status === 'failed') {
  760. \Illuminate\Support\Facades\Log::error("生成任务失败", [
  761. 'task_id' => $task['task_id'],
  762. 'error' => $taskStatus['error'] ?? '未知错误'
  763. ]);
  764. // 任务失败继续等待其他任务
  765. } else {
  766. $allCompleted = false;
  767. $runningTasks[] = $task['task_id'];
  768. }
  769. }
  770. if ($allCompleted) {
  771. \Illuminate\Support\Facades\Log::info('所有AI生成任务已完成', [
  772. 'completed' => $completedTasks,
  773. 'tasks' => $generatedTasks
  774. ]);
  775. break;
  776. }
  777. // 每10秒输出一次进度
  778. $elapsed = time() - $startTime;
  779. if ($elapsed % 10 < 2) {
  780. \Illuminate\Support\Facades\Log::info("生成进度", [
  781. 'elapsed' => $elapsed,
  782. 'completed' => count($completedTasks),
  783. 'running' => count($runningTasks),
  784. 'total' => count($generatedTasks)
  785. ]);
  786. }
  787. // 等待3秒后重试
  788. sleep(3);
  789. }
  790. $waitTime = time() - $startTime;
  791. \Illuminate\Support\Facades\Log::info('AI生成任务等待完成', [
  792. 'wait_time' => $waitTime,
  793. 'tasks' => $generatedTasks
  794. ]);
  795. }
  796. }
  797. /**
  798. * 根据题型配比和难度配比,从大量题目中筛选出最佳题目
  799. */
  800. protected function selectBestQuestions(
  801. array $questions,
  802. int $targetCount,
  803. ?string $difficultyCategory, // null 表示随机难度
  804. float $totalScore,
  805. array $questionTypeRatio
  806. ): array {
  807. // 去重并过滤:确保输入题目列表没有重复ID,且都有解题思路
  808. $uniqueQuestions = [];
  809. foreach ($questions as $q) {
  810. $id = $q['id'] ?? $q['question_id'] ?? null;
  811. // 只保留有解题思路且不重复的题目
  812. $sol = $q['solution'] ?? '';
  813. if (is_array($sol)) $sol = json_encode($sol, JSON_UNESCAPED_UNICODE);
  814. if ($id && !isset($uniqueQuestions[$id]) && !empty(trim($sol))) {
  815. $uniqueQuestions[$id] = $q;
  816. }
  817. }
  818. $questions = array_values($uniqueQuestions);
  819. if (count($questions) <= $targetCount) {
  820. return $questions;
  821. }
  822. \Illuminate\Support\Facades\Log::info("开始筛选题目", [
  823. 'total_available' => count($questions),
  824. 'target_count' => $targetCount,
  825. 'difficulty_category' => $difficultyCategory,
  826. 'total_score' => $totalScore,
  827. 'type_ratio' => $questionTypeRatio
  828. ]);
  829. // 1. 按题型分类题目
  830. $categorizedQuestions = [
  831. 'choice' => [], // 选择题
  832. 'fill' => [], // 填空题
  833. 'answer' => [], // 解答题
  834. ];
  835. // 统计所有题型的原始类型分布
  836. $rawTypeStats = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  837. foreach ($questions as $question) {
  838. $type = $this->determineQuestionType($question);
  839. if (!isset($categorizedQuestions[$type])) {
  840. $type = 'answer';
  841. }
  842. $categorizedQuestions[$type][] = $question;
  843. // 统计原始类型
  844. $rawType = $question['question_type'] ?? $question['type'] ?? 'unknown';
  845. if (strtolower($rawType) === 'choice') $rawTypeStats['choice']++;
  846. if (strtolower($rawType) === 'fill') $rawTypeStats['fill']++;
  847. if (strtolower($rawType) === 'answer') $rawTypeStats['answer']++;
  848. // 记录选择题的详细信息(用于调试)
  849. if ($type === 'choice') {
  850. \Illuminate\Support\Facades\Log::debug('题目被分类为选择题', [
  851. 'question_id' => $question['id'] ?? '',
  852. 'question_type' => $question['question_type'] ?? '',
  853. 'type' => $question['type'] ?? '',
  854. 'stem_preview' => mb_substr($question['stem'] ?? '', 0, 50)
  855. ]);
  856. }
  857. }
  858. \Illuminate\Support\Facades\Log::info("题目类型分类统计", [
  859. 'total_questions' => count($questions),
  860. 'raw_type_stats' => $rawTypeStats, // 题库中题目的原始类型分布
  861. 'final_type_stats' => [
  862. 'choice' => count($categorizedQuestions['choice']),
  863. 'fill' => count($categorizedQuestions['fill']),
  864. 'answer' => count($categorizedQuestions['answer'])
  865. ]
  866. ]);
  867. // 2. 根据难度分类筛选题目
  868. // 如果难度分类为null(用户未选择),则不过滤,保留所有题目(随机难度)
  869. if ($difficultyCategory === null) {
  870. \Illuminate\Support\Facades\Log::info("用户未选择难度,将随机生成所有难度的题目");
  871. $difficultyFilteredQuestions = $categorizedQuestions;
  872. } else {
  873. $difficultyFilteredQuestions = $this->filterByDifficulty($categorizedQuestions, $difficultyCategory);
  874. }
  875. // 3. 根据题型配比计算每种题型应选择的题目数量
  876. $selectedQuestions = [];
  877. $selectedIds = []; // 用于追踪已选题目ID
  878. $typeTargets = $this->computeTypeTargets($targetCount, $questionTypeRatio);
  879. // 检查每种题型的可用数量
  880. $availableCounts = [
  881. 'choice' => count($difficultyFilteredQuestions['choice'] ?? []),
  882. 'fill' => count($difficultyFilteredQuestions['fill'] ?? []),
  883. 'answer' => count($difficultyFilteredQuestions['answer'] ?? []),
  884. ];
  885. \Illuminate\Support\Facades\Log::info("各题型可用数量", [
  886. 'available' => $availableCounts,
  887. 'targets' => $typeTargets
  888. ]);
  889. // 优先保证每种题型至少一题(适用于总题目数>=3的情况)
  890. if ($targetCount >= 3) {
  891. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  892. if (!empty($difficultyFilteredQuestions[$typeKey])) {
  893. // 随机选择1道该题型的题目
  894. $randomIndex = array_rand($difficultyFilteredQuestions[$typeKey]);
  895. $q = $difficultyFilteredQuestions[$typeKey][$randomIndex];
  896. $id = $q['id'] ?? $q['question_id'];
  897. if (!in_array($id, $selectedIds)) {
  898. $selectedQuestions[] = $q;
  899. $selectedIds[] = $id;
  900. }
  901. \Illuminate\Support\Facades\Log::info("保证题型最少题目: {$typeKey}", [
  902. 'selected_index' => $randomIndex
  903. ]);
  904. } else {
  905. \Illuminate\Support\Facades\Log::warning("题型缺失: {$typeKey},需要从其他题型补充");
  906. }
  907. }
  908. }
  909. // 根据题型配比计算每种题型应选择的题目数量
  910. foreach ($typeTargets as $typeKey => $targetTypeCount) {
  911. if ($targetTypeCount <= 0) continue;
  912. $availableQuestions = $difficultyFilteredQuestions[$typeKey] ?? [];
  913. // 过滤掉已选的
  914. $availableQuestions = array_filter($availableQuestions, function($q) use ($selectedIds) {
  915. $id = $q['id'] ?? $q['question_id'];
  916. return !in_array($id, $selectedIds);
  917. });
  918. // 还需要选多少:目标数量 - 已选该类型的数量
  919. $currentTypeCount = 0;
  920. foreach ($selectedQuestions as $sq) {
  921. if ($this->determineQuestionType($sq) === $typeKey) {
  922. $currentTypeCount++;
  923. }
  924. }
  925. $needToSelect = $targetTypeCount - $currentTypeCount;
  926. if ($needToSelect > 0) {
  927. $availableCount = count($availableQuestions);
  928. // 如果该题型可用数量不足目标数量,从其他题型补充
  929. if ($availableCount < $needToSelect) {
  930. \Illuminate\Support\Facades\Log::warning("题型 {$typeKey} 数量不足", [
  931. 'available' => $availableCount,
  932. 'target' => $needToSelect,
  933. 'will_supplement' => true
  934. ]);
  935. // 先选完该题型的所有可用题目
  936. if ($availableCount > 0) {
  937. foreach ($availableQuestions as $q) {
  938. $selectedQuestions[] = $q;
  939. $selectedIds[] = $q['id'] ?? $q['question_id'];
  940. }
  941. }
  942. // 剩余题目从其他题型补充
  943. $remainingNeed = $needToSelect - $availableCount;
  944. $otherTypes = ['choice', 'fill', 'answer'];
  945. $otherTypes = array_filter($otherTypes, fn($t) => $t !== $typeKey);
  946. foreach ($otherTypes as $otherType) {
  947. if ($remainingNeed <= 0) break;
  948. $otherQuestions = $difficultyFilteredQuestions[$otherType] ?? [];
  949. // 过滤掉已选的
  950. $otherQuestions = array_filter($otherQuestions, function($q) use ($selectedIds) {
  951. $id = $q['id'] ?? $q['question_id'];
  952. return !in_array($id, $selectedIds);
  953. });
  954. if (!empty($otherQuestions)) {
  955. $takeCount = min($remainingNeed, count($otherQuestions));
  956. $randomKeys = array_rand($otherQuestions, $takeCount);
  957. if (!is_array($randomKeys)) {
  958. $randomKeys = [$randomKeys];
  959. }
  960. foreach ($randomKeys as $key) {
  961. $q = $otherQuestions[$key];
  962. $selectedQuestions[] = $q;
  963. $selectedIds[] = $q['id'] ?? $q['question_id'];
  964. }
  965. $remainingNeed -= $takeCount;
  966. }
  967. }
  968. \Illuminate\Support\Facades\Log::info("题型 {$typeKey} 补充完成", [
  969. 'original_need' => $needToSelect,
  970. 'available' => $availableCount,
  971. 'supplemented' => $needToSelect - $remainingNeed
  972. ]);
  973. } else {
  974. // 该题型数量足够,正常选择
  975. $takeCount = min($needToSelect, $availableCount, $targetCount - count($selectedQuestions));
  976. if ($takeCount > 0) {
  977. $randomKeys = array_rand($availableQuestions, $takeCount);
  978. if (!is_array($randomKeys)) {
  979. $randomKeys = [$randomKeys];
  980. }
  981. foreach ($randomKeys as $key) {
  982. $q = $availableQuestions[$key];
  983. $selectedQuestions[] = $q;
  984. $selectedIds[] = $q['id'] ?? $q['question_id'];
  985. }
  986. }
  987. }
  988. }
  989. }
  990. // 4. 如果还有空缺,随机补充其他题型
  991. if (count($selectedQuestions) < $targetCount) {
  992. // 从所有题目中过滤掉已选的
  993. $remainingQuestions = array_filter($questions, function($q) use ($selectedIds) {
  994. $id = $q['id'] ?? $q['question_id'];
  995. return !in_array($id, $selectedIds);
  996. });
  997. if (!empty($remainingQuestions)) {
  998. $needed = $targetCount - count($selectedQuestions);
  999. $take = min($needed, count($remainingQuestions));
  1000. $randomKeys = array_rand($remainingQuestions, $take);
  1001. if (!is_array($randomKeys)) {
  1002. $randomKeys = [$randomKeys];
  1003. }
  1004. foreach ($randomKeys as $key) {
  1005. $selectedQuestions[] = $remainingQuestions[$key];
  1006. }
  1007. }
  1008. }
  1009. // 5. 打乱题目顺序
  1010. shuffle($selectedQuestions);
  1011. $finalQuestions = array_slice($selectedQuestions, 0, $targetCount);
  1012. \Illuminate\Support\Facades\Log::info("题目筛选完成", [
  1013. 'selected_count' => count($finalQuestions),
  1014. 'difficulty_category' => $difficultyCategory,
  1015. 'total_score' => $totalScore
  1016. ]);
  1017. return $finalQuestions;
  1018. }
  1019. /**
  1020. * 根据比例与总题数计算各题型目标数量,四舍五入并校正总数
  1021. */
  1022. protected function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  1023. {
  1024. $map = [
  1025. '选择题' => 'choice',
  1026. '填空题' => 'fill',
  1027. '解答题' => 'answer',
  1028. ];
  1029. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  1030. // 初步分配
  1031. foreach ($questionTypeRatio as $label => $ratio) {
  1032. $key = $map[$label] ?? null;
  1033. if (!$key) {
  1034. continue;
  1035. }
  1036. $count = (int) round($targetCount * ($ratio / 100));
  1037. if ($ratio > 0 && $count < 1) {
  1038. $count = 1; // 有比例就至少 1 道
  1039. }
  1040. $targets[$key] = $count;
  1041. }
  1042. $currentSum = array_sum($targets);
  1043. if ($currentSum === 0) {
  1044. $targets['answer'] = $targetCount;
  1045. return $targets;
  1046. }
  1047. // 总数超出则递减最多的类型(>1 时才减)
  1048. while ($currentSum > $targetCount) {
  1049. arsort($targets);
  1050. foreach ($targets as $k => $v) {
  1051. if ($v > 1) {
  1052. $targets[$k]--;
  1053. $currentSum--;
  1054. break;
  1055. }
  1056. }
  1057. }
  1058. // 总数不足则按比例最高的类型补
  1059. if ($currentSum < $targetCount) {
  1060. $ratioByKey = [
  1061. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  1062. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  1063. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  1064. ];
  1065. while ($currentSum < $targetCount) {
  1066. arsort($ratioByKey);
  1067. $key = array_key_first($ratioByKey);
  1068. $targets[$key]++;
  1069. $currentSum++;
  1070. }
  1071. }
  1072. return $targets;
  1073. }
  1074. /**
  1075. * 检查题型完整性,确保每种题型至少有一题
  1076. */
  1077. protected function ensureQuestionTypeCompleteness(array $questions, int $targetCount): array
  1078. {
  1079. $result = [
  1080. 'missing_types' => [],
  1081. 'current_count' => count($questions),
  1082. 'has_choice' => false,
  1083. 'has_fill' => false,
  1084. 'has_answer' => false,
  1085. ];
  1086. // 统计各题型数量
  1087. $choiceCount = $fillCount = $answerCount = 0;
  1088. foreach ($questions as $q) {
  1089. $type = $this->determineQuestionType($q);
  1090. if ($type === 'choice') {
  1091. $choiceCount++;
  1092. $result['has_choice'] = true;
  1093. } elseif ($type === 'fill') {
  1094. $fillCount++;
  1095. $result['has_fill'] = true;
  1096. } elseif ($type === 'answer') {
  1097. $answerCount++;
  1098. $result['has_answer'] = true;
  1099. }
  1100. }
  1101. // 如果题目数量>=3,确保每种题型至少1题
  1102. if ($targetCount >= 3) {
  1103. if (!$result['has_choice']) {
  1104. $result['missing_types'][] = 'choice';
  1105. }
  1106. if (!$result['has_fill']) {
  1107. $result['missing_types'][] = 'fill';
  1108. }
  1109. if (!$result['has_answer']) {
  1110. $result['missing_types'][] = 'answer';
  1111. }
  1112. }
  1113. \Illuminate\Support\Facades\Log::info("题型完整性检查", [
  1114. 'choice_count' => $choiceCount,
  1115. 'fill_count' => $fillCount,
  1116. 'answer_count' => $answerCount,
  1117. 'missing_types' => $result['missing_types']
  1118. ]);
  1119. return $result;
  1120. }
  1121. /**
  1122. * 批量生成缺失题型的题目
  1123. */
  1124. protected function batchGenerateMissingTypes(array $missingTypes): void
  1125. {
  1126. if (empty($missingTypes)) {
  1127. return;
  1128. }
  1129. // 增加PHP脚本执行时间到120秒,给足够时间启动异步任务
  1130. set_time_limit(120);
  1131. \Illuminate\Support\Facades\Log::info("开始生成缺失题型题目", ['missing_types' => $missingTypes]);
  1132. // 为每个缺失题型生成3-5道题
  1133. foreach ($missingTypes as $type) {
  1134. $generateCount = 5; // 每个缺失题型生成5道题
  1135. \Illuminate\Support\Facades\Log::info("为缺失题型 {$type} 生成 {$generateCount} 道题");
  1136. foreach ($this->selectedKpCodes as $kpCode) {
  1137. $questionBankService = app(QuestionBankService::class);
  1138. // 根据题型设置特定的技能点
  1139. $skills = $this->selectedSkills;
  1140. if ($type === 'choice') {
  1141. $skills[] = '选择题专项练习';
  1142. } elseif ($type === 'fill') {
  1143. $skills[] = '填空题专项练习';
  1144. } elseif ($type === 'answer') {
  1145. $skills[] = '解答题专项练习';
  1146. }
  1147. $result = $questionBankService->generateIntelligentQuestions([
  1148. 'kp_code' => $kpCode,
  1149. 'skills' => $skills,
  1150. 'count' => $generateCount,
  1151. 'difficulty_distribution' => $this->difficultyRatio,
  1152. ]);
  1153. if ($result['success'] && isset($result['task_id'])) {
  1154. \Illuminate\Support\Facades\Log::info("已启动生成任务", [
  1155. 'type' => $type,
  1156. 'task_id' => $result['task_id'],
  1157. 'kp_code' => $kpCode
  1158. ]);
  1159. }
  1160. }
  1161. }
  1162. // 缺失题型生成任务已启动,由于题目生成是异步的,
  1163. // 将在预览时动态获取最新生成的题目
  1164. \Illuminate\Support\Facades\Log::info("缺失题型生成任务已启动,将在预览时动态获取");
  1165. }
  1166. /**
  1167. * 根据难度分类筛选题目
  1168. */
  1169. protected function filterByDifficulty(array $categorizedQuestions, string $difficultyCategory): array
  1170. {
  1171. $filtered = [];
  1172. $difficultyRanges = [
  1173. '基础' => [0, 0.6], // 扩大基础难度上限,从0.4提升到0.6
  1174. '中等' => [0.4, 0.8], // 扩大中等难度范围
  1175. '拔高' => [0.6, 1.0]
  1176. ];
  1177. $targetRange = $difficultyRanges[$difficultyCategory] ?? [0, 1.0];
  1178. foreach ($categorizedQuestions as $type => $questions) {
  1179. $filtered[$type] = [];
  1180. foreach ($questions as $question) {
  1181. $difficulty = floatval($question['difficulty'] ?? 0.5);
  1182. if ($difficulty >= $targetRange[0] && $difficulty <= $targetRange[1]) {
  1183. $filtered[$type][] = $question;
  1184. }
  1185. // 不再保留越界题目,严格按难度范围筛选
  1186. }
  1187. }
  1188. \Illuminate\Support\Facades\Log::info("难度筛选结果", [
  1189. 'difficulty_category' => $difficultyCategory,
  1190. 'difficulty_range' => $targetRange,
  1191. 'choice_count' => count($filtered['choice']),
  1192. 'fill_count' => count($filtered['fill']),
  1193. 'answer_count' => count($filtered['answer'])
  1194. ]);
  1195. return $filtered;
  1196. }
  1197. /**
  1198. * 根据题目标签或内容判断题型
  1199. */
  1200. protected function determineQuestionType(array $question): string
  1201. {
  1202. // 优先根据题目内容判断(而不是数据库字段)
  1203. $stem = $question['stem'] ?? $question['content'] ?? '';
  1204. // 处理 stem 可能是数组的情况
  1205. if (is_array($stem)) {
  1206. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  1207. }
  1208. $tags = $question['tags'] ?? '';
  1209. // 处理 tags 可能是数组的情况
  1210. if (is_array($tags)) {
  1211. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  1212. }
  1213. $skills = $question['skills'] ?? [];
  1214. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  1215. if (is_string($stem)) {
  1216. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  1217. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1218. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1219. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1220. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1221. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  1222. // 至少有2个选项就认为是选择题(降低阈值)
  1223. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  1224. if ($optionCount >= 2) {
  1225. return 'choice';
  1226. }
  1227. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  1228. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  1229. return 'choice';
  1230. }
  1231. }
  1232. // 2. 根据技能点判断
  1233. if (is_array($skills) && !empty($skills)) {
  1234. // 过滤非字符串元素,避免 implode 报错
  1235. $skillsFiltered = array_filter($skills, 'is_string');
  1236. if (!empty($skillsFiltered)) {
  1237. $skillsStr = implode(',', $skillsFiltered);
  1238. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  1239. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  1240. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  1241. }
  1242. }
  1243. // 3. 根据题目已有类型字段判断(作为后备)
  1244. if (!empty($question['question_type']) && is_string($question['question_type'])) {
  1245. $type = strtolower(trim($question['question_type']));
  1246. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  1247. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  1248. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  1249. }
  1250. if (!empty($question['type']) && is_string($question['type'])) {
  1251. $type = strtolower(trim($question['type']));
  1252. if (in_array($type, ['choice', '选择题', 'choice question'])) return 'choice';
  1253. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) return 'fill';
  1254. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) return 'answer';
  1255. }
  1256. // 4. 根据标签判断
  1257. if (is_string($tags)) {
  1258. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  1259. return 'choice';
  1260. }
  1261. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  1262. return 'fill';
  1263. }
  1264. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  1265. return 'answer';
  1266. }
  1267. }
  1268. // 5. 填空题特征:连续下划线或明显的填空括号
  1269. if (is_string($stem)) {
  1270. // 检查填空题特征:连续下划线
  1271. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  1272. return 'fill';
  1273. }
  1274. // 空括号填空
  1275. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  1276. return 'fill';
  1277. }
  1278. }
  1279. // 6. 根据题干内容关键词判断
  1280. if (is_string($stem)) {
  1281. // 有证明、解答、计算、求证等关键词的是解答题
  1282. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  1283. return 'answer';
  1284. }
  1285. }
  1286. // 默认是解答题(更安全的默认值)
  1287. return 'answer';
  1288. }
  1289. /**
  1290. * 为题目分配分数,确保总分等于设定值
  1291. */
  1292. protected function assignScoresToQuestions(array $questions, float $totalScore, array $questionTypeRatio): array
  1293. {
  1294. if (empty($questions)) {
  1295. return $questions;
  1296. }
  1297. // 按题型分组统计
  1298. $typeStats = [
  1299. 'choice' => ['count' => 0, 'indices' => []],
  1300. 'fill' => ['count' => 0, 'indices' => []],
  1301. 'answer' => ['count' => 0, 'indices' => []],
  1302. ];
  1303. foreach ($questions as $index => $question) {
  1304. $type = $this->determineQuestionType($question);
  1305. if (!isset($typeStats[$type])) {
  1306. $type = 'answer';
  1307. }
  1308. $typeStats[$type]['count']++;
  1309. $typeStats[$type]['indices'][] = $index;
  1310. }
  1311. \Illuminate\Support\Facades\Log::info("分数分配统计", [
  1312. 'total_score' => $totalScore,
  1313. 'choice_count' => $typeStats['choice']['count'],
  1314. 'fill_count' => $typeStats['fill']['count'],
  1315. 'answer_count' => $typeStats['answer']['count'],
  1316. 'type_ratio' => $questionTypeRatio
  1317. ]);
  1318. // 根据题型配比计算每种题型的分数比例
  1319. $choiceRatio = ($questionTypeRatio['选择题'] ?? 40) / 100;
  1320. $fillRatio = ($questionTypeRatio['填空题'] ?? 30) / 100;
  1321. $answerRatio = ($questionTypeRatio['解答题'] ?? 30) / 100;
  1322. // 计算每种题型的总分
  1323. $choiceTotalScore = $totalScore * $choiceRatio;
  1324. $fillTotalScore = $totalScore * $fillRatio;
  1325. $answerTotalScore = $totalScore * $answerRatio;
  1326. // 计算每道题的分数
  1327. $choiceScore = $typeStats['choice']['count'] > 0
  1328. ? round($choiceTotalScore / $typeStats['choice']['count'], 0)
  1329. : 0;
  1330. $fillScore = $typeStats['fill']['count'] > 0
  1331. ? round($fillTotalScore / $typeStats['fill']['count'], 0)
  1332. : 0;
  1333. $answerScore = $typeStats['answer']['count'] > 0
  1334. ? round($answerTotalScore / $typeStats['answer']['count'], 0)
  1335. : 0;
  1336. // 确保每道题至少有分数
  1337. $choiceScore = max($choiceScore, 2);
  1338. $fillScore = max($fillScore, 3);
  1339. $answerScore = max($answerScore, 5);
  1340. // 分配分数
  1341. $assignedTotal = 0;
  1342. foreach ($questions as $index => &$question) {
  1343. // 题目类型应该在之前确定并存储,避免重复调用
  1344. $type = $question['question_type'] ?? $this->determineQuestionType($question);
  1345. if ($type === 'choice') {
  1346. $question['score'] = $choiceScore;
  1347. } elseif ($type === 'fill') {
  1348. $question['score'] = $fillScore;
  1349. } else {
  1350. $question['score'] = $answerScore;
  1351. }
  1352. $assignedTotal += $question['score'];
  1353. }
  1354. unset($question);
  1355. // 调整分数以确保总分正确
  1356. $diff = $totalScore - $assignedTotal;
  1357. if ($diff != 0 && !empty($questions)) {
  1358. // 优先调整解答题的分数
  1359. $adjustIndices = !empty($typeStats['answer']['indices'])
  1360. ? $typeStats['answer']['indices']
  1361. : (!empty($typeStats['fill']['indices'])
  1362. ? $typeStats['fill']['indices']
  1363. : $typeStats['choice']['indices']);
  1364. if (!empty($adjustIndices)) {
  1365. $adjustPerQuestion = intval($diff / count($adjustIndices));
  1366. $remainder = $diff % count($adjustIndices);
  1367. foreach ($adjustIndices as $i => $idx) {
  1368. $adjustment = $adjustPerQuestion + ($i < abs($remainder) ? ($remainder > 0 ? 1 : -1) : 0);
  1369. $questions[$idx]['score'] = max(1, $questions[$idx]['score'] + $adjustment);
  1370. }
  1371. }
  1372. }
  1373. // 最终验证
  1374. $scores = array_column($questions, 'score');
  1375. // 确保所有分数都是数字
  1376. $scores = array_map(function($s) {
  1377. return is_numeric($s) ? (float)$s : 0;
  1378. }, $scores);
  1379. $finalTotal = array_sum($scores);
  1380. \Illuminate\Support\Facades\Log::info("分数分配完成", [
  1381. 'target_score' => $totalScore,
  1382. 'final_total' => $finalTotal,
  1383. 'choice_score_each' => $choiceScore,
  1384. 'fill_score_each' => $fillScore,
  1385. 'answer_score_each' => $answerScore
  1386. ]);
  1387. return $questions;
  1388. }
  1389. /**
  1390. * 快捷设置题型配比方案
  1391. */
  1392. public function applyRatioPreset(string $preset): void
  1393. {
  1394. if ($preset === '4-2-4') {
  1395. $this->questionTypeRatio = [
  1396. '选择题' => 40,
  1397. '填空题' => 20,
  1398. '解答题' => 40,
  1399. ];
  1400. } elseif ($preset === '5-2-3') {
  1401. $this->questionTypeRatio = [
  1402. '选择题' => 50,
  1403. '填空题' => 20,
  1404. '解答题' => 30,
  1405. ];
  1406. }
  1407. }
  1408. /**
  1409. * 保留旧方法以兼容(但不再使用)
  1410. */
  1411. protected function autoGenerateQuestions(int $count)
  1412. {
  1413. // 调用新的批量生成方法
  1414. $this->batchGenerateQuestions($count);
  1415. }
  1416. public function exportToPdf()
  1417. {
  1418. if (!$this->generatedPaperId) {
  1419. Notification::make()
  1420. ->title('错误')
  1421. ->body('请先生成试卷')
  1422. ->danger()
  1423. ->send();
  1424. return;
  1425. }
  1426. // 调用PDF导出API
  1427. return redirect()->route('filament.admin.auth.intelligent-exam.pdf', [
  1428. 'paper_id' => $this->generatedPaperId,
  1429. 'answer' => 'false'
  1430. ]);
  1431. }
  1432. public function resetForm()
  1433. {
  1434. $this->reset([
  1435. 'paperName', 'paperDescription', 'selectedGrade', 'selectedKpCodes', 'selectedSkills',
  1436. 'selectedTeacherId', 'selectedStudentId', 'filterByStudentWeakness', 'generatedQuestions', 'generatedPaperId'
  1437. ]);
  1438. $this->questionTypeRatio = [
  1439. '选择题' => 40,
  1440. '填空题' => 30,
  1441. '解答题' => 30,
  1442. ];
  1443. $this->difficultyRatio = [
  1444. '基础' => 50,
  1445. '中等' => 35,
  1446. '拔高' => 15,
  1447. ];
  1448. }
  1449. /**
  1450. * 监听TeacherStudentSelector组件的老师变化事件
  1451. */
  1452. #[On('teacherChanged')]
  1453. public function onTeacherChanged(string $teacherId): void
  1454. {
  1455. \Illuminate\Support\Facades\Log::info('智能出题页面收到教师变更事件', [
  1456. 'teacher_id' => $teacherId
  1457. ]);
  1458. $this->selectedTeacherId = $teacherId;
  1459. // 清空学生选择和相关的筛选
  1460. $this->selectedStudentId = null;
  1461. $this->filterByStudentWeakness = false;
  1462. }
  1463. /**
  1464. * 监听TeacherStudentSelector组件的学生变化事件
  1465. */
  1466. #[On('studentChanged')]
  1467. public function onStudentChanged(string $teacherId, string $studentId): void
  1468. {
  1469. \Illuminate\Support\Facades\Log::info('智能出题页面收到学生变更事件', [
  1470. 'teacher_id' => $teacherId,
  1471. 'student_id' => $studentId
  1472. ]);
  1473. $this->selectedTeacherId = $teacherId;
  1474. $this->selectedStudentId = $studentId;
  1475. // ✅ 如果有学生选择,自动启用学生薄弱点筛选(但暂不勾选知识点)
  1476. if ($studentId) {
  1477. $this->filterByStudentWeakness = true;
  1478. \Illuminate\Support\Facades\Log::info('已自动启用薄弱点筛选', [
  1479. 'student_id' => $studentId,
  1480. 'filter_enabled' => $this->filterByStudentWeakness
  1481. ]);
  1482. // 不立即触发,让用户自己选择
  1483. } else {
  1484. // 如果清空了学生选择,也清空薄弱点筛选
  1485. $this->filterByStudentWeakness = false;
  1486. }
  1487. }
  1488. }