StudentDashboard.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Filament\Traits\HandlesMindmapDetails;
  4. use App\Filament\Traits\HasUserRole;
  5. use App\Models\Student;
  6. use App\Models\Teacher;
  7. use App\Services\LearningAnalyticsService;
  8. use BackedEnum;
  9. use Filament\Pages\Page;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Http;
  13. use Illuminate\Support\Facades\Log;
  14. use UnitEnum;
  15. use Livewire\Attributes\Layout;
  16. use Livewire\Attributes\Title;
  17. use Livewire\Attributes\On;
  18. use Livewire\Attributes\Computed;
  19. use App\Models\Student as StudentModel;
  20. use App\Services\MistakeBookService;
  21. class StudentDashboard extends Page
  22. {
  23. use HasUserRole, HandlesMindmapDetails;
  24. use \Filament\Pages\Concerns\InteractsWithFormActions;
  25. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';
  26. protected static string|UnitEnum|null $navigationGroup = '操作';
  27. protected static ?string $navigationLabel = '学生仪表板';
  28. protected static ?int $navigationSort = 4;
  29. protected ?string $heading = '学生仪表板';
  30. protected string $view = 'filament.pages.student-dashboard';
  31. public string $studentId = '';
  32. public string $teacherId = '';
  33. public array $dashboardData = [];
  34. public bool $isLoading = false;
  35. public string $errorMessage = '';
  36. public array $mindmapMasteryData = [];
  37. public bool $mindmapDrawerOpen = false;
  38. public array $mindmapNodeDetails = [];
  39. public ?string $mindmapSelectedNode = null;
  40. // teachers 和 students 现在是 Computed 属性,不再需要声明
  41. public array $mistakePanel = [];
  42. public function mount(Request $request): void
  43. {
  44. // 初始化用户角色检查
  45. $this->initializeUserRole();
  46. // 如果是老师,自动选择当前老师
  47. if ($this->isTeacher) {
  48. $teacherId = $this->getCurrentTeacherId();
  49. if ($teacherId) {
  50. $this->teacherId = $teacherId;
  51. }
  52. } else {
  53. // 从请求中获取老师ID
  54. $this->teacherId = (string) ($request->input('teacher_id') ?? '');
  55. }
  56. // 从请求中获取学生ID
  57. $this->studentId = (string) ($request->input('student_id') ?? '');
  58. if ($this->studentId && empty($this->teacherId)) {
  59. $student = StudentModel::find($this->studentId);
  60. if ($student && $student->teacher_id) {
  61. $this->teacherId = (string) $student->teacher_id;
  62. }
  63. }
  64. // 若已通过 URL 传入学生,自动加载仪表盘数据,减少手动刷新
  65. if ($this->studentId && $this->teacherId) {
  66. $this->loadDashboardData();
  67. }
  68. }
  69. #[Computed]
  70. public function teachers(): array
  71. {
  72. try {
  73. $query = Teacher::query()
  74. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  75. ->select(
  76. 'teachers.teacher_id',
  77. 'teachers.name',
  78. 'teachers.subject',
  79. 'u.username',
  80. 'u.email'
  81. );
  82. // 如果是老师,只返回自己
  83. if ($this->isTeacher) {
  84. $teacherId = $this->getCurrentTeacherId();
  85. if ($teacherId) {
  86. $query->where('teachers.teacher_id', $teacherId);
  87. }
  88. }
  89. $teachers = $query->orderBy('teachers.name')->get();
  90. // 检查是否有学生没有对应的老师记录
  91. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  92. $missingTeacherIds = Student::query()
  93. ->distinct()
  94. ->whereNotIn('teacher_id', $teacherIds)
  95. ->pluck('teacher_id')
  96. ->toArray();
  97. $teachersArray = $teachers->all();
  98. if (!empty($missingTeacherIds)) {
  99. foreach ($missingTeacherIds as $missingId) {
  100. $teachersArray[] = (object) [
  101. 'teacher_id' => $missingId,
  102. 'name' => '未知老师 (' . $missingId . ')',
  103. 'subject' => '未知',
  104. 'username' => null,
  105. 'email' => null
  106. ];
  107. }
  108. usort($teachersArray, function($a, $b) {
  109. return strcmp($a->name, $b->name);
  110. });
  111. }
  112. return $teachersArray;
  113. } catch (\Exception $e) {
  114. Log::error('加载老师列表失败', [
  115. 'error' => $e->getMessage()
  116. ]);
  117. return [];
  118. }
  119. }
  120. #[Computed]
  121. public function students(): array
  122. {
  123. if (empty($this->teacherId)) {
  124. return [];
  125. }
  126. try {
  127. return Student::query()
  128. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  129. ->where('students.teacher_id', $this->teacherId)
  130. ->select(
  131. 'students.student_id',
  132. 'students.name',
  133. 'students.grade',
  134. 'students.class_name',
  135. 'u.username',
  136. 'u.email'
  137. )
  138. ->orderBy('students.grade')
  139. ->orderBy('students.class_name')
  140. ->orderBy('students.name')
  141. ->get()
  142. ->all();
  143. } catch (\Exception $e) {
  144. Log::error('加载学生列表失败', [
  145. 'teacher_id' => $this->teacherId,
  146. 'error' => $e->getMessage()
  147. ]);
  148. return [];
  149. }
  150. }
  151. /**
  152. * 老师改变时重新加载学生列表
  153. */
  154. public function updatedTeacherId(): void
  155. {
  156. // 清空之前选中的学生ID
  157. $this->studentId = '';
  158. }
  159. /**
  160. * 学生改变时重新加载数据
  161. */
  162. public function updatedStudentId(): void
  163. {
  164. if (!empty($this->studentId)) {
  165. $this->loadDashboardData();
  166. } else {
  167. $this->mindmapMasteryData = [];
  168. $this->dispatch('mastery-updated', data: []);
  169. $this->mistakePanel = [];
  170. }
  171. }
  172. public function loadDashboardData(): void
  173. {
  174. // 检查是否选择了学生
  175. if (empty($this->studentId)) {
  176. $this->errorMessage = '请先选择学生';
  177. $this->isLoading = false;
  178. return;
  179. }
  180. $this->isLoading = true;
  181. $this->errorMessage = '';
  182. try {
  183. $service = app(LearningAnalyticsService::class);
  184. // 检查服务健康状态
  185. if (!$service->checkHealth()) {
  186. $this->errorMessage = '学习分析系统当前不可用,请稍后重试';
  187. $this->isLoading = false;
  188. return;
  189. }
  190. Log::info('开始加载仪表板数据', ['student_id' => $this->studentId]);
  191. // 获取各项数据
  192. $masteryOverview = $service->getStudentMasteryOverview($this->studentId);
  193. $skillProficiency = $service->getStudentSkillProficiency($this->studentId);
  194. $skillSummary = $service->getStudentSkillSummary($this->studentId);
  195. $predictions = $service->getStudentPredictions($this->studentId, 5);
  196. $learningPaths = $service->getStudentLearningPaths($this->studentId, 3);
  197. $predictionAnalytics = $service->getPredictionAnalytics($this->studentId);
  198. $pathAnalytics = $service->getLearningPathAnalytics($this->studentId);
  199. $quickPrediction = $service->quickScorePrediction($this->studentId);
  200. Log::info('快速预测结果', [
  201. 'student_id' => $this->studentId,
  202. 'quick_prediction' => $quickPrediction
  203. ]);
  204. $recommendations = $service->recommendLearningPaths($this->studentId, 3);
  205. // 组合数据
  206. $this->dashboardData = [
  207. 'mastery' => [
  208. 'overview' => $masteryOverview,
  209. 'list' => $service->getStudentMasteryList($this->studentId),
  210. ],
  211. 'skill' => [
  212. 'proficiency' => $skillProficiency,
  213. 'summary' => $skillSummary,
  214. ],
  215. 'prediction' => [
  216. 'list' => $predictions,
  217. 'analytics' => $predictionAnalytics,
  218. 'quick' => $quickPrediction,
  219. ],
  220. 'learning_path' => [
  221. 'list' => $learningPaths,
  222. 'analytics' => $pathAnalytics,
  223. 'recommendations' => $recommendations,
  224. ],
  225. ];
  226. $this->mindmapMasteryData = $this->buildMasteryMap(
  227. $this->dashboardData['mastery']['list'] ?? []
  228. );
  229. $this->dispatch('mastery-updated', data: $this->mindmapMasteryData);
  230. Log::info('仪表板数据加载完成', [
  231. 'student_id' => $this->studentId,
  232. 'dashboard_data_keys' => array_keys($this->dashboardData)
  233. ]);
  234. try {
  235. $mistakeService = app(MistakeBookService::class);
  236. $this->mistakePanel = $mistakeService->getPanelSnapshot($this->studentId, 5);
  237. } catch (\Exception $e) {
  238. Log::warning('加载错题本面板数据失败', [
  239. 'student_id' => $this->studentId,
  240. 'error' => $e->getMessage()
  241. ]);
  242. $this->mistakePanel = [];
  243. }
  244. } catch (\Exception $e) {
  245. $this->errorMessage = '加载数据时发生错误:' . $e->getMessage();
  246. Log::error('学生仪表板数据加载失败', [
  247. 'student_id' => $this->studentId,
  248. 'error' => $e->getMessage()
  249. ]);
  250. $this->mindmapMasteryData = [];
  251. $this->dispatch('mastery-updated', data: []);
  252. $this->mistakePanel = [];
  253. } finally {
  254. $this->isLoading = false;
  255. }
  256. }
  257. public function recalculateMastery(string $kpCode): void
  258. {
  259. try {
  260. $service = app(LearningAnalyticsService::class);
  261. $result = $service->recalculateMastery($this->studentId, $kpCode);
  262. if ($result) {
  263. $this->dispatch('notify', message: '掌握度重新计算完成', type: 'success');
  264. $this->loadDashboardData(); // 刷新数据
  265. } else {
  266. $this->dispatch('notify', message: '掌握度重新计算失败', type: 'danger');
  267. }
  268. } catch (\Exception $e) {
  269. Log::error('重新计算掌握度失败', [
  270. 'student_id' => $this->studentId,
  271. 'kp_code' => $kpCode,
  272. 'error' => $e->getMessage()
  273. ]);
  274. $this->dispatch('notify', message: '操作失败:' . $e->getMessage(), type: 'danger');
  275. }
  276. }
  277. public function batchUpdateSkills(): void
  278. {
  279. try {
  280. $service = app(LearningAnalyticsService::class);
  281. $result = $service->batchUpdateSkillProficiency($this->studentId);
  282. if ($result) {
  283. $this->dispatch('notify', message: '技能熟练度更新完成', type: 'success');
  284. $this->loadDashboardData(); // 刷新数据
  285. } else {
  286. $this->dispatch('notify', message: '技能熟练度更新失败', type: 'danger');
  287. }
  288. } catch (\Exception $e) {
  289. Log::error('批量更新技能熟练度失败', [
  290. 'student_id' => $this->studentId,
  291. 'error' => $e->getMessage()
  292. ]);
  293. $this->dispatch('notify', message: '操作失败:' . $e->getMessage(), type: 'danger');
  294. }
  295. }
  296. public function generateQuickPrediction(): void
  297. {
  298. try {
  299. $service = app(LearningAnalyticsService::class);
  300. $result = $service->quickScorePrediction($this->studentId);
  301. if ($result) {
  302. $this->dispatch('notify', message: '快速预测生成完成', type: 'success');
  303. $this->loadDashboardData(); // 刷新数据
  304. } else {
  305. $this->dispatch('notify', message: '快速预测生成失败', type: 'danger');
  306. }
  307. } catch (\Exception $e) {
  308. Log::error('生成快速预测失败', [
  309. 'student_id' => $this->studentId,
  310. 'error' => $e->getMessage()
  311. ]);
  312. $this->dispatch('notify', message: '操作失败:' . $e->getMessage(), type: 'danger');
  313. }
  314. }
  315. protected function buildMasteryMap(array $list): array
  316. {
  317. $map = [];
  318. $items = $list['data'] ?? $list['masteries'] ?? $list;
  319. if (!is_array($items)) {
  320. return $map;
  321. }
  322. foreach ($items as $item) {
  323. if (!is_array($item)) {
  324. continue;
  325. }
  326. $code = $item['kp_code'] ?? $item['code'] ?? null;
  327. if (!$code) {
  328. continue;
  329. }
  330. $map[$code] = $item;
  331. }
  332. return $map;
  333. }
  334. public function openMindmapDrawer(string $nodeId): void
  335. {
  336. $this->mindmapSelectedNode = $nodeId;
  337. $this->mindmapNodeDetails = $this->getNodeDetails($nodeId, $this->mindmapMasteryData);
  338. $this->mindmapDrawerOpen = true;
  339. }
  340. public function closeMindmapDrawer(): void
  341. {
  342. $this->mindmapDrawerOpen = false;
  343. $this->mindmapSelectedNode = null;
  344. $this->mindmapNodeDetails = [];
  345. }
  346. /**
  347. * 监听TeacherStudentSelector组件的老师变化事件
  348. */
  349. #[On('teacherChanged')]
  350. public function onTeacherChanged(string $teacherId): void
  351. {
  352. $this->teacherId = $teacherId;
  353. $this->loadStudentsByTeacher();
  354. $this->studentId = $this->getDefaultStudentId();
  355. }
  356. /**
  357. * 监听TeacherStudentSelector组件的学生变化事件
  358. */
  359. #[On('studentChanged')]
  360. public function onStudentChanged(string $teacherId, string $studentId): void
  361. {
  362. $this->teacherId = $teacherId;
  363. $this->studentId = $studentId;
  364. $this->loadDashboardData();
  365. }
  366. }