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

namespace detect.gui.VWMS;

public class LoginControlModel : ViewModelBase<LoginControlModel>
{
    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 LoginControlModel()
    {
        Username = "admin";
        Password = "winner!";

        LoginCommand = ReactiveCommand.Create(Login);
    }

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

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

        if (Message is not { NotificationType: NotificationType.Error })
        {
            Locator.Current.GetService<MainWindowModel>()!.IsDetectTaskView = true;
            Locator.Current.GetService<MainWindowModel>()!.SetAddress(1);
        }
    }
}