using System; using System.Collections.Generic; using System.Reactive; using System.Windows.Forms; using DispenserCommon.Aop; using DispenserCommon.Ioc; using DispenserCommon.Utils; using DispenserCore.Context; using DispenserCore.Model.DTO; using DispenserCore.Service; using ReactiveUI; using LoginErrorWindow = DispenserUI.Views.Windows.LoginErrorWindow; namespace DispenserUI.ViewModels.Login; [Component, GlobalTry] public class LoginVM : DynamicViewModel { private readonly Dictionary _errorTimes = new(); private readonly GlobalSessionHolder _sessionHolder = ServiceLocator.GetService(); // 用来记录登录错误告警情况,10分钟内异常超过3次则添加到小黑屋里面去 private readonly SlidingWindow _slidingWindow = new(10 * 60 * 1000); private readonly UserService _userService = ServiceLocator.GetService(); private bool _isCapsLockIndicatorVisible; //订阅IsCapsLockOn、IsPwdTextBoxFocus private bool _isCapsLockOn; private bool _isPwdTextBoxFocus; private string _password; private bool _showError; private string _userName; public LoginVM() { Visible = false; CapsLockUpCommand = ReactiveCommand.Create(CapsLockUp); PwdTextBoxGotFocusCommand = ReactiveCommand.Create(PwdTextBoxGotFocus); PwdTextBoxLostFocusCommand = ReactiveCommand.Create(PwdTextBoxLostFocus); ToLogin = ReactiveCommand.Create(Login); } public string UserName { get => _userName; set => this.RaiseAndSetIfChanged(ref _userName, value); } public string Password { get => _password; set => this.RaiseAndSetIfChanged(ref _password, value); } public bool IsCapsLockIndicatorVisible { get => _isCapsLockIndicatorVisible; set => this.RaiseAndSetIfChanged(ref _isCapsLockIndicatorVisible, value); } public bool ShowError { get => _showError; set => this.RaiseAndSetIfChanged(ref _showError, value); } public ReactiveCommand CapsLockUpCommand { get; } public ReactiveCommand PwdTextBoxGotFocusCommand { get; } public ReactiveCommand PwdTextBoxLostFocusCommand { get; } public ReactiveCommand ToLogin { get; } private void CapsLockUp() { _isCapsLockOn = Control.IsKeyLocked(Keys.CapsLock); UpdateCapsLockIndicator(); } private void PwdTextBoxGotFocus() { _isPwdTextBoxFocus = true; ShowError = false; UpdateCapsLockIndicator(); } private void PwdTextBoxLostFocus() { _isPwdTextBoxFocus = false; ShowError = false; UpdateCapsLockIndicator(); } private void UpdateCapsLockIndicator() { IsCapsLockIndicatorVisible = _isCapsLockOn && _isPwdTextBoxFocus; } /// /// 登录 /// [Operation("用户登录")] private void Login() { try { // 如果登录异常次数超过3次,则提示用户 if (_slidingWindow.Contains(UserName)) { WindowUtil.ShowDialog(new LoginErrorWindow()); // 清空当前的错误统计 _errorTimes.Remove(UserName); return; } ShowError = false; // 进行登录验证 var user = _userService.Login(UserName, Password); // 将登录结果记录下来 _sessionHolder.SetSession(new Session(user)); } catch (Exception e) { ShowError = true; _errorTimes.TryGetValue(UserName, out var times); times += 1; if (times >= 3) { // 添加到小黑屋,10分钟内不能进行登录 _slidingWindow.AllowValue(UserName); return; } _errorTimes[UserName] = times; } } }