using EasyTemplate.Blazor.Web.Common;
using EasyTemplate.Tool;
using EasyTemplate.Tool.Util;
using Microsoft.JSInterop;

namespace EasyTemplate.Blazor.Web.Components.Pages.Account.Login;

//https://www.cnblogs.com/j4587698/p/16531294.html
public partial class Login
{
    protected override async void OnInitialized()
    {
        base.OnInitialized();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            Model.LoginType = "1";
            var localStorageHelper = new LocalStorage(JSRuntime);
            var auto = await localStorageHelper.GetLocalStorage(LocalStorage.AutoLogin);
            Model.AutoLogin = auto == "True";
            if (Model.AutoLogin)
            {
                var user = await localStorageHelper.GetLocalStorage(LocalStorage.UserInfo);
                if (!string.IsNullOrWhiteSpace(user))
                {
                    var suser = Crypto.AESDecrypt(user).ToEntity<SystemUser>();
                    var match = User.AsQueryable()
                        .Where(x => x.Account == suser.Account && x.Password == suser.Password)
                        .First();

                    if (match is not null)
                        ExecuteLogin(suser, true);
                }
            }
        }
    }


    private async Task HandleSubmit()
    {
        LoginLoading = true;

        try
        {
            SystemUser user = null;
            if (Model.LoginType == "1")
            {
                if (string.IsNullOrWhiteSpace(Model.Account) || string.IsNullOrWhiteSpace(Model.Password))
                {
                    Message.Error("账号或密码错误");
                    return;
                }

                user = User.AsQueryable()
                    .Where(x => x.Account == Model.Account && x.Password == Crypto.MD5Encrypt(Model.Password))
                    .First();
            }
            else
            {
                if (string.IsNullOrWhiteSpace(Model.Mobile) || string.IsNullOrWhiteSpace(Model.VerifyCode))
                {
                    Message.Error("手机号或验证码错误");
                    return;
                }

                user = User.AsQueryable()
                    .Where(x => x.Mobile == Model.Mobile)
                    .First();
            }

            if (user == null)
            {
                Message.Error("账号或密码错误");
                return;
            }

            var localStorageHelper = new LocalStorage(JSRuntime);
            if (Model.AutoLogin)
            {
                await localStorageHelper.SetLocalStorage(LocalStorage.AutoLogin, Model.AutoLogin.ToString());//
            }
            await localStorageHelper.SetLocalStorage(LocalStorage.UserInfo, Crypto.AESEncrypt(new { user.Id, user.Account, user.Password, Expired = DateTime.Now.AddDays(Global.Expired) }.ToJson()));

            ExecuteLogin(user);
        }
        catch (Exception ex)
        {
            Message.Error(ex.ToString());
        }
        finally
        {
            LoginLoading = false;
        }
    }

    public async Task ExecuteLogin(SystemUser user, bool auto = false)
    {
        var host = Accessor.GetHost();
        Global.CurrentUser = User.AsQueryable().Where(x => x.Account == user.Account && x.Password == user.Password).First();
        if (auto)
        {
            LogLogin.Insert(new SystemLogLogin() { Info = $"用户【{Global.CurrentUser.Account}】通过自动登录功能登录账号", UserId = Global.CurrentUser.Id, IpAddress= host, CreateTime = DateTime.Now });
        }
        else
        {
            LogLogin.Insert(new SystemLogLogin() { Info = $"用户【{Global.CurrentUser.Account}】登录账号", UserId = Global.CurrentUser.Id, IpAddress = host, CreateTime = DateTime.Now });
        }

        //AuthStateProvider.SignIn(Global.CurrentUser);

        NavigationManager.NavigateTo("/");
    }

    /// <summary>
    /// 发送短信验证码
    /// </summary>
    private async Task SendSM()
    {
        Loading = true;
        if (!string.IsNullOrWhiteSpace(Model?.Mobile))
        {
            await Task.Delay(8000);
        }
        else
        {
            MessageService.Error("请输入手机号");
        }
        Loading = false;
    }

    /// <summary>
    /// 
    /// </summary>
    private readonly LoginInput Model = new();
    /// <summary>
    /// 
    /// </summary>
    [Inject] public NavigationManager NavigationManager { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] public MessageService Message { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private SqlSugarRepository<SystemUser> User { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private SqlSugarRepository<SystemLogLogin> LogLogin { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private CustomAuthenticationStateProvider AuthStateProvider { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private IHttpContextAccessor Accessor { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private IJSRuntime JSRuntime { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private IMessageService MessageService { get; set; }
    /// <summary>
    /// 
    /// </summary>
    private bool Loading;
    /// <summary>
    /// 
    /// </summary>
    private bool LoginLoading;
}