using System; using System.Reactive; using System.Timers; using Avalonia.Threading; using DispenserCommon.Aop; using DispenserCommon.Events; using DispenserCommon.Ioc; using DispenserCommon.Utils; using DispenserCore.Context; using DispenserCore.Model.Entity; using DispenserUI.ViewModels.Login; using ReactiveUI; using Serilog; namespace DispenserUI.ViewModels; /// /// 主界面 UI view model /// [Component, GlobalTry] public class MainVM : ViewModelBase { private readonly GlobalSessionHolder _holder = ServiceLocator.GetService(); private bool _logged; private bool _locked; private string _now = GetNowTime(); private User _who; public MainVM() { // 开启时钟 StartClock(); ToLogout = ReactiveCommand.Create(ToLogoutCmd); // 监听用户登录状态,然后进行页面跳转 _holder.PropertyChanged += (holder, args) => { var session = ((GlobalSessionHolder)holder).GetSession(); if (session == null) { EventBus.Publish(EventType.PageChanged, typeof(LoginVM)); return; } Who = session.User; Logged = true; EventBus.Publish(EventType.PageChanged, typeof(ContainerViewModel)); }; if (!_holder.Logged()) { // 如果没有登录,则跳转到登录页面 // EventBus.Publish(EventType.PageChanged, typeof(LoginVM)); } } /// /// 去首页 /// public ReactiveCommand ToLogout { get; } public string Now { get => _now; set => this.RaiseAndSetIfChanged(ref _now, value); } public User Who { get => _who; set => this.RaiseAndSetIfChanged(ref _who, value); } public bool Logged { get => _logged; set => this.RaiseAndSetIfChanged(ref _logged, value); } public bool Locked { get => _locked; set => this.RaiseAndSetIfChanged(ref _locked, value); } /// /// 处理登出页面 /// private void ToLogoutCmd() { _holder.ClearSession(); } private void StartClock() { var timer = new Timer(1000); timer.Elapsed += (sender, args) => { Dispatcher.UIThread.InvokeAsync(() => { Now = GetNowTime(); }); }; timer.AutoReset = true; timer.Enabled = true; } private static string GetNowTime() { return DateTime.Now.ToString("yyyy年M月d日 dddd HH:mm:ss"); } /// /// 监听远程锁机和解锁指令 /// /// /// [EventAction(EventType.LockEvent)] public void ListeningLocked(EventType type, bool locked) { Locked = locked; if (locked) { Log.Warning("已远程锁机"); } else { Log.Information("已远程解锁"); } } }