Dispenser/DispenserUI/ViewModels/MainVM.cs

130 lines
3.0 KiB
C#
Raw Permalink Normal View History

2024-08-16 07:20:09 +00:00
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;
/// <summary>
/// 主界面 UI view model
/// </summary>
[Component, GlobalTry]
public class MainVM : ViewModelBase
{
private readonly GlobalSessionHolder _holder = ServiceLocator.GetService<GlobalSessionHolder>();
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<Type>.Publish(EventType.PageChanged, typeof(LoginVM));
return;
}
Who = session.User;
Logged = true;
EventBus<Type>.Publish(EventType.PageChanged, typeof(ContainerViewModel));
};
if (!_holder.Logged())
{
// 如果没有登录,则跳转到登录页面
// EventBus<Type>.Publish(EventType.PageChanged, typeof(LoginVM));
}
}
/// <summary>
/// 去首页
/// </summary>
public ReactiveCommand<Unit, Unit> 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);
}
/// <summary>
/// 处理登出页面
/// </summary>
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");
}
/// <summary>
/// 监听远程锁机和解锁指令
/// </summary>
/// <param name="type"></param>
/// <param name="locked"></param>
[EventAction(EventType.LockEvent)]
public void ListeningLocked(EventType type, bool locked)
{
Locked = locked;
if (locked)
{
Log.Warning("已远程锁机");
}
else
{
Log.Information("已远程解锁");
}
}
}