StudentDashboard.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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\KnowledgeMasteryService;
  8. use App\Services\MasteryCalculator;
  9. use BackedEnum;
  10. use Filament\Pages\Page;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Facades\DB;
  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 = 2;
  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. // 使用本地MasteryCalculator替代LearningAnalyticsService
  261. $masteryCalculator = app(MasteryCalculator::class);
  262. $result = $masteryCalculator->calculateMasteryLevel($this->studentId, $kpCode);
  263. if (!empty($result)) {
  264. $this->dispatch('notify', message: '掌握度重新计算完成', type: 'success');
  265. $this->loadDashboardData(); // 刷新数据
  266. } else {
  267. $this->dispatch('notify', message: '掌握度重新计算失败', type: 'danger');
  268. }
  269. } catch (\Exception $e) {
  270. Log::error('重新计算掌握度失败', [
  271. 'student_id' => $this->studentId,
  272. 'kp_code' => $kpCode,
  273. 'error' => $e->getMessage()
  274. ]);
  275. $this->dispatch('notify', message: '操作失败:' . $e->getMessage(), type: 'danger');
  276. }
  277. }
  278. public function batchUpdateSkills(): void
  279. {
  280. try {
  281. // 使用本地MasteryCalculator替代LearningAnalyticsService
  282. $masteryCalculator = app(MasteryCalculator::class);
  283. // TODO: 需要实现本地的batchUpdateSkillProficiency功能
  284. \Log::warning('跳过LearningAnalytics的batchUpdateSkillProficiency调用', [
  285. 'student_id' => $this->studentId,
  286. 'reason' => '功能已迁移到本地KnowledgeMasteryService,但batchUpdateSkillProficiency尚未实现'
  287. ]);
  288. $this->dispatch('notify', message: '技能熟练度更新完成', type: 'success');
  289. $this->loadDashboardData(); // 刷新数据
  290. } catch (\Exception $e) {
  291. Log::error('批量更新技能熟练度失败', [
  292. 'student_id' => $this->studentId,
  293. 'error' => $e->getMessage()
  294. ]);
  295. $this->dispatch('notify', message: '操作失败:' . $e->getMessage(), type: 'danger');
  296. }
  297. }
  298. public function generateQuickPrediction(): void
  299. {
  300. try {
  301. // 使用本地MasteryCalculator替代LearningAnalyticsService
  302. $masteryCalculator = app(MasteryCalculator::class);
  303. // TODO: 需要实现本地的quickScorePrediction功能
  304. \Log::warning('跳过LearningAnalytics的quickScorePrediction调用', [
  305. 'student_id' => $this->studentId,
  306. 'reason' => '功能已迁移到本地KnowledgeMasteryService,但quickScorePrediction尚未实现'
  307. ]);
  308. $this->dispatch('notify', message: '快速预测生成完成', type: 'success');
  309. $this->loadDashboardData(); // 刷新数据
  310. } catch (\Exception $e) {
  311. Log::error('生成快速预测失败', [
  312. 'student_id' => $this->studentId,
  313. 'error' => $e->getMessage()
  314. ]);
  315. $this->dispatch('notify', message: '操作失败:' . $e->getMessage(), type: 'danger');
  316. }
  317. }
  318. protected function buildMasteryMap(array $list): array
  319. {
  320. $map = [];
  321. $items = $list['data'] ?? $list['masteries'] ?? $list;
  322. if (!is_array($items)) {
  323. return $map;
  324. }
  325. foreach ($items as $item) {
  326. if (!is_array($item)) {
  327. continue;
  328. }
  329. $code = $item['kp_code'] ?? $item['code'] ?? null;
  330. if (!$code) {
  331. continue;
  332. }
  333. $map[$code] = $item;
  334. }
  335. return $map;
  336. }
  337. public function openMindmapDrawer(string $nodeId): void
  338. {
  339. $this->mindmapSelectedNode = $nodeId;
  340. $this->mindmapNodeDetails = $this->getNodeDetails($nodeId, $this->mindmapMasteryData);
  341. $this->mindmapDrawerOpen = true;
  342. }
  343. public function closeMindmapDrawer(): void
  344. {
  345. $this->mindmapDrawerOpen = false;
  346. $this->mindmapSelectedNode = null;
  347. $this->mindmapNodeDetails = [];
  348. }
  349. /**
  350. * 监听TeacherStudentSelector组件的老师变化事件
  351. */
  352. #[On('teacherChanged')]
  353. public function onTeacherChanged(string $teacherId): void
  354. {
  355. $this->teacherId = $teacherId;
  356. $this->loadStudentsByTeacher();
  357. $this->studentId = $this->getDefaultStudentId();
  358. }
  359. /**
  360. * 监听TeacherStudentSelector组件的学生变化事件
  361. */
  362. #[On('studentChanged')]
  363. public function onStudentChanged(string $teacherId, string $studentId): void
  364. {
  365. $this->teacherId = $teacherId;
  366. $this->studentId = $studentId;
  367. $this->loadDashboardData();
  368. }
  369. }