using Azure.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.JsonWebTokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace CloudBuilder.Core.Policy
{
    public class ClaimPolicy
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        public const string CLAINM_USERID = "UserId";

        /// <summary>
        /// 账号
        /// </summary>
        public const string CLAINM_ACCOUNT = "Account";

        /// <summary>
        /// 名称
        /// </summary>
        public const string CLAINM_NAME = "Name";

        /// <summary>
        /// 语言
        /// </summary>
        public const string CLAINM_LOCALE = "zh-cn";

        public const string ROLE = "Role";

        public const string BEARER = "Bearer";

        public const string HEADER_LOCALE = "locale";
        /// <summary>
        /// 是否超级管理
        /// </summary>
        public const string CLAINM_SUPERADMIN = "SuperAdmin";

        /// <summary>
        /// 租户Id
        /// </summary>
        public const string TENANT_ID = "TenantId";

        public static string GetClaimValue(IHttpContextAccessor httpContextAccessor, string claimType)
        {
            string value = string.Empty;
            string token = GetJwtBearerToken(httpContextAccessor.HttpContext);
            return GetClaimValue(token, claimType);
        }

        public static string GetHeaderKeyValue(IHttpContextAccessor httpContextAccessor, string headerKey)
        {
            if (httpContextAccessor.HttpContext.Request.Headers.Keys.Contains(headerKey))
            {
                return httpContextAccessor.HttpContext.Request.Headers[headerKey].ToString();
            }
            return string.Empty;
        }

        public static string GetClaimValue(string token, string claimType)
        {
            string value = string.Empty;
            if (!string.IsNullOrEmpty(token) && token.Length > 30)
            {
                JsonWebToken tk = new JsonWebTokenHandler().ReadJsonWebToken(token);

                if (tk == null) { return null; }

                Claim claim = tk.GetClaim(claimType);
                if (claim != null)
                    value = claim.Value;
            }

            return value;
        }

        public static string GetJwtBearerToken(HttpContext httpContext, string headerKey = "Authorization", string tokenPrefix = "Bearer ")
        {
            // 判断请求报文头中是否有 "Authorization" 报文头
            var bearerToken = httpContext.Request.Headers[headerKey].ToString();
            if (string.IsNullOrWhiteSpace(bearerToken)) return default;

            var prefixLenght = tokenPrefix.Length;
            return bearerToken.StartsWith(tokenPrefix, true, null) && bearerToken.Length > prefixLenght ? bearerToken[prefixLenght..] : default;
        }
    }
}
