using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace HuiXin.Gateway.Ocelot
{
    public class JWTUtil
    {

        /// <summary>
        /// 创建token
        /// </summary>
        /// <returns></returns>
        public static string CreateJwtToken(IDictionary<string, object> payload, string secret, IDictionary<string, string> extraHeaders = null)
        {
            //IJwtEncoder encoder = new JwtEncoder(new HMACSHA256Algorithm(), new JsonNetSerializer(), new JwtBase64UrlEncoder());
            //var token = encoder.Encode(extraHeaders,payload, secret);
            //return token;

            Claim[] claims = new Claim[]
            {
                new Claim("Id", "aaa"),
                new Claim("Name", "bbb"),
                new Claim("Email", "ccc"),
            };

            var securityKey = new SymmetricSecurityKey(Convert.FromBase64String("GcTdqSZdpRxBtdtgwvDHBzS427VGTQzbM+JD1CBbUZY="));

            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);


            var header = new JwtHeader(signingCredentials);
            //header.Add("typ", "JWT"); // 默认情况下,typ通常是"JWT",但你可以明确设置它
            //header.Add("kid", "MyKey");
            //header.Add("key", "MyKey");
            //header.Add("keyid", "MyKey");

            // 设置JWT载荷(payload)
            var payload1 = new JwtPayload
            {
                    //{ "kid", "MyKey" },
                    //{ "key", "MyKey" },
                    //{ "keyid", "MyKey" },
                { "issuer",""},
                { "sub", "1234567890" },
                { "name", "测试用户" },
                { "role", new []{"test","admin" } },
                { "scope",new []{"all" } },
                { "iat",  ToUnixTime(DateTime.Now)},
                { "exp", ToUnixTime(DateTime.Now.AddDays(1)) }
            };

            // 创建JwtSecurityToken实例并结合header和payload
            var jwt = new JwtSecurityToken(header, payload1);
            return new JwtSecurityTokenHandler().WriteToken(jwt);
        }

        private static long ToUnixTime(DateTime dt)
        {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)(dt.ToUniversalTime() - epoch).TotalMilliseconds;
        }
    }
}