using System; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using ClassNotify.Client.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Utils; namespace ClassNotify.Client.ViewModels { public enum DevicePage { FirstPairing, // WAITING_FOR_FIRST_BIND (首次引导态) Running // RUNNING (日常运行与维护态) } /// /// Turn 117 教室大屏终端最终权威 ViewModel /// 严格遵循单向事实驱动: /// HasAnyTeacherBinding == false => FirstPairing /// HasAnyTeacherBinding == true => Running /// public sealed class DeviceStatusViewModel : INotifyPropertyChanged { private DevicePage _page = DevicePage.FirstPairing; private string _rawPairingCode = string.Empty; private string _pairingCodeDisplay = "等待获取"; private string _countdownText = "有效时间:10 分钟"; private DateTimeOffset _pairingExpiresAt = DateTimeOffset.MinValue; private DispatcherTimer? _countdownTimer; private BitmapImage? _qrImage; private ServerReachabilityState _reachabilityState = ServerReachabilityState.Checking; private bool _isRequestingCode = false; public event PropertyChangedEventHandler? PropertyChanged; public DevicePage Page { get => _page; private set { if (_page != value) { _page = value; OnPropertyChanged(); OnPropertyChanged(nameof(IsFirstPairing)); OnPropertyChanged(nameof(IsRunning)); OnPropertyChanged(nameof(HeaderReachabilityText)); OnPropertyChanged(nameof(FooterTipText)); } } } public bool IsFirstPairing => Page == DevicePage.FirstPairing; public bool IsRunning => Page == DevicePage.Running; public string AppVersion => $"v{typeof(DeviceStatusViewModel).Assembly.GetName().Version?.ToString(3) ?? "2.2.0"}"; public Func? RefreshCodeHandler { get; set; } public bool HasEightDigits { get { var clean = PairingCodeFormatter.Normalize(_rawPairingCode); return clean.Length == 8; } } public string Digit0 => GetDigit(0); public string Digit1 => GetDigit(1); public string Digit2 => GetDigit(2); public string Digit3 => GetDigit(3); public string Digit4 => GetDigit(4); public string Digit5 => GetDigit(5); public string Digit6 => GetDigit(6); public string Digit7 => GetDigit(7); private string GetDigit(int index) { var clean = PairingCodeFormatter.Normalize(_rawPairingCode); return (clean.Length == 8 && index >= 0 && index < 8) ? clean[index].ToString() : string.Empty; } public Visibility EightDigitsVisibility => HasEightDigits ? Visibility.Visible : Visibility.Collapsed; public Visibility PlaceholderVisibility => HasEightDigits ? Visibility.Collapsed : Visibility.Visible; public void NotifyDigitsChanged() { OnPropertyChanged(nameof(HasEightDigits)); OnPropertyChanged(nameof(EightDigitsVisibility)); OnPropertyChanged(nameof(PlaceholderVisibility)); OnPropertyChanged(nameof(Digit0)); OnPropertyChanged(nameof(Digit1)); OnPropertyChanged(nameof(Digit2)); OnPropertyChanged(nameof(Digit3)); OnPropertyChanged(nameof(Digit4)); OnPropertyChanged(nameof(Digit5)); OnPropertyChanged(nameof(Digit6)); OnPropertyChanged(nameof(Digit7)); } public string PairingCodeDisplay { get => _pairingCodeDisplay; private set { if (_pairingCodeDisplay != value) { _pairingCodeDisplay = value; OnPropertyChanged(); } } } public string CountdownText { get => _countdownText; private set { if (_countdownText != value) { _countdownText = value; OnPropertyChanged(); } } } public BitmapImage? QrImage { get => _qrImage; private set { if (_qrImage != value) { _qrImage = value; OnPropertyChanged(); } } } public ServerReachabilityState ReachabilityState { get => _reachabilityState; set { if (_reachabilityState != value) { _reachabilityState = value; OnPropertyChanged(); OnPropertyChanged(nameof(HeaderReachabilityText)); OnPropertyChanged(nameof(HeaderReachabilityBrush)); OnPropertyChanged(nameof(HeaderReachabilityBackground)); OnPropertyChanged(nameof(HeaderReachabilityBorder)); } } } public string HeaderReachabilityText { get { switch (ReachabilityState) { case ServerReachabilityState.Reachable: return Page == DevicePage.FirstPairing ? "● 已连接云服务" : "● 云服务连接正常"; case ServerReachabilityState.Checking: return "◌ 正在检测云服务"; case ServerReachabilityState.Unreachable: default: return "● 暂时无法连接云服务"; } } } public Brush HeaderReachabilityBrush { get { switch (ReachabilityState) { case ServerReachabilityState.Reachable: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#16A34A")); case ServerReachabilityState.Checking: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706")); case ServerReachabilityState.Unreachable: default: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); } } } public Brush HeaderReachabilityBackground { get { switch (ReachabilityState) { case ServerReachabilityState.Reachable: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DCFCE7")); case ServerReachabilityState.Checking: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FEF3C7")); case ServerReachabilityState.Unreachable: default: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FEE2E2")); } } } public Brush HeaderReachabilityBorder { get { switch (ReachabilityState) { case ServerReachabilityState.Reachable: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#86EFAC")); case ServerReachabilityState.Checking: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FDE68A")); case ServerReachabilityState.Unreachable: default: return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FCA5A5")); } } } public string FooterTipText { get { return Page == DevicePage.FirstPairing ? "本大屏尚未绑定教师,完成绑定后即可接收通知。" : "大屏服务正在运行 · 其他教师可在网页后台输入此码,将本大屏添加到自己的设备列表"; } } public bool IsRequestingCode { get => _isRequestingCode; set { if (_isRequestingCode != value) { _isRequestingCode = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanRefreshCode)); } } } public bool CanRefreshCode => !_isRequestingCode; public DeviceStatusViewModel() { // Generate QR Code bitmap for teacher registration URL QrImage = QrCodeImageService.GenerateQrBitmap("https://classnotify.paradise.eu.org/register", pixelsPerModule: 16); // Connect to ServerReachabilityService ReachabilityState = ServerReachabilityService.Instance.CurrentState; ServerReachabilityService.Instance.ReachabilityChanged += state => { App.Current.Dispatcher.InvokeAsync(() => { ReachabilityState = state; }); }; } public void SetPairingCode(string rawCode, int ttlSeconds = 600) => UpdatePairingCode(rawCode, ttlSeconds); private OperationalRestrictionState _restrictionState = OperationalRestrictionState.None; public OperationalRestrictionState RestrictionState { get => _restrictionState; set { if (_restrictionState != value) { _restrictionState = value; OnPropertyChanged(); OnPropertyChanged(nameof(RestrictionVisibility)); } } } public Visibility RestrictionVisibility => (_restrictionState != OperationalRestrictionState.None) ? Visibility.Visible : Visibility.Collapsed; /// /// 权威状态快照映射:只按 HasAnyTeacherBinding 决定页面 /// public void ApplySnapshot(ClientStateSnapshotDto state) { if (state == null) return; // Turn 117 Invariant: HasAnyTeacherBinding determines Page A vs Page B bool hasTeacher = state.BoundTeacherCount > 0 || state.BindingState == DeviceBindingState.Bound; Page = hasTeacher ? DevicePage.Running : DevicePage.FirstPairing; RestrictionState = state.RestrictionState; } public void ApplyPairingSession(PairingSessionDto session) { if (session == null) return; if (session.State == PairingSessionState.Active && !string.IsNullOrWhiteSpace(session.Code)) { _rawPairingCode = session.Code; PairingCodeDisplay = PairingCodeFormatter.FormatPairingCode(session.Code); NotifyDigitsChanged(); _pairingExpiresAt = session.ExpiresAt; StartCountdownTimer(); } else { _rawPairingCode = string.Empty; PairingCodeDisplay = "等待获取"; NotifyDigitsChanged(); CountdownText = "获取配对码失败,请重试"; } } public void UpdatePairingCode(string rawCode, int ttlSeconds = 600) { _rawPairingCode = rawCode; PairingCodeDisplay = PairingCodeFormatter.FormatPairingCode(rawCode); NotifyDigitsChanged(); _pairingExpiresAt = DateTimeOffset.UtcNow.AddSeconds(ttlSeconds > 0 ? ttlSeconds : 600); StartCountdownTimer(); } private void StartCountdownTimer() { StopCountdownTimer(); UpdateCountdown(); _countdownTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; _countdownTimer.Tick += (s, e) => UpdateCountdown(); _countdownTimer.Start(); } private async void UpdateCountdown() { var remaining = (int)(_pairingExpiresAt - DateTimeOffset.UtcNow).TotalSeconds; if (remaining <= 0) { CountdownText = "有效时间:已到期,正在自动续码..."; if (!_isRequestingCode && RefreshCodeHandler != null) { await TriggerAutoRefreshAsync(); } } else { // Auto-renew 15 seconds before expiry if (remaining <= 15 && !_isRequestingCode && RefreshCodeHandler != null) { _ = TriggerAutoRefreshAsync(); } int m = remaining / 60; int s = remaining % 60; CountdownText = $"有效时间:{m:D2}:{s:D2}"; } } public async Task TriggerAutoRefreshAsync() { if (_isRequestingCode || RefreshCodeHandler == null) return; IsRequestingCode = true; try { await RefreshCodeHandler(); } catch (Exception ex) { App.LogClient($"Auto-refresh pairing code failed: {ex.Message}"); } finally { IsRequestingCode = false; } } public void StopCountdownTimer() { if (_countdownTimer != null) { _countdownTimer.Stop(); _countdownTimer = null; } } private void OnPropertyChanged([CallerMemberName] string? name = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } }