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>
        private static readonly Repository.User.RB_Login_LogRepository login_LogRepository = new Repository.User.RB_Login_LogRepository();

        /// <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);
                try
                {
                    login_LogRepository.Insert(new Model.Entity.User.RB_Login_Log()
                    {
                        UserId = model.UserId,
                        LoginTime = DateTime.Now
                    });
                }
                catch(Exception ex2)
                {
                    Common.Plugin.LogHelper.Write(ex2, "UserInfoSet_SetSignBit缓存设置失败");
                }
            }
            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;
        }

        /// <summary>
        /// 获取小程序用户黑名单信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public static AppletUserInfo GetAppletUserBlacklistInfo(object UserId)
        {
            if (UserId != null)
            {
                string cacheKey = UserModuleCacheKeyConfig.Applet_Blacklist_Info + UserId.ToString();
                AppletUserInfo userInfo = null;
                try
                {
                    userInfo = redis.StringGet<AppletUserInfo>(cacheKey);
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "GetAppletUserBlacklistInfo");
                }
                if (userInfo == null)
                {
                    Int32.TryParse(UserId.ToString(), out int NewUserId);
                    if (NewUserId > 0)
                    {
                        var umodel = member_UserRepository.GetEntity<RB_Member_User_Extend>(NewUserId);
                        if (umodel != null)
                        {
                            userInfo = new AppletUserInfo
                            {
                                MallBaseId = umodel.MallBaseId,
                                UserId = NewUserId,
                                TenantId = umodel.TenantId,
                                Name = umodel.Name,
                                SuperiorId = umodel.SuperiorId ?? 0,                                
                                Blacklist = umodel.Blacklist
                            };
                            AppletUserInfoSet(UserModuleCacheKeyConfig.Applet_Blacklist_Info + UserId, userInfo, Config.JwtExpirTime);
                        }
                    }
                }
                return userInfo;
            }
            return null;
        }


        #region 不可开发票总金额

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




        /// <summary>
        /// 获取不可开发票总金额
        /// </summary>
        /// <param name="TenantId">商户Id</param>
        /// <returns></returns>
        public static TransactionPriceInfo GetTransactionPriceInfo(int MallBaseId)
        {
            TransactionPriceInfo transactionPriceInfo = null;
            if (MallBaseId > 0)
            {
                string cacheKey = UserModuleCacheKeyConfig.Transaction_Price_ + MallBaseId.ToString();
                try
                {
                    transactionPriceInfo = redis.StringGet<TransactionPriceInfo>(cacheKey);
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "GetTransactionPriceInfo");
                }
                //if (transactionPriceInfo == null)
                //{
                //    if (MallBaseId > 0 && TenantId > 0)
                //    {
                //        transactionPriceInfo = new TransactionPriceInfo
                //        {
                //            TenantId = (int)TenantId,
                //            MallBaseId = (int)MallBaseId,
                //            TotalPrice = TotalPrice
                //        };
                //        TransactionPriceSet(UserModuleCacheKeyConfig.Transaction_Price_ + MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                //    }
                //}
            }
            else
            {
                transactionPriceInfo = new TransactionPriceInfo();
            }
            return transactionPriceInfo;
        }
        #endregion 
    }
}
