using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Waste.Application;

namespace Waste.Web.Core
{
    public class JwtHandler : AppAuthorizeHandler
    {
        /// <summary>
        /// 请求管道
        /// </summary>
        /// <param name="context"></param>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 此处已经自动验证 Jwt token的有效性了，无需手动验证
            // 检查权限，如果方法时异步的就不用 Task.FromResult 包裹，直接使用 async/await 即可
            var ischecked = CheckAuthorzie(httpContext);
            // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false
            return Task.FromResult(ischecked);
        }

        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private static bool CheckAuthorzie(DefaultHttpContext httpContext)
        {
            // 获取权限特性
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) return true;
            return App.GetService<IAuthorizationManager>().CheckSecurity(securityDefineAttribute.ResourceId);
        }
        /// <summary>
        /// 自定义授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task HandleAsync(AuthorizationHandlerContext context)
        {
            //自动刷新token
            if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext()))
            {
                await AuthorizeHandleAsync(context);
            }
            else
            {
                context.Fail();
            }
            //// 常规授权（可以判断不是第三方）
            //var isAuthenticated = context.User.Identity.IsAuthenticated;

            //// 第三方授权自定义
            //if (是第三方)
            //{
            //    foreach (var requirement in pendingRequirements)
            //    {
            //        // 授权成功
            //        context.Succeed(requirement);
            //    }
            //}
            //// 授权失败
            //else context.Fail();
        }
    }
}