IntelligentExamGeneration.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Services\KnowledgeGraphService;
  4. use App\Services\LearningAnalyticsService;
  5. use App\Services\QuestionBankService;
  6. use App\Models\Student;
  7. use BackedEnum;
  8. use Filament\Notifications\Notification;
  9. use Filament\Pages\Page;
  10. use UnitEnum;
  11. use Livewire\Attributes\Computed;
  12. use Livewire\Attributes\On;
  13. use Livewire\Attributes\Reactive;
  14. use Livewire\Component;
  15. use Illuminate\Support\Facades\Cache; // Add Cache import
  16. class IntelligentExamGeneration extends Page
  17. {
  18. protected static ?string $title = '智能出卷';
  19. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document-duplicate';
  20. protected static ?string $navigationLabel = '智能出卷';
  21. protected static string|UnitEnum|null $navigationGroup = '操作';
  22. protected static ?int $navigationSort = 1;
  23. protected string $view = 'filament.pages.intelligent-exam-generation-simple';
  24. // 基本配置
  25. public ?string $paperName = '';
  26. public ?string $paperDescription = '';
  27. public ?string $difficultyCategory = '基础'; // 基础/进阶/竞赛
  28. public int $totalQuestions = 20;
  29. public int $totalScore = 100;
  30. // 知识点和技能点选择
  31. public array $selectedKpCodes = [];
  32. public array $selectedSkills = [];
  33. // 题型配比
  34. public array $questionTypeRatio = [
  35. '选择题' => 40, // 百分比
  36. '填空题' => 30,
  37. '解答题' => 30,
  38. ];
  39. // 难度配比
  40. public array $difficultyRatio = [
  41. '基础' => 50, // 百分比
  42. '中等' => 35,
  43. '拔高' => 15,
  44. ];
  45. // 教师和学生相关
  46. public ?string $selectedTeacherId = null;
  47. public ?string $selectedStudentId = null;
  48. public bool $filterByStudentWeakness = false;
  49. // 状态
  50. public bool $isGenerating = false;
  51. public array $generatedQuestions = [];
  52. public ?string $generatedPaperId = null;
  53. #[Computed]
  54. public function canGenerate(): bool
  55. {
  56. return !$this->isGenerating
  57. && $this->totalQuestions >= 6
  58. && !empty($this->selectedTeacherId)
  59. && !empty($this->selectedStudentId)
  60. && count($this->selectedKpCodes) > 0;
  61. }
  62. public function mount(): void
  63. {
  64. $this->selectedTeacherId = request()->query('teacher_id', $this->selectedTeacherId);
  65. $this->selectedStudentId = request()->query('student_id', $this->selectedStudentId);
  66. // 如果只传了 student_id,补全 teacher_id 以便学生下拉加载
  67. if ($this->selectedStudentId && !$this->selectedTeacherId) {
  68. $student = Student::find($this->selectedStudentId);
  69. if ($student && $student->teacher_id) {
  70. $this->selectedTeacherId = (string) $student->teacher_id;
  71. }
  72. }
  73. }
  74. #[Computed(cache: false)]
  75. public function knowledgePoints(): array
  76. {
  77. try {
  78. $result = app(KnowledgeGraphService::class)->listKnowledgePoints(1, 1000);
  79. $knowledgePoints = $result['data'] ?? [];
  80. \Illuminate\Support\Facades\Log::info('知识点列表获取成功', [
  81. 'count' => count($knowledgePoints),
  82. 'first_item' => !empty($knowledgePoints) ? $knowledgePoints[0] : null
  83. ]);
  84. return $knowledgePoints;
  85. } catch (\Exception $e) {
  86. \Illuminate\Support\Facades\Log::error('获取知识点列表失败', [
  87. 'error' => $e->getMessage()
  88. ]);
  89. return [];
  90. }
  91. }
  92. #[Computed(cache: false)]
  93. public function skills(): array
  94. {
  95. if (empty($this->selectedKpCodes)) {
  96. return [];
  97. }
  98. $allSkills = [];
  99. foreach ($this->selectedKpCodes as $kpCode) {
  100. $kpSkills = app(KnowledgeGraphService::class)->getSkillsByKnowledgePoint($kpCode);
  101. $allSkills = array_merge($allSkills, $kpSkills);
  102. }
  103. return $allSkills;
  104. }
  105. /**
  106. * 获取当前选择的教师名称
  107. */
  108. public function getSelectedTeacherName(): string
  109. {
  110. if (empty($this->selectedTeacherId)) {
  111. return '未选择';
  112. }
  113. try {
  114. $teacher = \App\Models\Teacher::query()
  115. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  116. ->where('teachers.teacher_id', $this->selectedTeacherId)
  117. ->select(
  118. 'teachers.name',
  119. 'teachers.subject',
  120. 'u.username'
  121. )
  122. ->first();
  123. if ($teacher) {
  124. $name = trim($teacher->name ?? $this->selectedTeacherId);
  125. $subject = $teacher->subject ? " ({$teacher->subject})" : '';
  126. $username = $teacher->username ? " [{$teacher->username}]" : '';
  127. return "{$name}{$subject}{$username}";
  128. }
  129. return $this->selectedTeacherId;
  130. } catch (\Exception $e) {
  131. return $this->selectedTeacherId;
  132. }
  133. }
  134. /**
  135. * 获取当前选择的学生名称
  136. */
  137. public function getSelectedStudentName(): string
  138. {
  139. if (empty($this->selectedStudentId) || empty($this->selectedTeacherId)) {
  140. return '未选择';
  141. }
  142. try {
  143. $student = \App\Models\Student::query()
  144. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  145. ->where('students.student_id', $this->selectedStudentId)
  146. ->where('students.teacher_id', $this->selectedTeacherId)
  147. ->select(
  148. 'students.name',
  149. 'students.grade',
  150. 'students.class_name',
  151. 'u.username'
  152. )
  153. ->first();
  154. if ($student) {
  155. $name = trim($student->name ?? $this->selectedStudentId);
  156. $gradeClass = trim("{$student->grade} - {$student->class_name}");
  157. $username = $student->username ? " [{$student->username}]" : '';
  158. return "{$name} ({$gradeClass}){$username}";
  159. }
  160. return $this->selectedStudentId;
  161. } catch (\Exception $e) {
  162. return $this->selectedStudentId;
  163. }
  164. }
  165. #[Computed(cache: false)]
  166. public function teachers(): array
  167. {
  168. try {
  169. // 首先获取teachers表中的老师
  170. $teachers = \App\Models\Teacher::query()->from('teachers as t')
  171. ->leftJoin('users as u', 't.teacher_id', '=', 'u.user_id')
  172. ->select(
  173. 't.teacher_id',
  174. 't.name',
  175. 't.subject',
  176. 'u.username',
  177. 'u.email'
  178. )
  179. ->orderBy('t.name')
  180. ->orderBy('t.name')
  181. ->get();
  182. // 如果有学生但没有对应的老师记录,添加一个"未知老师"条目
  183. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  184. $missingTeacherIds = \App\Models\Student::query()->from('students as s')
  185. ->distinct()
  186. ->whereNotIn('s.teacher_id', $teacherIds)
  187. ->pluck('teacher_id')
  188. ->toArray();
  189. // 转换 Collection 为数组以便合并和排序
  190. $teachersArray = $teachers->all();
  191. if (!empty($missingTeacherIds)) {
  192. foreach ($missingTeacherIds as $missingId) {
  193. $teachersArray[] = (object) [
  194. 'teacher_id' => $missingId,
  195. 'name' => '未知老师 (' . $missingId . ')',
  196. 'subject' => '未知',
  197. 'username' => null,
  198. 'email' => null
  199. ];
  200. }
  201. // 重新排序
  202. usort($teachersArray, function($a, $b) {
  203. return strcmp($a->name, $b->name);
  204. });
  205. return $teachersArray;
  206. }
  207. return $teachersArray;
  208. } catch (\Exception $e) {
  209. \Illuminate\Support\Facades\Log::error('加载老师列表失败', [
  210. 'error' => $e->getMessage()
  211. ]);
  212. return [];
  213. }
  214. }
  215. #[Computed(cache: false)]
  216. public function students(): array
  217. {
  218. if (empty($this->selectedTeacherId)) {
  219. return [];
  220. }
  221. try {
  222. $students = \App\Models\Student::query()->from('students as s')
  223. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  224. ->where('s.teacher_id', $this->selectedTeacherId)
  225. ->select(
  226. 's.student_id',
  227. 's.name',
  228. 's.grade',
  229. 's.class_name',
  230. 'u.username',
  231. 'u.email'
  232. )
  233. ->orderBy('s.grade')
  234. ->orderBy('s.class_name')
  235. ->orderBy('s.name')
  236. ->get()
  237. ->all();
  238. \Illuminate\Support\Facades\Log::info('智能出题页面加载学生列表', [
  239. 'teacher_id' => $this->selectedTeacherId,
  240. 'student_count' => count($students)
  241. ]);
  242. return $students;
  243. } catch (\Exception $e) {
  244. \Illuminate\Support\Facades\Log::error('加载学生列表失败', [
  245. 'teacher_id' => $this->selectedTeacherId,
  246. 'error' => $e->getMessage()
  247. ]);
  248. return [];
  249. }
  250. }
  251. #[Computed(cache: false)]
  252. public function studentWeaknesses(): array
  253. {
  254. if (!$this->selectedStudentId || !$this->filterByStudentWeakness) {
  255. \Illuminate\Support\Facades\Log::info('学生薄弱点未加载', [
  256. 'student_id' => $this->selectedStudentId,
  257. 'filter_enabled' => $this->filterByStudentWeakness
  258. ]);
  259. return [];
  260. }
  261. try {
  262. $weaknesses = app(LearningAnalyticsService::class)->getStudentWeaknesses($this->selectedStudentId);
  263. \Illuminate\Support\Facades\Log::info('获取学生薄弱点成功', [
  264. 'student_id' => $this->selectedStudentId,
  265. 'weakness_count' => count($weaknesses),
  266. 'weaknesses' => $weaknesses
  267. ]);
  268. return $weaknesses;
  269. } catch (\Exception $e) {
  270. \Illuminate\Support\Facades\Log::error('获取学生薄弱点失败', [
  271. 'student_id' => $this->selectedStudentId,
  272. 'error' => $e->getMessage()
  273. ]);
  274. return [];
  275. }
  276. }
  277. public function updatedSelectedTeacherId($value)
  278. {
  279. // 当教师选择变化时,清空之前选择的学生
  280. $this->selectedStudentId = null;
  281. }
  282. /**
  283. * 全选所有薄弱知识点
  284. */
  285. public function selectAllWeaknesses(): void
  286. {
  287. $weaknesses = $this->studentWeaknesses;
  288. if (empty($weaknesses)) {
  289. Notification::make()
  290. ->title('提示')
  291. ->body('暂无薄弱知识点数据')
  292. ->warning()
  293. ->send();
  294. return;
  295. }
  296. // 获取所有薄弱知识点的代码
  297. $kpCodes = array_column($weaknesses, 'kp_code');
  298. // 合并到已选择的知识点中(去重)
  299. $this->selectedKpCodes = array_unique(array_merge($this->selectedKpCodes, $kpCodes));
  300. Notification::make()
  301. ->title('成功')
  302. ->body('已全选 ' . count($kpCodes) . ' 个薄弱知识点')
  303. ->success()
  304. ->send();
  305. \Illuminate\Support\Facades\Log::info('全选薄弱知识点', [
  306. 'student_id' => $this->selectedStudentId,
  307. 'selected_kp_codes' => $kpCodes,
  308. 'total_selected' => count($this->selectedKpCodes)
  309. ]);
  310. }
  311. /**
  312. * 去重题目:基于ID和内容相似度去重
  313. */
  314. protected function deduplicateQuestions(array $questions): array
  315. {
  316. $uniqueQuestions = [];
  317. $seenIds = [];
  318. $seenStems = [];
  319. foreach ($questions as $question) {
  320. $id = $question['id'] ?? $question['question_id'] ?? null;
  321. $stem = $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '';
  322. $difficulty = $question['difficulty'] ?? 0.5;
  323. $kpCode = $question['kp_code'] ?? '';
  324. // 规范化题干:移除多余空白和换行
  325. $normalizedStem = preg_replace('/\s+/', ' ', trim($stem));
  326. $normalizedStem = preg_replace('/^\d+\.\s*/', '', $normalizedStem); // 移除题号
  327. // 创建唯一键:ID + 题干哈希 + 知识点
  328. $key = ($id ? "id:{$id}" : "stem:" . md5($normalizedStem)) . "kp:{$kpCode}";
  329. // 如果是选择题,进一步检查选项是否相同
  330. if ($this->determineQuestionType($question) === 'choice') {
  331. $options = $question['options'] ?? [];
  332. if (!empty($options) && is_array($options)) {
  333. $optionsKey = md5(implode('|', $options));
  334. $key .= "opt:{$optionsKey}";
  335. }
  336. }
  337. // 检查是否已存在
  338. if (isset($seenIds[$key]) || in_array($normalizedStem, $seenStems)) {
  339. \Illuminate\Support\Facades\Log::debug("跳过重复题目", [
  340. 'id' => $id,
  341. 'stem_preview' => mb_substr($normalizedStem, 0, 50)
  342. ]);
  343. continue;
  344. }
  345. // 记录并保留
  346. $seenIds[$key] = true;
  347. $seenStems[] = $normalizedStem;
  348. $uniqueQuestions[] = $question;
  349. }
  350. \Illuminate\Support\Facades\Log::info("题目去重完成", [
  351. 'original_count' => count($questions),
  352. 'unique_count' => count($uniqueQuestions),
  353. 'removed_count' => count($questions) - count($uniqueQuestions)
  354. ]);
  355. return array_values($uniqueQuestions);
  356. }
  357. /**
  358. * 清空所有选择的知识点
  359. */
  360. public function clearSelection(): void
  361. {
  362. $this->selectedKpCodes = [];
  363. Notification::make()
  364. ->title('成功')
  365. ->body('已清空所有选择的知识点')
  366. ->info()
  367. ->send();
  368. \Illuminate\Support\Facades\Log::info('清空知识点选择', [
  369. 'student_id' => $this->selectedStudentId
  370. ]);
  371. }
  372. public function updatedSelectedStudentId($value)
  373. {
  374. // 选择学生后,不要清空知识点选择,保持步骤3的选择有效
  375. // $this->selectedKpCodes = []; // 注释掉这行,避免清空用户选择
  376. // 如果启用了薄弱点筛选,加载但不自动勾选
  377. if ($this->filterByStudentWeakness && $value) {
  378. $weaknesses = $this->studentWeaknesses;
  379. if (empty($weaknesses)) {
  380. Notification::make()
  381. ->title('提示')
  382. ->body('该学生暂无薄弱点数据,您可以在步骤3中手动选择知识点')
  383. ->warning()
  384. ->send();
  385. } else {
  386. Notification::make()
  387. ->title('提示')
  388. ->body('已加载' . count($weaknesses) . '个薄弱知识点,您可以在下方或步骤3中选择要练习的知识点')
  389. ->info()
  390. ->send();
  391. }
  392. }
  393. }
  394. /**
  395. * 监听知识点选择变化
  396. */
  397. public function updatedSelectedKpCodes($value)
  398. {
  399. // 记录调试信息
  400. \Illuminate\Support\Facades\Log::info('selectedKpCodes updated', [
  401. 'count' => count($this->selectedKpCodes),
  402. 'codes' => $this->selectedKpCodes,
  403. 'type' => gettype($value),
  404. 'value' => $value
  405. ]);
  406. }
  407. public function generateExam()
  408. {
  409. \Illuminate\Support\Facades\Log::info('generateExam called with studentId=' . ($this->selectedStudentId ?? 'null'));
  410. $this->validate([
  411. // 'paperName' => 'required|string|max:255', // 已移除必填
  412. 'totalQuestions' => 'required|integer|min:6|max:100',
  413. 'selectedTeacherId' => 'nullable|string', // 可选老师
  414. 'selectedStudentId' => 'nullable|string', // 可选学生
  415. ]);
  416. // 确保题目数量至少6题
  417. if ($this->totalQuestions < 6) {
  418. \Illuminate\Support\Facades\Log::warning('题目数量少于6题,已自动调整为6题', ['original' => $this->totalQuestions]);
  419. $this->totalQuestions = 6;
  420. }
  421. if (empty($this->selectedTeacherId) || empty($this->selectedStudentId)) {
  422. Notification::make()
  423. ->title('请选择教师与学生')
  424. ->body('请选择出卷对应的教师与学生后再生成试卷,确保个性化规则生效。')
  425. ->danger()
  426. ->send();
  427. return;
  428. }
  429. if (empty($this->selectedKpCodes)) {
  430. Notification::make()
  431. ->title('请选择知识点')
  432. ->body('请至少选择 1 个知识点后再生成试卷。可勾选学生薄弱点或手动选择知识点。')
  433. ->danger()
  434. ->send();
  435. return;
  436. }
  437. // 自动生成试卷名称
  438. if (empty($this->paperName)) {
  439. $studentName = '学生' . ($this->selectedStudentId ?? '未选择');
  440. // 如果有选择学生,尝试从数据库获取真实姓名
  441. if ($this->selectedStudentId) {
  442. try {
  443. $student = \App\Models\Student::where('student_id', $this->selectedStudentId)->first();
  444. if ($student && $student->name) {
  445. $studentName = $student->name;
  446. }
  447. } catch (\Exception $e) {
  448. \Illuminate\Support\Facades\Log::warning('获取学生姓名失败', [
  449. 'student_id' => $this->selectedStudentId,
  450. 'error' => $e->getMessage()
  451. ]);
  452. }
  453. }
  454. $this->paperName = $studentName . '_' . now()->format('Ymd_His') . '_智能试卷';
  455. }
  456. $this->isGenerating = true;
  457. try {
  458. // 使用LearningAnalyticsService进行智能出卷
  459. $learningAnalyticsService = app(LearningAnalyticsService::class);
  460. // 准备出卷参数
  461. $examParams = [
  462. 'student_id' => $this->selectedStudentId,
  463. 'total_questions' => $this->totalQuestions,
  464. 'kp_codes' => $this->selectedKpCodes,
  465. 'skills' => $this->selectedSkills,
  466. 'question_type_ratio' => $this->questionTypeRatio,
  467. 'difficulty_ratio' => $this->difficultyRatio,
  468. ];
  469. // 调用智能出卷API
  470. $result = $learningAnalyticsService->generateIntelligentExam($examParams);
  471. if (!$result['success']) {
  472. throw new \Exception($result['message']);
  473. }
  474. $questions = $result['questions'];
  475. if (count($questions) < $this->totalQuestions) {
  476. // 题库不足时,批量生成题目(使用题库的多AI模型并行生成功能)
  477. $neededCount = $this->totalQuestions - count($questions);
  478. // 生成比需求更多的题目,储备起来供后续使用
  479. $generateCount = max($neededCount, 20); // 至少生成20道题作为储备
  480. \Illuminate\Support\Facades\Log::info("题库题目不足,需要补充 {$neededCount} 道题,准备批量生成 {$generateCount} 道题", [
  481. 'current_count' => count($questions),
  482. 'needed' => $neededCount,
  483. 'will_generate' => $generateCount
  484. ]);
  485. // 只生成一次,生成足够多的题目(题库服务支持多AI模型并行)
  486. $this->batchGenerateQuestions($generateCount);
  487. // 重新从题库获取题目
  488. $questionBankService = app(QuestionBankService::class);
  489. $params = [
  490. 'kp_codes' => implode(',', $this->selectedKpCodes),
  491. 'limit' => $this->totalQuestions * 2 // 获取更多题目用于筛选
  492. ];
  493. if (!empty($this->selectedSkills)) {
  494. $params['skills'] = implode(',', $this->selectedSkills);
  495. }
  496. if ($this->selectedStudentId) {
  497. $params['exclude_student_questions'] = $this->selectedStudentId;
  498. }
  499. $newResponse = $questionBankService->filterQuestions($params);
  500. // 合并题目并去重
  501. if (!empty($newResponse['data'])) {
  502. $existingIds = array_column($questions, 'id');
  503. foreach ($newResponse['data'] as $newQ) {
  504. if (!in_array($newQ['id'], $existingIds)) {
  505. $questions[] = $newQ;
  506. }
  507. }
  508. }
  509. \Illuminate\Support\Facades\Log::info("批量生成完成,当前题库题目数量: " . count($questions), [
  510. 'generated_count' => $generateCount,
  511. 'total_in_bank' => count($questions)
  512. ]);
  513. }
  514. // 2. 最终去重:确保没有重复题目
  515. $questions = $this->deduplicateQuestions($questions);
  516. \Illuminate\Support\Facades\Log::info("去重后题目数量: " . count($questions));
  517. // 3. 限制试卷题目数量为用户要求的数量
  518. if (count($questions) > $this->totalQuestions) {
  519. // 根据题型配比和难度配比对题目进行筛选和排序
  520. $questions = $this->selectBestQuestions(
  521. $questions,
  522. $this->totalQuestions,
  523. $this->difficultyCategory,
  524. $this->totalScore,
  525. $this->questionTypeRatio
  526. );
  527. \Illuminate\Support\Facades\Log::info("从 " . count($questions) . " 道题中筛选出 " . count($questions) . " 道题,难度分类: {$this->difficultyCategory}, 总分: {$this->totalScore}");
  528. }
  529. // 3. 检查题型完整性(至少保证每种题型都有题目)
  530. $checkResult = $this->ensureQuestionTypeCompleteness($questions, $this->totalQuestions);
  531. if ($checkResult['missing_types']) {
  532. \Illuminate\Support\Facades\Log::warning("检测到缺失题型,将自动生成", [
  533. 'missing_types' => $checkResult['missing_types'],
  534. 'current_count' => $checkResult['current_count']
  535. ]);
  536. // 批量生成缺失题型的题目
  537. $this->batchGenerateMissingTypes($checkResult['missing_types']);
  538. // 重新获取题目
  539. $questionBankService = app(QuestionBankService::class);
  540. $params = [
  541. 'kp_codes' => implode(',', $this->selectedKpCodes),
  542. 'limit' => $this->totalQuestions * 2
  543. ];
  544. if (!empty($this->selectedSkills)) {
  545. $params['skills'] = implode(',', $this->selectedSkills);
  546. }
  547. if ($this->selectedStudentId) {
  548. $params['exclude_student_questions'] = $this->selectedStudentId;
  549. }
  550. $newResponse = $questionBankService->filterQuestions($params);
  551. if (!empty($newResponse['data'])) {
  552. $questions = array_merge($questions, $newResponse['data']);
  553. }
  554. // 再次筛选
  555. $questions = $this->selectBestQuestions(
  556. $questions,
  557. $this->totalQuestions,
  558. $this->difficultyCategory,
  559. $this->totalScore,
  560. $this->questionTypeRatio
  561. );
  562. }
  563. // 2. 为题目添加类型信息(如果缺失)
  564. foreach ($questions as &$question) {
  565. if (!isset($question['question_type'])) {
  566. $question['question_type'] = $this->determineQuestionType($question);
  567. \Illuminate\Support\Facades\Log::debug('为题目添加类型', [
  568. 'question_id' => $question['id'] ?? '',
  569. 'added_type' => $question['question_type']
  570. ]);
  571. }
  572. }
  573. unset($question); // 释放引用
  574. // 3. 生成试卷数据
  575. $examData = [
  576. 'paper_name' => $this->paperName,
  577. 'paper_description' => $this->paperDescription,
  578. 'difficulty_category' => $this->difficultyCategory,
  579. 'questions' => $questions,
  580. 'total_score' => $this->totalScore,
  581. 'total_questions' => count($questions),
  582. 'student_id' => $this->selectedStudentId,
  583. 'teacher_id' => $this->selectedTeacherId,
  584. ];
  585. // 4. 保存到数据库
  586. $questionBankService = app(QuestionBankService::class);
  587. $paperId = $questionBankService->saveExamToDatabase($examData);
  588. // 如果保存返回 null,使用默认占位 ID,防止 UI 不显示
  589. if (empty($paperId)) {
  590. $paperId = 'demo_' . $this->selectedStudentId . '_' . now()->format('YmdHis');
  591. }
  592. \Illuminate\Support\Facades\Log::info('Generated paper ID: ' . $paperId);
  593. $this->generatedPaperId = $paperId;
  594. // 将生成的试卷数据缓存,以便 PDF 预览时使用(缓存 1 小时)
  595. \Illuminate\Support\Facades\Log::info('缓存试卷数据', [
  596. 'paper_id' => $paperId,
  597. 'question_count' => count($questions),
  598. 'question_types' => array_column($questions, 'question_type')
  599. ]);
  600. Cache::put('generated_exam_' . $paperId, $examData, now()->addHour());
  601. $this->generatedQuestions = $questions;
  602. $stats = $result['stats'] ?? [];
  603. $message = "已生成包含 " . count($questions) . " 道题的试卷";
  604. if (!empty($stats['weakness_targeted'])) {
  605. $message .= ",其中针对薄弱点 " . $stats['weakness_targeted'] . " 题";
  606. }
  607. Notification::make()
  608. ->title('试卷生成成功')
  609. ->body($message)
  610. ->success()
  611. ->send();
  612. } catch (\Exception $e) {
  613. // 记录错误并提供回退的试卷 ID,防止 UI 无显示
  614. \Illuminate\Support\Facades\Log::error('生成试卷失败', ['error' => $e->getMessage()]);
  615. $fallbackId = 'demo_' . $this->selectedStudentId . '_' . now()->format('YmdHis');
  616. $this->generatedPaperId = $fallbackId;
  617. $this->generatedQuestions = [];
  618. Notification::make()
  619. ->title('试卷生成失败,使用默认试卷')
  620. ->body('错误: ' . $e->getMessage() . "\n已生成默认试卷 ID: $fallbackId")
  621. ->warning()
  622. ->send();
  623. } finally {
  624. $this->isGenerating = false;
  625. }
  626. }
  627. /**
  628. * 批量生成题目(使用题库的多AI模型并行功能)
  629. */
  630. protected function batchGenerateQuestions(int $count)
  631. {
  632. // 增加PHP脚本执行时间到120秒,给足够时间启动异步任务和等待完成
  633. set_time_limit(120);
  634. $questionBankService = app(QuestionBankService::class);
  635. $generatedTasks = [];
  636. // 只生成一次,使用所有选中的知识点
  637. $allKpCodes = $this->selectedKpCodes;
  638. if (empty($allKpCodes)) {
  639. // 如果没有选中知识点,使用默认知识点
  640. $allKpCodes = ['R01']; // 默认知识点
  641. }
  642. // 对每个知识点生成题目
  643. foreach ($allKpCodes as $kpCode) {
  644. \Illuminate\Support\Facades\Log::info("为知识点 {$kpCode} 生成题目", [
  645. 'count' => $count,
  646. 'skills' => $this->selectedSkills
  647. ]);
  648. $result = $questionBankService->generateIntelligentQuestions([
  649. 'kp_code' => $kpCode,
  650. 'skills' => $this->selectedSkills,
  651. 'count' => $count,
  652. 'difficulty_distribution' => $this->difficultyRatio,
  653. ]);
  654. if ($result['success'] && isset($result['task_id'])) {
  655. $generatedTasks[] = [
  656. 'task_id' => $result['task_id'],
  657. 'kp_code' => $kpCode
  658. ];
  659. \Illuminate\Support\Facades\Log::info("已启动生成任务: {$result['task_id']} for {$kpCode}");
  660. } else {
  661. \Illuminate\Support\Facades\Log::warning("生成任务启动失败", [
  662. 'kp_code' => $kpCode,
  663. 'result' => $result
  664. ]);
  665. }
  666. }
  667. // 等待所有任务完成(最多等待60秒)
  668. if (!empty($generatedTasks)) {
  669. $maxWaitTime = 60; // 增加最大等待时间
  670. $startTime = time();
  671. \Illuminate\Support\Facades\Log::info("等待 {$maxWaitTime} 秒,所有生成任务完成", [
  672. 'tasks' => array_column($generatedTasks, 'task_id')
  673. ]);
  674. while (time() - $startTime < $maxWaitTime) {
  675. $allCompleted = true;
  676. $completedTasks = [];
  677. $runningTasks = [];
  678. foreach ($generatedTasks as $task) {
  679. $taskStatus = $questionBankService->getTaskStatus($task['task_id']);
  680. if (!$taskStatus) {
  681. $allCompleted = false;
  682. $runningTasks[] = $task['task_id'];
  683. continue;
  684. }
  685. $status = $taskStatus['status'] ?? '';
  686. if ($status === 'completed') {
  687. $completedTasks[] = $task['task_id'];
  688. } elseif ($status === 'failed') {
  689. \Illuminate\Support\Facades\Log::error("生成任务失败", [
  690. 'task_id' => $task['task_id'],
  691. 'error' => $taskStatus['error'] ?? '未知错误'
  692. ]);
  693. // 任务失败继续等待其他任务
  694. } else {
  695. $allCompleted = false;
  696. $runningTasks[] = $task['task_id'];
  697. }
  698. }
  699. if ($allCompleted) {
  700. \Illuminate\Support\Facades\Log::info('所有AI生成任务已完成', [
  701. 'completed' => $completedTasks,
  702. 'tasks' => $generatedTasks
  703. ]);
  704. break;
  705. }
  706. // 每10秒输出一次进度
  707. $elapsed = time() - $startTime;
  708. if ($elapsed % 10 < 2) {
  709. \Illuminate\Support\Facades\Log::info("生成进度", [
  710. 'elapsed' => $elapsed,
  711. 'completed' => count($completedTasks),
  712. 'running' => count($runningTasks),
  713. 'total' => count($generatedTasks)
  714. ]);
  715. }
  716. // 等待3秒后重试
  717. sleep(3);
  718. }
  719. $waitTime = time() - $startTime;
  720. \Illuminate\Support\Facades\Log::info('AI生成任务等待完成', [
  721. 'wait_time' => $waitTime,
  722. 'tasks' => $generatedTasks
  723. ]);
  724. }
  725. }
  726. /**
  727. * 根据题型配比和难度配比,从大量题目中筛选出最佳题目
  728. */
  729. protected function selectBestQuestions(
  730. array $questions,
  731. int $targetCount,
  732. string $difficultyCategory,
  733. float $totalScore,
  734. array $questionTypeRatio
  735. ): array {
  736. // 去重:确保输入题目列表没有重复ID
  737. $uniqueQuestions = [];
  738. foreach ($questions as $q) {
  739. $id = $q['id'] ?? $q['question_id'] ?? null;
  740. if ($id && !isset($uniqueQuestions[$id])) {
  741. $uniqueQuestions[$id] = $q;
  742. }
  743. }
  744. $questions = array_values($uniqueQuestions);
  745. if (count($questions) <= $targetCount) {
  746. return $questions;
  747. }
  748. \Illuminate\Support\Facades\Log::info("开始筛选题目", [
  749. 'total_available' => count($questions),
  750. 'target_count' => $targetCount,
  751. 'difficulty_category' => $difficultyCategory,
  752. 'total_score' => $totalScore,
  753. 'type_ratio' => $questionTypeRatio
  754. ]);
  755. // 1. 按题型分类题目
  756. $categorizedQuestions = [
  757. 'choice' => [], // 选择题
  758. 'fill' => [], // 填空题
  759. 'answer' => [], // 解答题
  760. ];
  761. foreach ($questions as $question) {
  762. $type = $this->determineQuestionType($question);
  763. if (!isset($categorizedQuestions[$type])) {
  764. $type = 'answer';
  765. }
  766. $categorizedQuestions[$type][] = $question;
  767. }
  768. // 2. 根据难度分类筛选题目
  769. $difficultyFilteredQuestions = $this->filterByDifficulty($categorizedQuestions, $difficultyCategory);
  770. // 3. 根据题型配比计算每种题型应选择的题目数量
  771. $selectedQuestions = [];
  772. $selectedIds = []; // 用于追踪已选题目ID
  773. // 优先保证每种题型至少一题(适用于总题目数>=3的情况)
  774. if ($targetCount >= 3) {
  775. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  776. if (!empty($difficultyFilteredQuestions[$typeKey])) {
  777. // 随机选择1道该题型的题目
  778. $randomIndex = array_rand($difficultyFilteredQuestions[$typeKey]);
  779. $q = $difficultyFilteredQuestions[$typeKey][$randomIndex];
  780. $id = $q['id'] ?? $q['question_id'];
  781. if (!in_array($id, $selectedIds)) {
  782. $selectedQuestions[] = $q;
  783. $selectedIds[] = $id;
  784. }
  785. \Illuminate\Support\Facades\Log::info("保证题型最少题目: {$typeKey}", [
  786. 'selected_index' => $randomIndex
  787. ]);
  788. } else {
  789. \Illuminate\Support\Facades\Log::warning("题型缺失: {$typeKey},需要从其他题型补充");
  790. }
  791. }
  792. }
  793. // 根据题型配比计算每种题型应选择的题目数量
  794. foreach ($questionTypeRatio as $type => $ratio) {
  795. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  796. // 计算该类型目标数量
  797. $targetTypeCount = floor($targetCount * $ratio / 100);
  798. // 调整目标数量:如果总数>=3,需要考虑已经选了的题目
  799. // 简单起见,我们计算总共需要的数量,然后减去已经选了的数量
  800. // 但这里为了保证比例,我们还是尽量多选
  801. if ($targetTypeCount <= 0) continue;
  802. if (!empty($difficultyFilteredQuestions[$typeKey])) {
  803. $availableQuestions = $difficultyFilteredQuestions[$typeKey];
  804. // 过滤掉已选的
  805. $availableQuestions = array_filter($availableQuestions, function($q) use ($selectedIds) {
  806. $id = $q['id'] ?? $q['question_id'];
  807. return !in_array($id, $selectedIds);
  808. });
  809. // 如果没有可用题目了,跳过
  810. if (empty($availableQuestions)) continue;
  811. $availableCount = count($availableQuestions);
  812. // 还需要选多少:目标数量 - 已选该类型的数量
  813. $currentTypeCount = 0;
  814. foreach ($selectedQuestions as $sq) {
  815. if ($this->determineQuestionType($sq) === $typeKey) {
  816. $currentTypeCount++;
  817. }
  818. }
  819. $needToSelect = $targetTypeCount - $currentTypeCount;
  820. if ($needToSelect > 0) {
  821. $takeCount = min($needToSelect, $availableCount, $targetCount - count($selectedQuestions));
  822. if ($takeCount > 0) {
  823. $randomKeys = array_rand($availableQuestions, $takeCount);
  824. if (!is_array($randomKeys)) {
  825. $randomKeys = [$randomKeys];
  826. }
  827. foreach ($randomKeys as $key) {
  828. $q = $availableQuestions[$key];
  829. $selectedQuestions[] = $q;
  830. $selectedIds[] = $q['id'] ?? $q['question_id'];
  831. }
  832. }
  833. }
  834. }
  835. }
  836. // 4. 如果还有空缺,随机补充其他题型
  837. if (count($selectedQuestions) < $targetCount) {
  838. // 从所有题目中过滤掉已选的
  839. $remainingQuestions = array_filter($questions, function($q) use ($selectedIds) {
  840. $id = $q['id'] ?? $q['question_id'];
  841. return !in_array($id, $selectedIds);
  842. });
  843. if (!empty($remainingQuestions)) {
  844. $needed = $targetCount - count($selectedQuestions);
  845. $take = min($needed, count($remainingQuestions));
  846. $randomKeys = array_rand($remainingQuestions, $take);
  847. if (!is_array($randomKeys)) {
  848. $randomKeys = [$randomKeys];
  849. }
  850. foreach ($randomKeys as $key) {
  851. $selectedQuestions[] = $remainingQuestions[$key];
  852. }
  853. }
  854. }
  855. // 5. 打乱题目顺序
  856. shuffle($selectedQuestions);
  857. $finalQuestions = array_slice($selectedQuestions, 0, $targetCount);
  858. \Illuminate\Support\Facades\Log::info("题目筛选完成", [
  859. 'selected_count' => count($finalQuestions),
  860. 'difficulty_category' => $difficultyCategory,
  861. 'total_score' => $totalScore
  862. ]);
  863. return $finalQuestions;
  864. }
  865. /**
  866. * 检查题型完整性,确保每种题型至少有一题
  867. */
  868. protected function ensureQuestionTypeCompleteness(array $questions, int $targetCount): array
  869. {
  870. $result = [
  871. 'missing_types' => [],
  872. 'current_count' => count($questions),
  873. 'has_choice' => false,
  874. 'has_fill' => false,
  875. 'has_answer' => false,
  876. ];
  877. // 统计各题型数量
  878. $choiceCount = $fillCount = $answerCount = 0;
  879. foreach ($questions as $q) {
  880. $type = $this->determineQuestionType($q);
  881. if ($type === 'choice') {
  882. $choiceCount++;
  883. $result['has_choice'] = true;
  884. } elseif ($type === 'fill') {
  885. $fillCount++;
  886. $result['has_fill'] = true;
  887. } elseif ($type === 'answer') {
  888. $answerCount++;
  889. $result['has_answer'] = true;
  890. }
  891. }
  892. // 如果题目数量>=3,确保每种题型至少1题
  893. if ($targetCount >= 3) {
  894. if (!$result['has_choice']) {
  895. $result['missing_types'][] = 'choice';
  896. }
  897. if (!$result['has_fill']) {
  898. $result['missing_types'][] = 'fill';
  899. }
  900. if (!$result['has_answer']) {
  901. $result['missing_types'][] = 'answer';
  902. }
  903. }
  904. \Illuminate\Support\Facades\Log::info("题型完整性检查", [
  905. 'choice_count' => $choiceCount,
  906. 'fill_count' => $fillCount,
  907. 'answer_count' => $answerCount,
  908. 'missing_types' => $result['missing_types']
  909. ]);
  910. return $result;
  911. }
  912. /**
  913. * 批量生成缺失题型的题目
  914. */
  915. protected function batchGenerateMissingTypes(array $missingTypes): void
  916. {
  917. if (empty($missingTypes)) {
  918. return;
  919. }
  920. // 增加PHP脚本执行时间到120秒,给足够时间启动异步任务
  921. set_time_limit(120);
  922. \Illuminate\Support\Facades\Log::info("开始生成缺失题型题目", ['missing_types' => $missingTypes]);
  923. // 为每个缺失题型生成3-5道题
  924. foreach ($missingTypes as $type) {
  925. $generateCount = 5; // 每个缺失题型生成5道题
  926. \Illuminate\Support\Facades\Log::info("为缺失题型 {$type} 生成 {$generateCount} 道题");
  927. foreach ($this->selectedKpCodes as $kpCode) {
  928. $questionBankService = app(QuestionBankService::class);
  929. // 根据题型设置特定的技能点
  930. $skills = $this->selectedSkills;
  931. if ($type === 'choice') {
  932. $skills[] = '选择题专项练习';
  933. } elseif ($type === 'fill') {
  934. $skills[] = '填空题专项练习';
  935. } elseif ($type === 'answer') {
  936. $skills[] = '解答题专项练习';
  937. }
  938. $result = $questionBankService->generateIntelligentQuestions([
  939. 'kp_code' => $kpCode,
  940. 'skills' => $skills,
  941. 'count' => $generateCount,
  942. 'difficulty_distribution' => $this->difficultyRatio,
  943. ]);
  944. if ($result['success'] && isset($result['task_id'])) {
  945. \Illuminate\Support\Facades\Log::info("已启动生成任务", [
  946. 'type' => $type,
  947. 'task_id' => $result['task_id'],
  948. 'kp_code' => $kpCode
  949. ]);
  950. }
  951. }
  952. }
  953. // 缺失题型生成任务已启动,由于题目生成是异步的,
  954. // 将在预览时动态获取最新生成的题目
  955. \Illuminate\Support\Facades\Log::info("缺失题型生成任务已启动,将在预览时动态获取");
  956. }
  957. /**
  958. * 根据难度分类筛选题目
  959. */
  960. protected function filterByDifficulty(array $categorizedQuestions, string $difficultyCategory): array
  961. {
  962. $filtered = [];
  963. $difficultyRanges = [
  964. '基础' => [0, 0.4],
  965. '中等' => [0.3, 0.7],
  966. '拔高' => [0.6, 1.0]
  967. ];
  968. $targetRange = $difficultyRanges[$difficultyCategory] ?? [0, 1.0];
  969. foreach ($categorizedQuestions as $type => $questions) {
  970. $filtered[$type] = [];
  971. foreach ($questions as $question) {
  972. $difficulty = floatval($question['difficulty'] ?? 0.5);
  973. if ($difficulty >= $targetRange[0] && $difficulty <= $targetRange[1]) {
  974. $filtered[$type][] = $question;
  975. } else {
  976. // 保留部分越界题目(如果该难度题目不足)
  977. if (count($filtered[$type]) < 2) {
  978. $filtered[$type][] = $question;
  979. }
  980. }
  981. }
  982. }
  983. \Illuminate\Support\Facades\Log::info("难度筛选结果", [
  984. 'difficulty_category' => $difficultyCategory,
  985. 'difficulty_range' => $targetRange,
  986. 'choice_count' => count($filtered['choice']),
  987. 'fill_count' => count($filtered['fill']),
  988. 'answer_count' => count($filtered['answer'])
  989. ]);
  990. return $filtered;
  991. }
  992. /**
  993. * 根据题目标签或内容判断题型
  994. */
  995. protected function determineQuestionType(array $question): string
  996. {
  997. // 0. 如果题目已有明确类型,直接返回
  998. if (!empty($question['type'])) {
  999. if ($question['type'] === 'choice' || $question['type'] === '选择题') return 'choice';
  1000. if ($question['type'] === 'fill' || $question['type'] === '填空题') return 'fill';
  1001. if ($question['type'] === 'answer' || $question['type'] === '解答题') return 'answer';
  1002. }
  1003. $tags = $question['tags'] ?? '';
  1004. $stem = $question['stem'] ?? $question['content'] ?? '';
  1005. // 1. 根据标签判断
  1006. if (is_string($tags)) {
  1007. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  1008. return 'choice';
  1009. }
  1010. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  1011. return 'fill';
  1012. }
  1013. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  1014. return 'answer';
  1015. }
  1016. }
  1017. // 2. 根据题干内容判断 - 填空题优先(有下划线)
  1018. // 填空题特征:连续的下划线,或者括号中明显是填空的(通常不会有选项)
  1019. if (is_string($stem)) {
  1020. // 检查填空题特征:连续下划线
  1021. if (strpos($stem, '____') !== false || strpos($stem, '______') !== false) {
  1022. return 'fill';
  1023. }
  1024. }
  1025. // 3. 根据题干内容判断 - 选择题
  1026. // 选择题特征:必须包含选项 A. B. C. D.
  1027. if (is_string($stem)) {
  1028. // 检查选项格式 A. B. C. D.(支持跨行匹配)
  1029. // 更严格的正则:A. 后面跟内容,或者 (A) 后面跟内容
  1030. if (preg_match('/[A-D]\s*\./', $stem) || preg_match('/\([A-D]\)/', $stem)) {
  1031. // 再次确认是否包含多个选项,防止误判
  1032. if (preg_match('/A\./', $stem) && preg_match('/B\./', $stem)) {
  1033. return 'choice';
  1034. }
  1035. }
  1036. // 如果只有括号但没有选项,可能是填空题
  1037. // 比如 "计算:(1) ... (2) ..." 这种是解答题
  1038. // "若 x > 0,则 x + 1 ( )" 这种可能是填空也可能是选择,取决于是否有选项
  1039. // 这里我们保守一点,如果没有选项特征,就不认为是选择题
  1040. }
  1041. // 4. 再次检查填空题特征(括号填空)
  1042. if (is_string($stem)) {
  1043. // 只有括号且没有选项,通常是填空
  1044. if ((strpos($stem, '()') !== false || strpos($stem, '()') !== false) && !preg_match('/[A-D]\./', $stem)) {
  1045. return 'fill';
  1046. }
  1047. }
  1048. // 5. 根据题干长度和内容判断(启发式)
  1049. if (is_string($stem)) {
  1050. // 有证明、解答、计算、求证等关键词的是解答题
  1051. if (strpos($stem, '证明') !== false || strpos($stem, '求证') !== false || strpos($stem, '解方程') !== false || strpos($stem, '计算:') !== false) {
  1052. return 'answer';
  1053. }
  1054. }
  1055. // 默认是解答题
  1056. return 'answer';
  1057. }
  1058. /**
  1059. * 保留旧方法以兼容(但不再使用)
  1060. */
  1061. protected function autoGenerateQuestions(int $count)
  1062. {
  1063. // 调用新的批量生成方法
  1064. $this->batchGenerateQuestions($count);
  1065. }
  1066. public function exportToPdf()
  1067. {
  1068. if (!$this->generatedPaperId) {
  1069. Notification::make()
  1070. ->title('错误')
  1071. ->body('请先生成试卷')
  1072. ->danger()
  1073. ->send();
  1074. return;
  1075. }
  1076. // 调用PDF导出API
  1077. return redirect()->route('filament.admin.auth.intelligent-exam.pdf', [
  1078. 'paper_id' => $this->generatedPaperId
  1079. ]);
  1080. }
  1081. public function resetForm()
  1082. {
  1083. $this->reset([
  1084. 'paperName', 'paperDescription', 'selectedKpCodes', 'selectedSkills',
  1085. 'selectedTeacherId', 'selectedStudentId', 'filterByStudentWeakness', 'generatedQuestions', 'generatedPaperId'
  1086. ]);
  1087. $this->questionTypeRatio = [
  1088. '选择题' => 40,
  1089. '填空题' => 30,
  1090. '解答题' => 30,
  1091. ];
  1092. $this->difficultyRatio = [
  1093. '基础' => 50,
  1094. '中等' => 35,
  1095. '拔高' => 15,
  1096. ];
  1097. }
  1098. /**
  1099. * 监听TeacherStudentSelector组件的老师变化事件
  1100. */
  1101. #[On('teacherChanged')]
  1102. public function onTeacherChanged(string $teacherId): void
  1103. {
  1104. \Illuminate\Support\Facades\Log::info('智能出题页面收到教师变更事件', [
  1105. 'teacher_id' => $teacherId
  1106. ]);
  1107. $this->selectedTeacherId = $teacherId;
  1108. // 清空学生选择和相关的筛选
  1109. $this->selectedStudentId = null;
  1110. $this->filterByStudentWeakness = false;
  1111. }
  1112. /**
  1113. * 监听TeacherStudentSelector组件的学生变化事件
  1114. */
  1115. #[On('studentChanged')]
  1116. public function onStudentChanged(string $teacherId, string $studentId): void
  1117. {
  1118. \Illuminate\Support\Facades\Log::info('智能出题页面收到学生变更事件', [
  1119. 'teacher_id' => $teacherId,
  1120. 'student_id' => $studentId
  1121. ]);
  1122. $this->selectedTeacherId = $teacherId;
  1123. $this->selectedStudentId = $studentId;
  1124. // ✅ 如果有学生选择,自动启用学生薄弱点筛选(但暂不勾选知识点)
  1125. if ($studentId) {
  1126. $this->filterByStudentWeakness = true;
  1127. \Illuminate\Support\Facades\Log::info('已自动启用薄弱点筛选', [
  1128. 'student_id' => $studentId,
  1129. 'filter_enabled' => $this->filterByStudentWeakness
  1130. ]);
  1131. // 不立即触发,让用户自己选择
  1132. } else {
  1133. // 如果清空了学生选择,也清空薄弱点筛选
  1134. $this->filterByStudentWeakness = false;
  1135. }
  1136. }
  1137. }