using JWT;
using JWT.Serializers;
using Mall.Common.API;
using Mall.Common.Plugin;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mall.WebApi.Helper
{
    /// <summary>
    /// Token帮助类
    /// </summary>
    public class TokenHelper
    {

        /// <summary>
        /// 生成Token
        /// </summary>
        /// <returns></returns>
        public static string CreateToken()
        {
            return "";
        }

        /// <summary>
        /// 解析Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static TokenUserInfo ParsingToken(string token)
        {
            TokenUserInfo tokenUser = new TokenUserInfo();
            if (string.IsNullOrEmpty(token))
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                string secret = Common.Config.JwtSecretKey;
                var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串
                if (!string.IsNullOrEmpty(json))
                {
                    JObject jwtJson = JObject.Parse(json);
                    var mall_userInfo = JObject.Parse(jwtJson.GetStringValue("mall_userInfo"));
                    tokenUser.requestFrom = (Common.Enum.ApiRequestFromEnum)mall_userInfo.GetInt("requestFrom");
                    tokenUser.uid = mall_userInfo.GetStringValue("uid");
                }
            }
            return tokenUser;
        }
    }
}
