home-page.component.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { ReviewPage, reviewOverview } from '../../core/review-page';
  2. import { CommonModule } from '@angular/common';
  3. import { ChangeDetectionStrategy, Component, computed, inject, OnDestroy, OnInit, signal } from '@angular/core';
  4. import { Router, RouterLink } from '@angular/router';
  5. import { AlertCircle, BarChart3, BookOpen, CalendarDays, Check, ChevronRight, Clock3, Eye, EyeOff, GraduationCap, Headphones, Info, LucideAngularModule, RefreshCw, Search, Sparkles, UserRound, Zap } from 'lucide-angular';
  6. import { finalize } from 'rxjs';
  7. import { antiForgetCompleted, antiForgetDate, buildAntiForgetView, findAntiForgetList } from '../../core/anti-forget';
  8. import { ApiError, ApiService } from '../../core/api.service';
  9. import { PlatformService } from '../../core/platform.service';
  10. import { SessionService } from '../../core/session.service';
  11. import { LiveDataRefreshService } from '../../core/live-data-refresh.service';
  12. type Item = Record<string, unknown>;
  13. @Component({
  14. selector: 'app-home-page',
  15. standalone: true,
  16. imports: [CommonModule, RouterLink, LucideAngularModule],
  17. templateUrl: './home-page.component.html',
  18. styleUrl: './home-page.component.scss',
  19. changeDetection: ChangeDetectionStrategy.OnPush,
  20. })
  21. export class HomePageComponent implements OnInit, OnDestroy {
  22. readonly session = inject(SessionService);
  23. readonly stats = signal<Record<string, number>>({});
  24. readonly statsLoading = signal(false);
  25. readonly coachStatsError = signal('');
  26. readonly recommendations = signal<Item[]>([]);
  27. readonly recommendationError = signal('');
  28. readonly commissionHidden = signal(true);
  29. readonly antiForgetItems = signal<Item[]>([]);
  30. readonly antiForgetLoading = signal(false);
  31. readonly antiForgetError = signal('');
  32. readonly reviewData=signal<ReviewPage|null>(null);
  33. readonly antiForgetView = computed(() => reviewOverview(this.reviewData()));
  34. readonly isCoach = computed(() => Number(this.session.groupId()) === 3);
  35. readonly coachReviewItems = computed(() => [...this.antiForgetItems()].sort((left, right) => {
  36. const stateOrder = (item: Item) => antiForgetCompleted(item) ? 2 : this.coachReviewReady(item) ? 0 : 1;
  37. const stateDifference = stateOrder(left) - stateOrder(right);
  38. if (stateDifference) return stateDifference;
  39. const dateDifference = antiForgetDate(left).localeCompare(antiForgetDate(right));
  40. return stateOrder(left) === 1 ? dateDifference : -dateDifference;
  41. }));
  42. readonly coachReviewSummary=computed(()=>this.reviewData()?.summary||{today:0,due:0,completed:0});
  43. readonly icons = { AlertCircle, BarChart3, BookOpen, CalendarDays, Check, ChevronRight, Clock3, Eye, EyeOff, GraduationCap, Headphones, Info, RefreshCw, Search, Sparkles, UserRound, Zap };
  44. private readonly api = inject(ApiService);
  45. private readonly router = inject(Router);
  46. private readonly platform = inject(PlatformService);
  47. private readonly liveData = inject(LiveDataRefreshService);
  48. private stopLiveRefresh?: () => void;
  49. ngOnInit(): void {
  50. const uid = this.session.user()?.userId;
  51. if (uid) {
  52. this.loadStats(uid);
  53. this.loadAntiForget(uid);
  54. this.stopLiveRefresh = this.liveData.watch({
  55. scopes: ['appointments', 'review', 'account'],
  56. studentId: () => Number(this.session.user()?.userId) || undefined,
  57. onRefresh: () => {
  58. const currentId = this.session.user()?.userId;
  59. if (!currentId) return;
  60. this.loadStats(currentId, true);
  61. this.loadAntiForget(currentId, true);
  62. },
  63. });
  64. }
  65. if (this.isCoach()) return;
  66. this.loadRecommendations();
  67. }
  68. ngOnDestroy(): void {
  69. this.stopLiveRefresh?.();
  70. }
  71. retryCoachStats(): void {
  72. const uid = this.session.user()?.userId;
  73. if (uid) this.loadStats(uid);
  74. }
  75. loadRecommendations(): void {
  76. this.recommendationError.set('');
  77. this.api.get<unknown>('product_list', { nodes: '15,16', hot: 1, cpage: 1, psize: 8 }).subscribe({
  78. next: ({ result }) => this.recommendations.set(this.toList(result)),
  79. error: (error: ApiError) => this.recommendationError.set(error.message),
  80. });
  81. }
  82. openProduct(item: Item): void {
  83. const id = item['ID'] ?? item['id'] ?? item['GeneralID'];
  84. if (id) void this.router.navigate(['/pages/shop/shop_item'], { queryParams: { id } });
  85. }
  86. image(item: Item): string { return this.api.assetUrl(item['Thumbnails'] ?? item['Pic']); }
  87. name(item: Item): string { return String(item['Proname'] ?? item['Title'] ?? '学习内容'); }
  88. price(item: Item): string { return Number(item['LinPrice'] ?? item['Price'] ?? 0).toFixed(2); }
  89. retryAntiForget(): void {
  90. const uid = this.session.user()?.userId;
  91. if (uid) this.loadAntiForget(uid);
  92. }
  93. coachReviewStudent(item: Item): string {
  94. const studentId = String(item['yhid'] ?? '').trim();
  95. const student = this.reviewData()?.students?.find((entry) => String(entry.id) === studentId);
  96. const names = [student?.name, item['honeyName'], item['HoneyName'], item['Title']];
  97. for (const name of names) {
  98. const displayName = String(name ?? '').split('@')[0].trim();
  99. if (displayName) return displayName;
  100. }
  101. return studentId && studentId !== '0' ? `学员 ${studentId}` : '未关联学员';
  102. }
  103. coachReviewTitle(item: Item): string {
  104. return String(item['kc_title'] ?? item['kctitle'] ?? item['kcmc'] ?? '单词复习').split('@')[0];
  105. }
  106. coachReviewDate(item: Item): string {
  107. return antiForgetDate(item) || '日期待确认';
  108. }
  109. coachReviewReady(item: Item): boolean {
  110. const date = antiForgetDate(item);
  111. return Boolean(date && date <= this.today() && !antiForgetCompleted(item));
  112. }
  113. coachReviewStatus(item: Item): string {
  114. if (antiForgetCompleted(item)) return '已完成';
  115. return this.coachReviewReady(item) ? '待复习' : '未到期';
  116. }
  117. coachReviewAction(item: Item): string {
  118. if (antiForgetCompleted(item)) return '查看';
  119. return this.coachReviewReady(item) ? '带学生复习' : '查看计划';
  120. }
  121. openCoachReview(item: Item): void {
  122. if (!this.coachReviewReady(item) && !antiForgetCompleted(item)) {
  123. void this.router.navigateByUrl('/pages/stu/stu_calendar');
  124. return;
  125. }
  126. const studentId = Number(item['yhid'] ?? 0);
  127. if (!studentId) {
  128. this.platform.toast('复习任务缺少关联学员', 'error');
  129. return;
  130. }
  131. this.session.setStudent({
  132. userId: studentId,
  133. honeyName: this.coachReviewStudent(item),
  134. groupId: 1,
  135. });
  136. void this.router.navigate(['/pages/stu/record'], {
  137. queryParams: { id: item['xxjlid'], gid: item['GeneralID'], kcid: item['kcid'] },
  138. });
  139. }
  140. private loadStats(uid: string | number, background = false): void {
  141. if (!background) {
  142. this.statsLoading.set(true);
  143. this.coachStatsError.set('');
  144. }
  145. this.api.post<Record<string, number>>('e_order_tongji', { uid }).pipe(
  146. finalize(() => { if (!background) this.statsLoading.set(false); }),
  147. ).subscribe({
  148. next: ({ result }) => this.stats.set(result || {}),
  149. error: () => {
  150. if (!background && this.isCoach()) this.coachStatsError.set('今日业务数据暂时无法加载');
  151. },
  152. });
  153. }
  154. private loadAntiForget(uid: string | number, background = false): void {
  155. if (!background) {
  156. this.antiForgetLoading.set(true);
  157. this.antiForgetError.set('');
  158. }
  159. this.api.post<ReviewPage>('app_review_page', { uid, page:1,pageSize:20,status:'pending' }).pipe(
  160. finalize(() => { if (!background) this.antiForgetLoading.set(false); }),
  161. ).subscribe({
  162. next: ({ result }) => {this.reviewData.set(result);this.antiForgetItems.set(result.items);},
  163. error: () => { if (!background) this.antiForgetError.set('抗遗忘计划暂时无法加载'); },
  164. });
  165. }
  166. private today(): string {
  167. const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date());
  168. const value = (type: Intl.DateTimeFormatPartTypes) => parts.find((part) => part.type === type)?.value ?? '';
  169. return `${value('year')}-${value('month')}-${value('day')}`;
  170. }
  171. private toList(value: unknown): Item[] {
  172. if (Array.isArray(value)) return value as Item[];
  173. if (value && typeof value === 'object') {
  174. for (const nested of Object.values(value)) if (Array.isArray(nested)) return nested as Item[];
  175. }
  176. return [];
  177. }
  178. }