using System.Reactive;
using System.Threading.Tasks;
using detect.gui.Api.Helpers;
using detect.gui.Commons;
using Avalonia.Controls.Notifications;
using detect.gui.Models;
using detect.gui.Models.Entities;
using ReactiveUI;

namespace detect.gui.ViewModels;

public class LoginViewModel : RoutableViewModelBase<UserModel>
{
    private long? _userId;
    public long? UserId
    {
        get => _userId;
        set => this.RaiseAndSetIfChanged(ref _userId, value);
    }

    private string? _username;
    public string? Username
    {
        get => _username;
        set => this.RaiseAndSetIfChanged(ref _username, value);
    }

    private string? _password;
    public string? Password
    {
        get => _password;
        set => this.RaiseAndSetIfChanged(ref _password, value);
    }

    private string? _realName;
    public string? RealName
    {
        get => _realName;
        set => this.RaiseAndSetIfChanged(ref _realName, value);
    }

    public LoginViewModel()
    {
        Username = "admin";
        Password = "winner!";

        LoginCommand = ReactiveCommand.Create(Login);
    }

    public ReactiveCommand<Unit, Unit> LoginCommand { get; }

    /// <summary>
    /// 登录
    /// </summary>
    public async void Login()
    {
        Message = null;
        
        IsLoading = true;
        
        await Task.Factory.StartNew(() =>
        {
        
            var data = UserHelper.Login(Username, Password);
            if (data?.Code != 0)
            {
                Message = new MessageItem(data?.Message, NotificationType.Error);
                return;
            }
            RootViewModel!.CurrentUser = data.Result?.Convert<UserEntity, UserModel>();
            Message = new MessageItem("欢迎," + data.Result?.RealName, NotificationType.Success);
        });
        
        IsLoading = false;

        if (Message is not { NotificationType: NotificationType.Error })
            HostScreen?.Router.Navigate.Execute(new HomeViewModel());
    }
}