Files
FATrace/FATrace.WPLApp/ViewModels/LoginViewModel.cs
2025-11-26 16:46:48 +08:00

97 lines
3.2 KiB
C#

using FATrace.Model;
using FATrace.WPLApp.Core;
using FATrace.WPLApp.Services;
using FreeSql;
using Prism.Commands;
using Prism.Regions;
using System;
using System.Security;
using System.Threading.Tasks;
using System.Windows;
namespace FATrace.WPLApp.ViewModels
{
public class LoginViewModel : NavigationViewModel
{
private readonly IFreeSql _fsql;
private readonly ILogService _log;
private readonly SysRunService _sys;
private readonly IRegionManager _regionManager;
public LoginViewModel(IFreeSql fsql, ILogService log, SysRunService sysRunService, IRegionManager regionManager)
{
_fsql = fsql;
_log = log;
_sys = sysRunService;
_regionManager = regionManager;
LoginCommand = new DelegateCommand(async () => await DoLoginAsync(), () => !IsBusy)
.ObservesProperty(() => IsBusy);
}
private string _userName;
public string UserName { get => _userName; set { _userName = value; RaisePropertyChanged(); } }
private string _password;
public string Password { get => _password; set { _password = value; RaisePropertyChanged(); } }
private bool _isBusy;
public bool IsBusy { get => _isBusy; set { _isBusy = value; RaisePropertyChanged(); } }
public DelegateCommand LoginCommand { get; }
private async Task DoLoginAsync()
{
if (IsBusy) return;
try
{
if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password))
{
MessageBox.Show("请输入用户名和密码", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
IsBusy = true;
var user = await Task.Run(() =>
{
return _fsql.Select<TbUser>()
.Where(a => a.UserName == UserName)
.First();
});
if (user == null)
{
MessageBox.Show("用户不存在", "登录失败", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
// 明文密码对比(与现有模型字段一致)。如后续改为哈希,可在此替换校验逻辑。
if (!string.Equals(user.Password, Password))
{
MessageBox.Show("密码错误", "登录失败", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
_sys.CurUser = user.UserName;
_log.Info($"用户登录成功: {user.UserName}");
UserName="";
Password="";
try
{
_regionManager.Regions["ContentRegion"].RequestNavigate("DashBoardView");
}
catch { }
}
catch (Exception ex)
{
_log.Error($"登录异常: {ex}");
MessageBox.Show($"登录异常: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
IsBusy = false;
}
}
}
}