| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199 |
- import { ReviewPage, reviewOverview } from '../../core/review-page';
- import { CommonModule } from '@angular/common';
- import { ChangeDetectionStrategy, Component, computed, inject, OnDestroy, OnInit, signal } from '@angular/core';
- import { Router, RouterLink } from '@angular/router';
- import { AlertCircle, BarChart3, BookOpen, CalendarDays, Check, ChevronRight, Clock3, Eye, EyeOff, GraduationCap, Headphones, Info, LucideAngularModule, RefreshCw, Search, Sparkles, UserRound, Zap } from 'lucide-angular';
- import { finalize } from 'rxjs';
- import { antiForgetCompleted, antiForgetDate, buildAntiForgetView, findAntiForgetList } from '../../core/anti-forget';
- import { ApiError, ApiService } from '../../core/api.service';
- import { PlatformService } from '../../core/platform.service';
- import { SessionService } from '../../core/session.service';
- import { LiveDataRefreshService } from '../../core/live-data-refresh.service';
- type Item = Record<string, unknown>;
- @Component({
- selector: 'app-home-page',
- standalone: true,
- imports: [CommonModule, RouterLink, LucideAngularModule],
- templateUrl: './home-page.component.html',
- styleUrl: './home-page.component.scss',
- changeDetection: ChangeDetectionStrategy.OnPush,
- })
- export class HomePageComponent implements OnInit, OnDestroy {
- readonly session = inject(SessionService);
- readonly stats = signal<Record<string, number>>({});
- readonly statsLoading = signal(false);
- readonly coachStatsError = signal('');
- readonly recommendations = signal<Item[]>([]);
- readonly recommendationError = signal('');
- readonly commissionHidden = signal(true);
- readonly antiForgetItems = signal<Item[]>([]);
- readonly antiForgetLoading = signal(false);
- readonly antiForgetError = signal('');
- readonly reviewData=signal<ReviewPage|null>(null);
- readonly antiForgetView = computed(() => reviewOverview(this.reviewData()));
- readonly isCoach = computed(() => Number(this.session.groupId()) === 3);
- readonly coachReviewItems = computed(() => [...this.antiForgetItems()].sort((left, right) => {
- const stateOrder = (item: Item) => antiForgetCompleted(item) ? 2 : this.coachReviewReady(item) ? 0 : 1;
- const stateDifference = stateOrder(left) - stateOrder(right);
- if (stateDifference) return stateDifference;
- const dateDifference = antiForgetDate(left).localeCompare(antiForgetDate(right));
- return stateOrder(left) === 1 ? dateDifference : -dateDifference;
- }));
- readonly coachReviewSummary=computed(()=>this.reviewData()?.summary||{today:0,due:0,completed:0});
- readonly icons = { AlertCircle, BarChart3, BookOpen, CalendarDays, Check, ChevronRight, Clock3, Eye, EyeOff, GraduationCap, Headphones, Info, RefreshCw, Search, Sparkles, UserRound, Zap };
- private readonly api = inject(ApiService);
- private readonly router = inject(Router);
- private readonly platform = inject(PlatformService);
- private readonly liveData = inject(LiveDataRefreshService);
- private stopLiveRefresh?: () => void;
- ngOnInit(): void {
- const uid = this.session.user()?.userId;
- if (uid) {
- this.loadStats(uid);
- this.loadAntiForget(uid);
- this.stopLiveRefresh = this.liveData.watch({
- scopes: ['appointments', 'review', 'account'],
- studentId: () => Number(this.session.user()?.userId) || undefined,
- onRefresh: () => {
- const currentId = this.session.user()?.userId;
- if (!currentId) return;
- this.loadStats(currentId, true);
- this.loadAntiForget(currentId, true);
- },
- });
- }
- if (this.isCoach()) return;
- this.loadRecommendations();
- }
- ngOnDestroy(): void {
- this.stopLiveRefresh?.();
- }
- retryCoachStats(): void {
- const uid = this.session.user()?.userId;
- if (uid) this.loadStats(uid);
- }
- loadRecommendations(): void {
- this.recommendationError.set('');
- this.api.get<unknown>('product_list', { nodes: '15,16', hot: 1, cpage: 1, psize: 8 }).subscribe({
- next: ({ result }) => this.recommendations.set(this.toList(result)),
- error: (error: ApiError) => this.recommendationError.set(error.message),
- });
- }
- openProduct(item: Item): void {
- const id = item['ID'] ?? item['id'] ?? item['GeneralID'];
- if (id) void this.router.navigate(['/pages/shop/shop_item'], { queryParams: { id } });
- }
- image(item: Item): string { return this.api.assetUrl(item['Thumbnails'] ?? item['Pic']); }
- name(item: Item): string { return String(item['Proname'] ?? item['Title'] ?? '学习内容'); }
- price(item: Item): string { return Number(item['LinPrice'] ?? item['Price'] ?? 0).toFixed(2); }
- retryAntiForget(): void {
- const uid = this.session.user()?.userId;
- if (uid) this.loadAntiForget(uid);
- }
- coachReviewStudent(item: Item): string {
- const studentId = String(item['yhid'] ?? '').trim();
- const student = this.reviewData()?.students?.find((entry) => String(entry.id) === studentId);
- const names = [student?.name, item['honeyName'], item['HoneyName'], item['Title']];
- for (const name of names) {
- const displayName = String(name ?? '').split('@')[0].trim();
- if (displayName) return displayName;
- }
- return studentId && studentId !== '0' ? `学员 ${studentId}` : '未关联学员';
- }
- coachReviewTitle(item: Item): string {
- return String(item['kc_title'] ?? item['kctitle'] ?? item['kcmc'] ?? '单词复习').split('@')[0];
- }
- coachReviewDate(item: Item): string {
- return antiForgetDate(item) || '日期待确认';
- }
- coachReviewReady(item: Item): boolean {
- const date = antiForgetDate(item);
- return Boolean(date && date <= this.today() && !antiForgetCompleted(item));
- }
- coachReviewStatus(item: Item): string {
- if (antiForgetCompleted(item)) return '已完成';
- return this.coachReviewReady(item) ? '待复习' : '未到期';
- }
- coachReviewAction(item: Item): string {
- if (antiForgetCompleted(item)) return '查看';
- return this.coachReviewReady(item) ? '带学生复习' : '查看计划';
- }
- openCoachReview(item: Item): void {
- if (!this.coachReviewReady(item) && !antiForgetCompleted(item)) {
- void this.router.navigateByUrl('/pages/stu/stu_calendar');
- return;
- }
- const studentId = Number(item['yhid'] ?? 0);
- if (!studentId) {
- this.platform.toast('复习任务缺少关联学员', 'error');
- return;
- }
- this.session.setStudent({
- userId: studentId,
- honeyName: this.coachReviewStudent(item),
- groupId: 1,
- });
- void this.router.navigate(['/pages/stu/record'], {
- queryParams: { id: item['xxjlid'], gid: item['GeneralID'], kcid: item['kcid'] },
- });
- }
- private loadStats(uid: string | number, background = false): void {
- if (!background) {
- this.statsLoading.set(true);
- this.coachStatsError.set('');
- }
- this.api.post<Record<string, number>>('e_order_tongji', { uid }).pipe(
- finalize(() => { if (!background) this.statsLoading.set(false); }),
- ).subscribe({
- next: ({ result }) => this.stats.set(result || {}),
- error: () => {
- if (!background && this.isCoach()) this.coachStatsError.set('今日业务数据暂时无法加载');
- },
- });
- }
- private loadAntiForget(uid: string | number, background = false): void {
- if (!background) {
- this.antiForgetLoading.set(true);
- this.antiForgetError.set('');
- }
- this.api.post<ReviewPage>('app_review_page', { uid, page:1,pageSize:20,status:'pending' }).pipe(
- finalize(() => { if (!background) this.antiForgetLoading.set(false); }),
- ).subscribe({
- next: ({ result }) => {this.reviewData.set(result);this.antiForgetItems.set(result.items);},
- error: () => { if (!background) this.antiForgetError.set('抗遗忘计划暂时无法加载'); },
- });
- }
- private today(): string {
- const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date());
- const value = (type: Intl.DateTimeFormatPartTypes) => parts.find((part) => part.type === type)?.value ?? '';
- return `${value('year')}-${value('month')}-${value('day')}`;
- }
- private toList(value: unknown): Item[] {
- if (Array.isArray(value)) return value as Item[];
- if (value && typeof value === 'object') {
- for (const nested of Object.values(value)) if (Array.isArray(nested)) return nested as Item[];
- }
- return [];
- }
- }
|