using Mall.CacheKey;
using Mall.CacheManager.Base;
using Mall.CacheManager.DataStatistic;
using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Extend.User;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mall.CacheManager.User
{
    /// <summary>
    /// redis缓存（只适用于数据统计）
    /// </summary>
    public class UserReidsCache
    {
        static readonly RedisHelper redis = new RedisHelper(DataConstant.REDIS_DB2);

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="model"></param>
        public static void UserInfoSet(string cacheKey, UserInfo model, int JwtExpirTime)
        {
            try
            {
                TimeSpan ts = GetExpirTime(JwtExpirTime);
                redis.StringSet<UserInfo>(cacheKey, model, ts);
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "UserInfoSet缓存设置失败");
            }
        }

        /// <summary>
        /// 获取缓存时长
        /// </summary>
        /// <param name="JwtExpirTime"></param>
        /// <returns></returns>
        private static TimeSpan GetExpirTime(int JwtExpirTime)
        {
            DateTime dt = DateTime.Now;
            DateTime dt2 = DateTime.Now;
            TimeSpan ts = dt.AddSeconds(JwtExpirTime) - dt2;
            return ts;
        }

        /// <summary>
        /// 判断key是否存在
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public static bool Exists(string cacheKey)
        {
            return redis.KeyExists(cacheKey);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="Data"></param>
        /// <param name="JwtExpirTime"></param>
        public static void Set(string cacheKey, object Data, int JwtExpirTime)
        {
            try
            {
                TimeSpan ts = GetExpirTime(JwtExpirTime);
                redis.StringSet(cacheKey, Data, ts);
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// 商户信息仓储层对象
        /// </summary>
        private static readonly Mall.Repository.User.RB_TenantRepository tenantRepository = new Repository.User.RB_TenantRepository();

        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <param name="TenantId">商户Id</param>
        /// <returns></returns>
        public static UserInfo GetUserLoginInfo(object TenantId)
        {
            UserInfo userInfo = null;
            if (TenantId != null)
            {
                string cacheKey = UserModuleCacheKeyConfig.Mall_Login_Info + TenantId.ToString();
                try
                {
                    userInfo = redis.StringGet<UserInfo>(cacheKey);
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "GetUserLoginInfo");
                }
                if (userInfo == null)
                {
                    Int32.TryParse(TenantId.ToString(), out int NewTenantId);
                    if (NewTenantId > 0)
                    {
                        string token = "";
                        var extModel = tenantRepository.GetEntity<RB_Tenant_Extend>(NewTenantId);
                        if (extModel != null)
                        {
                            userInfo = new UserInfo
                            {
                                TenantId = extModel.TenantId,
                                Account = extModel.Account,
                                Name = extModel.Name,
                                MobilePhone = extModel.MobilePhone,
                                WeChatNum = extModel.WeChatNum,
                                IsEffective = extModel.IsEffective,
                                AccountValidate = extModel.AccountValidate,
                                CreateMiniPrograme = extModel.CreateMiniPrograme,
                                //MallName = extModel.MallName,
                                AccountStatus = extModel.AccountStatus,
                                Token = token,
                                SecretKey = "",
                            };
                            UserInfoSet(UserModuleCacheKeyConfig.Mall_Login_Info + TenantId, userInfo, Config.JwtExpirTime);
                        }
                    }
                }
            }
            else
            {
                userInfo = new UserInfo();
            }

            return userInfo;
        }

        /// <summary>
        /// 设置小程序用户缓存
        /// </summary>
        /// <param name="model"></param>
        public static void AppletUserInfoSet(string cacheKey, AppletUserInfo model, int JwtExpirTime)
        {
            try
            {
                TimeSpan ts = GetExpirTime(JwtExpirTime);
                redis.StringSet<AppletUserInfo>(cacheKey, model, ts);
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "UserInfoSet缓存设置失败");
            }
        }

        /// <summary>
        /// 用户
        /// </summary>

        private static readonly Repository.User.RB_Member_UserRepository member_UserRepository = new Repository.User.RB_Member_UserRepository();

        /// <summary>
        /// 获取小程序用户登录信息
        /// </summary>
        /// <param name="UserId">用户Id</param>
        /// <returns></returns>
        public static AppletUserInfo GetAppletUserLoginInfo(object UserId)
        {
            if (UserId != null)
            {
                string cacheKey = UserModuleCacheKeyConfig.Applet_Login_Info + UserId.ToString();
                AppletUserInfo userInfo = null;
                try
                {
                    userInfo = redis.StringGet<AppletUserInfo>(cacheKey);
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "GetAppletUserLoginInfo");
                }
                if (userInfo == null)
                {
                    Int32.TryParse(UserId.ToString(), out int NewUserId);
                    if (NewUserId > 0)
                    {
                        string token = "";
                        var umodel = member_UserRepository.GetEntity<RB_Member_User_Extend>(NewUserId);
                        if (umodel != null)
                        {
                            userInfo = new AppletUserInfo
                            {
                                MallBaseId = umodel.MallBaseId,
                                MallName = "",
                                Mobile = umodel.Moblie,
                                UserId = NewUserId,
                                TenantId = umodel.TenantId,
                                Name = umodel.Name,
                                OpenId = umodel.OpenId,
                                Photo = umodel.Photo,
                                Source = umodel.Source,
                                SecretKey = umodel.SecretKey,
                                SuperiorId = umodel.SuperiorId ?? 0,
                                Token = token
                            };
                            AppletUserInfoSet(UserModuleCacheKeyConfig.Applet_Login_Info + UserId, userInfo, Config.JwtExpirTime);
                        }
                    }
                }
                return userInfo;
            }
            return null;
        }
    }
}
