using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Nirvana.Common;
using Nirvana.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.NApi.DBServices
{
    /// <summary>
    /// 接口权限管理
    /// </summary>
    public partial class BaseApp : Repository<YB_Account>
    {
        public static int ExpiresMin = 60 * 24 * 7;//60*24*1 登录过期时间,单位为分钟
        public static WebApiOperaModel authInfo = null;
        public static string secureKey = Configs.GetString("SecureKey");
        public string CDNURL = Configs.GetString("CDNURL");//CDN地址
        public string APICDNURL = Configs.GetString("APICDNURL");//API图片CDN地址
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string Token(WebApiOperaModel model)
        {
            //生成token,SecureKey是用于加密token的key
            byte[] key = Encoding.Default.GetBytes(secureKey);
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            model.expiretime = DateTime.Now.AddMinutes(ExpiresMin);
            model.gid = Guid.NewGuid().ToString("N");
            //保存gid到redis
            //RedisHelpers.Insert($"sc_{model.userid}", model.gid);
            var token = encoder.Encode(model, key);
            return token;
        }


        /// <summary>
        /// token解密
        /// </summary>
        /// <param name="token"></param>
        /// <param name="ip">接口访问ip</param>
        /// <returns></returns>
        public static bool DecodeToken(string token, string ip)
        {
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            IJsonSerializer serializer = new JsonNetSerializer();
            var provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
            var tokens = decoder.Decode(token, secureKey, verify: true);

            if (string.IsNullOrEmpty(tokens))
            {
                return false;
            }
            var info = tokens.ToObject<WebApiOperaModel>();
            //检查时间是否已经过期
            if (DateTime.Now > info.expiretime)
            {
                return false;
            }
            //检查用户ID是否存在
            if (info.UserId <= 0)
            {
                return false;
            }
            //if (RedisHelpers.stringGet($"sc_{ info.userid}") != info.gid)
            //{
            //    return false;
            //}
            //检查访问的ip是否为token里的ip
            //if (ip != info.loginip)
            //{
            //    return false;
            //}
            info.expiretime = DateTime.Now.AddMinutes(ExpiresMin);
            authInfo = info;
            return true;

        }
    }
}
