using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace IRaCIS.Core.Application.Filter;




public class LimitUserRequestAuthorization : IAsyncAuthorizationFilter
{


    private readonly IEasyCachingProvider _provider;

    private readonly IUserInfo _userInfo;

    private readonly IOptionsMonitor<ServiceVerifyConfigOption> _verifyConfig;

    public LimitUserRequestAuthorization(IEasyCachingProvider provider, IUserInfo userInfo, IOptionsMonitor<ServiceVerifyConfigOption> verifyConfig)
    {
        _provider = provider;
        _userInfo = userInfo;
        _verifyConfig = verifyConfig;
    }


    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (_verifyConfig.CurrentValue.OpenLoginLimit)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is IAllowAnonymous))
            {

                return;
                //匿名访问的不处理
            }
            else
            {
                //1、用户登陆的时候，设置缓存



                //没有从请求中取到token
                if (string.IsNullOrWhiteSpace(_userInfo.UserToken))
                {
                    context.HttpContext.Response.ContentType = "application/json";
                    context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
                    context.Result = new JsonResult(ResponseOutput.NotOk("当前请求未从Header/Url取到用户Token"));

                    //await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk("当前请求未从Header/Url取到用户Token,请联系开发者")));
                }

                //2、在这里取缓存  进行比较  看是否有其他人进行了登陆，如果其他人登陆了，就把之前用户挤掉
                var cacheUserToken = (await _provider.GetAsync<string>(_userInfo.Id.ToString())).Value;

                //缓存中没有取到Token
                if (string.IsNullOrWhiteSpace(cacheUserToken))
                {
                    //设置当前用户最新Token
                    await _provider.SetAsync(_userInfo.Id.ToString(), _userInfo.UserToken, TimeSpan.FromDays(7));

                    cacheUserToken = _userInfo.UserToken;

                }
                //是同一个人  
                else if (cacheUserToken == _userInfo.UserToken)
                {

                }

                else
                {

                    context.HttpContext.Response.ContentType = "application/json";
                    context.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
                    context.Result = new JsonResult(ResponseOutput.NotOk("您的账户在其他地方已登陆，您被迫下线。", ApiResponseCodeEnum.LoginInOtherPlace));
                    //await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk("您的账户在其他地方已登陆，您被迫下线。", ApiResponseCodeEnum.LoginInOtherPlace)));

                }



            }
        }


    }
}














//public class UserTypeRequirement : IAuthorizationRequirement
//{
//}

//public class UserTypeHandler : AuthorizationHandler<UserTypeRequirement>
//{

//    private IUserInfo _userInfo;

//    public UserTypeHandler(IUserInfo userInfo)
//    {
//        _userInfo = userInfo;
//    }


//    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserTypeRequirement requirement)
//    {

//        //if (context.User.Claims.Count() == 0)
//        //{
//        //    return Task.CompletedTask;
//        //}

//        //string userId = context.User.Claims.First(c => c.Type == "Userid").Value;
//        //string qq = context.User.Claims.First(c => c.Type == "QQ").Value;

//        //if (_UserService.Validata(userId, qq))
//        //{
//        //    context.Succeed(requirement); //验证通过了
//        //}
//        ////在这里就可以做验证

//        return Task.CompletedTask;
//    }
//}

