MistakeBook.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Filament\Traits\HasUserRole;
  4. use App\Models\Student;
  5. use App\Services\KnowledgeServiceApi;
  6. use App\Services\MistakeBookService;
  7. use App\Services\QuestionBankService;
  8. use BackedEnum;
  9. use Filament\Pages\Page;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Arr;
  12. use Illuminate\Support\Facades\Log;
  13. use UnitEnum;
  14. use Livewire\Attributes\On;
  15. use Livewire\Attributes\Computed;
  16. use App\Models\Teacher;
  17. class MistakeBook extends Page
  18. {
  19. use HasUserRole;
  20. protected static ?string $title = '错题本';
  21. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bookmark';
  22. protected static ?string $navigationLabel = '错题本';
  23. protected static string|UnitEnum|null $navigationGroup = '资源';
  24. protected static ?int $navigationSort = 6;
  25. protected static ?string $slug = 'mistake-book';
  26. protected string $view = 'filament.pages.mistake-book';
  27. public string $teacherId = '';
  28. public string $studentId = '';
  29. public array $filters = [
  30. 'kp_ids' => [],
  31. 'skill_ids' => [],
  32. 'error_types' => [],
  33. 'time_range' => 'last_30',
  34. 'start_date' => null,
  35. 'end_date' => null,
  36. ];
  37. public array $filterOptions = [
  38. 'knowledge_points' => [],
  39. 'skills' => [],
  40. ];
  41. public array $mistakes = [];
  42. public array $patterns = [];
  43. public array $summary = [];
  44. public array $recommendations = [];
  45. public array $relatedQuestions = [];
  46. public array $selectedMistakeIds = [];
  47. public bool $isLoading = false;
  48. public string $errorMessage = '';
  49. public string $actionMessage = '';
  50. public string $actionMessageType = 'success';
  51. public function mount(Request $request): void
  52. {
  53. // 初始化用户角色检查
  54. $this->initializeUserRole();
  55. // 如果是老师,自动选择当前老师
  56. if ($this->isTeacher) {
  57. $teacherId = $this->getCurrentTeacherId();
  58. if ($teacherId) {
  59. $this->teacherId = $teacherId;
  60. }
  61. } else {
  62. $this->teacherId = (string) ($request->input('teacher_id') ?? '');
  63. }
  64. $this->studentId = (string) ($request->input('student_id') ?? '');
  65. $this->filters['time_range'] = (string) ($request->input('range') ?? 'last_30');
  66. if ($this->studentId && empty($this->teacherId)) {
  67. $student = Student::find($this->studentId);
  68. if ($student && $student->teacher_id) {
  69. $this->teacherId = (string) $student->teacher_id;
  70. }
  71. }
  72. $this->loadFilterOptions();
  73. if ($this->studentId) {
  74. $this->loadMistakeData();
  75. }
  76. }
  77. public function updatedStudentId(): void
  78. {
  79. if ($this->studentId) {
  80. $this->loadMistakeData();
  81. } else {
  82. $this->resetPageState();
  83. }
  84. }
  85. public function loadMistakeData(): void
  86. {
  87. if (empty($this->studentId)) {
  88. $this->errorMessage = '请先选择学生';
  89. return;
  90. }
  91. $this->isLoading = true;
  92. $this->errorMessage = '';
  93. $this->actionMessage = '';
  94. try {
  95. $service = app(MistakeBookService::class);
  96. $list = $service->listMistakes([
  97. ...$this->filters,
  98. 'student_id' => $this->studentId,
  99. ]);
  100. $this->mistakes = $list['data'] ?? [];
  101. $this->summary = $service->summarize($this->studentId);
  102. $this->patterns = $service->getMistakePatterns($this->studentId);
  103. // 清理无效的选中项
  104. $validIds = collect($this->mistakes)->pluck('id')->filter()->all();
  105. $this->selectedMistakeIds = array_values(
  106. array_intersect($this->selectedMistakeIds, $validIds)
  107. );
  108. } catch (\Throwable $e) {
  109. $this->errorMessage = '加载错题本数据失败:' . $e->getMessage();
  110. Log::error('Load mistake book failed', [
  111. 'student_id' => $this->studentId,
  112. 'error' => $e->getMessage(),
  113. ]);
  114. } finally {
  115. $this->isLoading = false;
  116. }
  117. }
  118. public function refreshPatterns(): void
  119. {
  120. if (!$this->studentId) {
  121. return;
  122. }
  123. try {
  124. $service = app(MistakeBookService::class);
  125. $this->patterns = $service->getMistakePatterns($this->studentId);
  126. } catch (\Throwable $e) {
  127. Log::error('Refresh mistake patterns failed', [
  128. 'student_id' => $this->studentId,
  129. 'error' => $e->getMessage(),
  130. ]);
  131. }
  132. }
  133. public function toggleFavorite(string $mistakeId): void
  134. {
  135. $service = app(MistakeBookService::class);
  136. $current = $this->findMistakeById($mistakeId);
  137. $willFavorite = !($current['favorite'] ?? false);
  138. if ($service->toggleFavorite($mistakeId, $willFavorite)) {
  139. $this->updateMistakeField($mistakeId, 'favorite', $willFavorite);
  140. $this->notify('已更新收藏状态');
  141. } else {
  142. $this->notify('收藏操作失败,请稍后再试', 'danger');
  143. }
  144. }
  145. public function markReviewed(string $mistakeId): void
  146. {
  147. $service = app(MistakeBookService::class);
  148. if ($service->markReviewed($mistakeId)) {
  149. $this->updateMistakeField($mistakeId, 'reviewed', true);
  150. $this->notify('已标记为已复习');
  151. } else {
  152. $this->notify('标记失败,请稍后再试', 'danger');
  153. }
  154. }
  155. public function addToRetryList(string $mistakeId): void
  156. {
  157. $service = app(MistakeBookService::class);
  158. if ($service->addToRetryList($mistakeId)) {
  159. $this->notify('已加入重练清单');
  160. } else {
  161. $this->notify('加入清单失败,请稍后再试', 'danger');
  162. }
  163. }
  164. public function loadRelatedQuestions(string $mistakeId): void
  165. {
  166. $mistake = $this->findMistakeById($mistakeId);
  167. if (empty($mistake)) {
  168. return;
  169. }
  170. $questionBank = app(QuestionBankService::class);
  171. $kpIds = Arr::wrap($mistake['kp_ids'] ?? []);
  172. $skills = Arr::wrap($mistake['skill_ids'] ?? $mistake['skills'] ?? []);
  173. $response = $questionBank->filterQuestions(array_filter([
  174. 'kp_codes' => !empty($kpIds) ? implode(',', $kpIds) : null,
  175. 'skills' => !empty($skills) ? implode(',', $skills) : null,
  176. 'limit' => 5,
  177. ]));
  178. $this->relatedQuestions[$mistakeId] = $response['data'] ?? [];
  179. }
  180. public function toggleSelection(string $mistakeId): void
  181. {
  182. if (in_array($mistakeId, $this->selectedMistakeIds, true)) {
  183. $this->selectedMistakeIds = array_values(array_diff($this->selectedMistakeIds, [$mistakeId]));
  184. } else {
  185. $this->selectedMistakeIds[] = $mistakeId;
  186. }
  187. }
  188. public function generatePracticeFromSelection(): void
  189. {
  190. if (empty($this->selectedMistakeIds)) {
  191. $this->notify('请先选择至少一道错题', 'warning');
  192. return;
  193. }
  194. $selected = array_filter($this->mistakes, fn ($item) => in_array($item['id'] ?? '', $this->selectedMistakeIds, true));
  195. $kpIds = collect($selected)
  196. ->pluck('kp_ids')
  197. ->flatten()
  198. ->filter()
  199. ->unique()
  200. ->values()
  201. ->all();
  202. $skillIds = collect($selected)
  203. ->pluck('skill_ids')
  204. ->flatten()
  205. ->filter()
  206. ->unique()
  207. ->values()
  208. ->all();
  209. $service = app(MistakeBookService::class);
  210. $result = $service->recommendPractice($this->studentId, $kpIds, $skillIds);
  211. $this->recommendations = $result['data'] ?? ($result['questions'] ?? []);
  212. if (!empty($this->recommendations)) {
  213. $this->notify('已生成重练题单');
  214. } else {
  215. $this->notify('未能生成题单,请稍后再试', 'warning');
  216. }
  217. }
  218. public function applyFilters(): void
  219. {
  220. $this->loadMistakeData();
  221. }
  222. public function clearCustomRange(): void
  223. {
  224. $this->filters['start_date'] = null;
  225. $this->filters['end_date'] = null;
  226. }
  227. #[Computed]
  228. public function teachers(): array
  229. {
  230. try {
  231. $query = Teacher::query()
  232. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  233. ->select(
  234. 'teachers.teacher_id',
  235. 'teachers.name',
  236. 'teachers.subject',
  237. 'u.username',
  238. 'u.email'
  239. );
  240. // 如果是老师,只返回自己
  241. if ($this->isTeacher) {
  242. $teacherId = $this->getCurrentTeacherId();
  243. if ($teacherId) {
  244. $query->where('teachers.teacher_id', $teacherId);
  245. }
  246. }
  247. $teachers = $query->orderBy('teachers.name')->get();
  248. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  249. $missingTeacherIds = Student::query()
  250. ->distinct()
  251. ->whereNotIn('teacher_id', $teacherIds)
  252. ->pluck('teacher_id')
  253. ->toArray();
  254. $teachersArray = $teachers->all();
  255. if (!empty($missingTeacherIds)) {
  256. foreach ($missingTeacherIds as $missingId) {
  257. $teachersArray[] = (object) [
  258. 'teacher_id' => $missingId,
  259. 'name' => '未知老师 (' . $missingId . ')',
  260. 'subject' => '未知',
  261. 'username' => null,
  262. 'email' => null
  263. ];
  264. }
  265. usort($teachersArray, function($a, $b) {
  266. return strcmp($a->name, $b->name);
  267. });
  268. }
  269. return $teachersArray;
  270. } catch (\Exception $e) {
  271. Log::error('加载老师列表失败', [
  272. 'error' => $e->getMessage()
  273. ]);
  274. return [];
  275. }
  276. }
  277. #[Computed]
  278. public function students(): array
  279. {
  280. if (empty($this->teacherId)) {
  281. return [];
  282. }
  283. try {
  284. return Student::query()
  285. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  286. ->where('students.teacher_id', $this->teacherId)
  287. ->select(
  288. 'students.student_id',
  289. 'students.name',
  290. 'students.grade',
  291. 'students.class_name',
  292. 'u.username',
  293. 'u.email'
  294. )
  295. ->orderBy('students.grade')
  296. ->orderBy('students.class_name')
  297. ->orderBy('students.name')
  298. ->get()
  299. ->all();
  300. } catch (\Exception $e) {
  301. Log::error('加载学生列表失败', [
  302. 'teacher_id' => $this->teacherId,
  303. 'error' => $e->getMessage()
  304. ]);
  305. return [];
  306. }
  307. }
  308. public function getStudents(): array
  309. {
  310. return Student::query()
  311. ->select(['student_id', 'name', 'grade', 'class_name'])
  312. ->orderBy('grade')
  313. ->orderBy('class_name')
  314. ->orderBy('name')
  315. ->get()
  316. ->toArray();
  317. }
  318. #[On('teacherChanged')]
  319. public function onTeacherChanged(string $teacherId): void
  320. {
  321. $this->teacherId = $teacherId;
  322. $this->studentId = '';
  323. $this->resetPageState();
  324. }
  325. #[On('studentChanged')]
  326. public function onStudentChanged(?string $teacherId, ?string $studentId): void
  327. {
  328. $this->teacherId = (string) ($teacherId ?? '');
  329. $this->studentId = (string) ($studentId ?? '');
  330. if ($this->studentId) {
  331. $this->loadMistakeData();
  332. } else {
  333. $this->resetPageState();
  334. }
  335. }
  336. protected function loadFilterOptions(): void
  337. {
  338. try {
  339. $knowledgeService = app(KnowledgeServiceApi::class);
  340. $knowledge = $knowledgeService->listKnowledgePoints(150);
  341. $this->filterOptions['knowledge_points'] = $knowledge
  342. ->map(function ($item) {
  343. $code = $item['kp_code'] ?? $item['code'] ?? null;
  344. if (!$code) {
  345. return null;
  346. }
  347. return [
  348. 'code' => $code,
  349. 'name' => $item['cn_name'] ?? $item['name'] ?? $code,
  350. ];
  351. })
  352. ->filter()
  353. ->take(200)
  354. ->values()
  355. ->toArray();
  356. $skills = $knowledgeService->listSkills(null, 200);
  357. $this->filterOptions['skills'] = $skills
  358. ->map(function ($item) {
  359. return [
  360. 'id' => $item['skill_id'] ?? $item['id'] ?? ($item['code'] ?? ''),
  361. 'name' => $item['name'] ?? $item['skill_name'] ?? ($item['code'] ?? ''),
  362. 'kp_code' => $item['kp_code'] ?? $item['knowledge_point_code'] ?? null,
  363. ];
  364. })
  365. ->filter(fn ($item) => filled($item['id']))
  366. ->values()
  367. ->toArray();
  368. } catch (\Throwable $e) {
  369. Log::error('Load filter options failed', [
  370. 'error' => $e->getMessage(),
  371. ]);
  372. $this->filterOptions = ['knowledge_points' => [], 'skills' => []];
  373. }
  374. }
  375. protected function updateMistakeField(string $mistakeId, string $field, $value): void
  376. {
  377. foreach ($this->mistakes as &$mistake) {
  378. if (($mistake['id'] ?? null) === $mistakeId) {
  379. $mistake[$field] = $value;
  380. break;
  381. }
  382. }
  383. }
  384. protected function findMistakeById(string $mistakeId): array
  385. {
  386. foreach ($this->mistakes as $mistake) {
  387. if (($mistake['id'] ?? null) === $mistakeId) {
  388. return $mistake;
  389. }
  390. }
  391. return [];
  392. }
  393. protected function resetPageState(): void
  394. {
  395. $this->mistakes = [];
  396. $this->patterns = [];
  397. $this->summary = [];
  398. $this->selectedMistakeIds = [];
  399. $this->recommendations = [];
  400. $this->relatedQuestions = [];
  401. $this->actionMessage = '';
  402. $this->errorMessage = '';
  403. }
  404. protected function notify(string $message, string $type = 'success'): void
  405. {
  406. $this->actionMessage = $message;
  407. $this->actionMessageType = $type;
  408. }
  409. }