using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.Framework.Login;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.IService;
using ASHermed.SinoInterface.Code;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Exception;
using ASHermed.SinoInterface.IFramework.SingleSignOn;
using ASHermed.SinoInterface.Tools;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using PoJun.Util;
using PoJun.Util.Maps;
using Renci.SshNet.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ASHermed.SinoInterface.Api.Service
{
    /// <summary>
	/// Token信息
	/// </summary>
	public class TokenService : BaseService, ITokenService
    {
        IPubUserInfoService _pubUserInfoService;
        IPubUserInfoRepository _pubUserInfoRepository;
        RedisHelperClient _redisHelper;
        IJWTService _jWTService;
        #region 初始化
        /// <summary>
        /// 
        /// </summary>
        public TokenService(IPubUserInfoService pubUserInfoService, IPubUserInfoRepository pubUserInfoRepository, RedisHelperClient redisHelper, IJWTService jWTService)
        {
            _pubUserInfoService = pubUserInfoService;
            _pubUserInfoRepository = pubUserInfoRepository;
            _redisHelper = redisHelper;
            _jWTService = jWTService;
        }
        #endregion

        public Pub_User_Info CheckToken(string token)
        {
            try
            {
                if (!string.IsNullOrEmpty(token))
                {
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    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, algorithm);
                    token = token.Replace("Bearer ", "");
                    var userInfo = decoder.DecodeToObject<Dictionary<string, object>>(token, "suvalue2019", verify: true);
                    var key = userInfo.FirstOrDefault().Value + "";
                    if (userInfo != null && userInfo.Count > 0)
                    {
                        if (_redisHelper.KeyExistsAsync(key).Result)
                        {
                            _redisHelper.KeyExpire(key, TimeSpan.FromSeconds(7 * 24 * 60 * 60));//30 * 24 * 
                        }
                        else
                        {
                            throw new BaseException("用户信息过期,请重新登录", DetailedStatusCode.Fail);
                        }
                        var userId = key.Replace("user_", "").ToInt();
                        var pubUserInfo = _pubUserInfoRepository.initLinq().Where(p => p.ID == userId).Single();
                        
                        return pubUserInfo;
                    }
                    else
                    {
                        throw new BaseException("token解密失败", DetailedStatusCode.Fail);
                    }
                }
                return null;
            }
            catch (System.Exception e)
            {
                throw new BaseException(e.Message, DetailedStatusCode.Fail);
            }

        }

        public int UpdateUserVersion(int id, string vers)
        {
            return _pubUserInfoRepository.UpdateUserVersion(id, vers);
        }


        public Pub_Pat_Info CheckTokenForPat(string token)
        {
            try
            {
                if (!string.IsNullOrEmpty(token))
                {
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    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, algorithm);
                    token = token.Replace("Bearer ", "");
                    var userInfo = decoder.DecodeToObject<Dictionary<string, object>>(token, "suvalue2019", verify: true);
                    var key = userInfo.FirstOrDefault().Value + "";
                    if (userInfo != null && userInfo.Count > 0)
                    {
                        if (_redisHelper.KeyExistsAsync(key).Result)
                        {
                            _redisHelper.KeyExpire(key, TimeSpan.FromSeconds(7 * 24 * 60 * 60));//30 * 24 * 
                        }
                        else
                        {
                            throw new BaseException("用户信息过期,请重新登录", DetailedStatusCode.Fail);
                        }
                        var userId = key.Replace("pat_", "").ToInt();
                        var pubpatInfo = _pubUserInfoService.SelectById(userId);
                        return pubpatInfo;
                    }
                    else
                    {
                        throw new BaseException("token解密失败", DetailedStatusCode.Fail);
                    }
                }
                return null;
            }
            catch (System.Exception e)
            {
                throw new BaseException(e.Message, DetailedStatusCode.Fail);
            }

        }

        public string SetReport(int userId)
        {
            if (userId == 0)
            {
                return null;
            }
            try
            {
                //获取jedis对象
                string tokenStr = _jWTService.JavaSign(userId + "");
                _redisHelper.Set(userId + "", tokenStr, TimeSpan.FromDays(1));
                return tokenStr;

            }
            catch (System.Exception e)
            {
                return null;
            }

        }


    }
}
