using ChaoXingAutoClass.Interface.Services; using XFEExtension.NetCore.WinUIHelper.Utilities; using System.Collections.ObjectModel; using ChaoXingAutoClass.Browser; using ChaoXingAutoClass.Core; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; using Windows.Storage.Streams; using Microsoft.UI.Dispatching; namespace ChaoXingAutoClass.ViewModels; public partial class MainPageViewModel : ViewModelBase, IDisposable { public ILearningService LearningService { get; } = ServiceManager.GetGlobalService()!; private CancellationTokenSource? _qrStop; private bool _initialized; public ObservableCollection Courses { get; } = []; private readonly DispatcherQueue _dispatcher = DispatcherQueue.GetForCurrentThread(); private bool _subscribed; public MainPageViewModel() => Activate(); public void Activate() { if (!_subscribed) { LearningService.JobChanged += OnJob; _subscribed = true; } foreach (var job in LearningService.Jobs) OnJob(job); } private void OnJob(CourseJobSnapshot job) => _dispatcher.TryEnqueue(() => { Courses.FirstOrDefault(c => CourseIdentity.Key(c.Course) == CourseIdentity.Key(job.Course))?.Update(job); }); public void Dispose() { _qrStop?.Cancel(); if (_subscribed) LearningService.JobChanged -= OnJob; _subscribed = false; } [RelayCommand] private async Task StartSelectedAsync() { var selected = Courses.Where(c => c.IsSelected).Select(c => c.Course).ToArray(); if (selected.Length == 0) { Status = "请先勾选要同时学习的课程。"; return; } IsBusy = true; try { await LearningService.QueueCoursesAsync(selected, CancellationToken.None); Status = $"已启动 {selected.Length} 门课程,当前同时运行上限 {LearningService.EffectiveConcurrency} 门;点击课程查看实时进度。"; } catch (Exception error) { Status = error.Message; } finally { IsBusy = false; } } [RelayCommand] private void StopAll() { foreach (var job in LearningService.Jobs.Where(j => j.IsRunning)) LearningService.Stop(job.Course); } [ObservableProperty] public partial bool IsBusy { get; set; } [ObservableProperty] public partial string Status { get; set; } = "正在恢复登录状态…"; [ObservableProperty] public partial Visibility LoginVisibility { get; set; } = Visibility.Collapsed; [ObservableProperty] public partial Visibility CoursesVisibility { get; set; } = Visibility.Collapsed; [ObservableProperty] public partial Visibility QrVisibility { get; set; } = Visibility.Visible; [ObservableProperty] public partial Visibility PasswordVisibility { get; set; } = Visibility.Collapsed; [ObservableProperty] public partial ImageSource? QrImage { get; set; } [ObservableProperty] public partial string Account { get; set; } = ""; [ObservableProperty] public partial string Password { get; set; } = ""; public async Task InitializeAsync() { Activate(); if (_initialized) return; _initialized = true; await RefreshAsync(); } [RelayCommand] private async Task RefreshAsync() { _qrStop?.Cancel(); IsBusy = true; try { var courses = await LearningService.RefreshCoursesAsync(CancellationToken.None); var selected = Courses.Where(c => c.IsSelected).Select(c => CourseIdentity.Key(c.Course)).ToHashSet(); Courses.Clear(); foreach (var course in courses) { var card = new CourseCardViewModel(course) { IsSelected = selected.Contains(CourseIdentity.Key(course)) }; if (LearningService.GetJob(course) is { } job) card.Update(job); Courses.Add(card); } LoginVisibility = Visibility.Collapsed; CoursesVisibility = Visibility.Visible; Status = $"{Courses.Count} 门课程 · 勾选课程后并行学习,点击卡片查看章节、作业与实时进度"; } catch (LoginRequiredException) { LoginVisibility = Visibility.Visible; CoursesVisibility = Visibility.Collapsed; await RefreshQrAsync(); } catch (Exception error) { Status = error.Message; } finally { IsBusy = false; } } [RelayCommand] private async Task RefreshQrAsync() { _qrStop?.Cancel(); _qrStop?.Dispose(); _qrStop = new(); var token = _qrStop.Token; QrVisibility = Visibility.Visible; PasswordVisibility = Visibility.Collapsed; try { Status = "使用学习通扫描二维码"; var qr = await LearningService.GetQrAsync(token); using var stream = new InMemoryRandomAccessStream(); using (var writer = new DataWriter(stream.GetOutputStreamAt(0))) { writer.WriteBytes(qr.Image); await writer.StoreAsync(); writer.DetachStream(); } stream.Seek(0); var image = new BitmapImage(); await image.SetSourceAsync(stream); QrImage = image; _ = PollQrAsync(qr, token); } catch (OperationCanceledException) when (token.IsCancellationRequested) { } catch (Exception error) { Status = error.Message; } } private async Task PollQrAsync(LoginQr qr, CancellationToken token) { try { while (!token.IsCancellationRequested) { await Task.Delay(2000, token); var result = await LearningService.PollQrAsync(qr, token); Status = result.Message; if (result.LoggedIn) { await RefreshAsync(); return; } if (result.Expired) return; } } catch (OperationCanceledException) when (token.IsCancellationRequested) { } catch (Exception error) { Status = "二维码状态读取失败:" + error.Message; } } [RelayCommand] private void ToggleLogin() { if (PasswordVisibility == Visibility.Visible) { _ = RefreshQrAsync(); return; } _qrStop?.Cancel(); QrVisibility = Visibility.Collapsed; PasswordVisibility = Visibility.Visible; Status = "登录信息只发送至学习通,不保存密码。"; } [RelayCommand] private async Task PasswordLoginAsync() { IsBusy = true; try { var error = await LearningService.PasswordLoginAsync(Account, Password, CancellationToken.None); Password = ""; if (error is null) await RefreshAsync(); else Status = error; } catch (Exception error) { Status = error.Message; } finally { Password = ""; IsBusy = false; } } }