using DFS.Core.Mvc.Jwt.Model;
using DFS.Infrastructure.Redis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Security.Claims;

namespace DFS.Core.Mvc.Jwt.Impl
{
    public class AuthService : IAuth
    {

        private static UnauthorizedObjectResult _SysUnauthorizedResult = new UnauthorizedObjectResult("未授权的请求")
        { StatusCode = 401, Value = "401 未授权的请求" };

        private ITokenManager _tokenManager;
        private readonly string _JwtTokenKey = "yuexiuhui!@#85632sdaxcdfeasdasdasdasd";

        /// <summary>
        /// 授权redis 库 数据库为3
        /// </summary>
        //public static CSRedisClient csRedisClient = CoreRedisHelper.GetRedisHelper("AuthRedis");

        /// <summary>
        /// 授权
        /// </summary>
        private IHttpContextAccessor _httpContextAccessor;

        public AuthService(IHttpContextAccessor contextAccessor, ITokenManager tokenManager)
        {
            _httpContextAccessor = contextAccessor;
            _tokenManager = tokenManager;
        }


        public bool AuthToken(ActionExecutingContext context)
        {
            var token = GetToken();
            if (string.IsNullOrEmpty(token))
            {
                context.Result = _SysUnauthorizedResult;

                return false;
            }

            //验证token 是否过期。
            try
            {
                var adminToken = _tokenManager.DecodeToken<TokenModel>(token, _JwtTokenKey);
                if (adminToken.ExpireTime < DateTimeOffset.Now || !BuildAuthUser(_httpContextAccessor,adminToken))
                {
                    context.Result = _SysUnauthorizedResult;
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

        ///// <summary>
        ///// 获取客户端信息
        ///// </summary>
        ///// <param name="context"></param>
        ///// <returns></returns>
        //public bool AuthClient(ActionExecutingContext context)
        //{
        //    if (context.ActionDescriptor.EndpointMetadata.Any(p => p.GetType().Name == "AllowAnonymousAttribute"))
        //    {
        //        return true;
        //    }
        //    var client = GetClientInfo();
        //    if (client == null || !client.AuthTimeSpan())
        //    {
        //        context.Result = _SysUnauthorizedResult;
        //        return false;
        //    }

        //    BuildAuthClient(_httpContextAccessor, client);
        //    return true;
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetToken()
        {
            var token = string.Empty;
            StringValues authorizationValue="";

            if (_httpContextAccessor.HttpContext.Request.Headers.Any(o => o.Key.ToLower() == "authorization"))
            {
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("Authorization", out authorizationValue);
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("authorization", out authorizationValue);
            }

            if (string.IsNullOrWhiteSpace(authorizationValue.ToString()))
            {
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("authorization", out authorizationValue);
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("Authorization", out authorizationValue);
            }

            if (!string.IsNullOrWhiteSpace(authorizationValue.ToString()))
            {
                var splitCount = authorizationValue.ToString().Split(' ');
                if (splitCount != null && splitCount.Count() > 1)
                {
                    token = splitCount[1];
                }
            }

            return token;
        }

        /// <summary>
        /// 获取授权ClientId
        /// </summary>
        /// <returns></returns>
        private OpenClient GetClientInfo()
        {
            StringValues appid="";

            if (_httpContextAccessor.HttpContext.Request.Headers.Any(o => o.Key.ToLower() == "authorization"))
            {
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("AppId", out appid);
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("appid", out appid);
            }

            if (appid.ToString().IsNullOrWhiteSpace())
            {
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("AppId", out appid);
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("appid", out appid);
            }

            if (appid.ToString().IsNullOrWhiteSpace())
            {
                return null;
            }
            StringValues timespan="";
            if (_httpContextAccessor.HttpContext.Request.Headers.Any(o => o.Key.ToLower() == "timespan"))
            {
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("timespan", out timespan);
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("TimeSpan", out timespan);
            }

            if (string.IsNullOrWhiteSpace(timespan.ToString()))
            {
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("timespan", out timespan);
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("TimeSpan", out timespan);
            }
            if (timespan.ToString().IsNullOrWhiteSpace())
            {
                return null;
            }

            StringValues sign="";
            if (_httpContextAccessor.HttpContext.Request.Headers.Any(o => o.Key.ToLower() == "sign"))
            {
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("sign", out sign);
                _httpContextAccessor.HttpContext.Request.Headers.TryGetValue("Sign", out sign);
            }
            if (string.IsNullOrWhiteSpace(sign.ToString()))
            {
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("Sign", out sign);
                _httpContextAccessor.HttpContext.Request.Query.TryGetValue("sign", out sign);
            }
            if (timespan.ToString().IsNullOrWhiteSpace())
            {
                return null;
            }
            return new OpenClient(appid.ToString(), sign.ToString(), timespan.ToString());
        }

        /// <summary>
        /// 向http context 生成授权当前用户的信息
        /// </summary>
        /// <param name="tokenValue"></param>
        private bool BuildAuthData(string tokenValue)
        {
            if (tokenValue.IsNullOrWhiteSpace())
            {
                return false;
            }
            var authClient = CoreRedisHelper.GetRedisHelper("AuthJwtRedis");
            if (authClient == null)
            {
                throw new Exception($"授权配置redis不能为空,名称节点:AuthJwtRedis");
            }

            var redisValue = authClient.Get(tokenValue);
            if (redisValue.IsNullOrWhiteSpace())
            {
                return false;
            }

            //var aesDecryptStr = redisValue.AesDecryptFormBase64(key);
            //var sortedDic= JsonConvert.DeserializeObject<SortedDictionary<string, string>>(aesDecryptStr);
            string decryptString = "";
            //EncryptUtil.AesDecrypt(redisValue, JwtConfig.RedisKey);
            //var sortedDic = JsonConvert.DeserializeObject<SortedDictionary<string, string>>(decryptString);

            ////var sortedDicS = DoUitl.GetEnity<SortedDictionary<string, string>>(decryptString);
            //var userInfo = new UserInfo();
          
            //var userClient = sortedDic.GetEntity<UserClient>();
            //if (userClient == null || userClient.expired_time.ToDateTime() < new DateTime())
            //{
            //    return false;
            //}
            //userInfo.UserClient = userClient;
            return BuildAuthUser(_httpContextAccessor, new TokenModel());
        }


        /// <summary>
        /// 生成授权用户信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        private bool BuildAuthUser(IHttpContextAccessor httpContext, TokenModel userInfo)
        {
            ClaimsPrincipal principal = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new[] {
                        new Claim(JwtConfig.TokenUser,JsonConvert.SerializeObject(userInfo), ClaimValueTypes.String,"DFS.com"),
                        new Claim(JwtConfig.SystemType, userInfo.SystemType,ClaimValueTypes.String,"DFS.com"),
                        new Claim(JwtConfig.Channel, userInfo.Channel_type,ClaimValueTypes.String,"DFS.com"),
                    },
                    "DFS"
                ));
            httpContext.HttpContext.User = principal;
            return true;
        }

        /// <summary>
        /// 生成授权客户端
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        private bool BuildAuthClient(IHttpContextAccessor httpContext, OpenClient app)
        {
            ClaimsPrincipal principal = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new[] {
                        new Claim("OpenClient",JsonConvert.SerializeObject(app), ClaimValueTypes.String,"DFS.com"),
                    },
                    "DFS.TK"
                ));
            httpContext.HttpContext.User = principal;
            return true;
        }

        /// <summary>
        /// 验证客户端授权，从ClientId+密钥方式进行获取
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AuthClient(ActionExecutingContext context)
        {
            throw new NotImplementedException();
        }
    }
}
