using Edu.CacheManager.Base;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Enum.Customer;
using Edu.Common.Enum.User;
using Edu.Model.CacheModel;
using Edu.Repository.Customer;
using Edu.Repository.User;
using System;
using System.Linq;

namespace Edu.Cache.User
{
    /// <summary>
    /// redis缓存
    /// </summary>
    public class UserReidsCache
    {
        /// <summary>
        /// 使用redis第几号库
        /// </summary>
        public static readonly int REDIS_DB3 = 3;

        static readonly RedisHelper redis = new RedisHelper(REDIS_DB3);

        /// <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>
        /// <param name="cacheKey"></param>
        public static object Get(string cacheKey)
        {
            try
            {
                object info = redis.StringGet<object>(cacheKey);
                return info;
            }
            catch (Exception)
            {
                return "";
            }
        }
        /// <summary>
        /// 账号仓储层对象
        /// </summary>
        private static readonly RB_AccountRepository accountRepository = new RB_AccountRepository();
        /// <summary>
        /// 部门仓储层对象
        /// </summary>
        private static readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();

        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <param name="Id">账号Id</param>
        /// <param name="apiRequestFromEnum">请求来源</param>
        /// <returns></returns>
        public static UserInfo GetUserLoginInfo(object Id, ApiRequestFromEnum apiRequestFromEnum = ApiRequestFromEnum.WebAdmin)
        {
            UserInfo userInfo = null;
            if (Id != null)
            {
                string cacheKey = Cache.CacheKey.User_Login_Key + Id.ToString();
                try
                {
                    userInfo = redis.StringGet<UserInfo>(cacheKey);
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "GetUserLoginInfo");
                }
                if (userInfo == null)
                {
                    Int32.TryParse(Id.ToString(), out int NewId);
                    if (NewId > 0)
                    {
                        string token = "";
                        var model = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                        {
                            Id = NewId
                        })?.FirstOrDefault();
                        if (model != null)
                        {
                            var deptList = departmentRepository.GetDepartmentListRepository(new Model.ViewModel.User.RB_Department_ViewModel()
                            {
                                DeptId = model.Dept_Id,
                                Group_Id = model.Group_Id,
                                ManagerIds = model.Id.ToString()
                            });
                            userInfo = new UserInfo
                            {
                                Id = model.Id,
                                Group_Id = model.Group_Id,
                                School_Id = model.School_Id,
                                AccountType = model.AccountType,
                                AccountName = model.AccountName,
                                GroupName = model.GroupName,
                                SchoolName = model.SchoolName,
                                Token = token,
                                ApiRequestFromEnum = apiRequestFromEnum,
                                DeptId = model.Dept_Id,
                                PostId = model.Post_Id,
                                AccountId = model.AccountId,
                                UserMobile = model.Account,
                                ErpToken = "",
                                MallToken = "",
                                JHMallBaseId = "",
                                JHTenantId = "",
                                GroupLogo = model.GroupLogo,
                                UserIcon = model.UserIcon,
                                DeptName = model.DeptName,
                                PostName = model.PostName,
                                Email = model.Email,
                                IsTenCccUser = model.IsTenCccUser,
                                IsCourseConsultant = (model != null && model.UserRole == UserRoleEnum.CourseConsultant) ? 1 : 0,
                                IsMarket = (model != null && model.UserRole == UserRoleEnum.MarketPersion) ? 1 : 0,
                                IsManager = (deptList?.Count ?? 0) > 0 ? 1 : 0,
                            };
                            UserInfoSet(Cache.CacheKey.User_Login_Key + Id.ToString(), userInfo, Common.Config.JwtExpirTime);
                        }
                    }
                }
            }
            else
            {
                userInfo = new UserInfo();
            }
            return userInfo;
        }

        /// <summary>
        /// 清除用户缓存
        /// </summary>
        /// <param name="Id"></param>
        public static void ClearUserLoginCache(object Id)
        {
            string cacheKey = CacheKey.User_Login_Key + Id.ToString();
            redis.KeyDelete(cacheKey);
        }

        /// <summary>
        /// 同业
        /// </summary>
        private static readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();

        /// <summary>
        /// 获取同于用户登录信息
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public static AppletCustomerInfo GetAppletCustomerLoginInfo(object CustomerId)
        {
            if (CustomerId != null)
            {
                string cacheKey = CacheKey.AppletB2B_Login_Info_ + CustomerId.ToString();
                AppletCustomerInfo userInfo = null;
                try
                {
                    userInfo = redis.StringGet<AppletCustomerInfo>(cacheKey);
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "GetAppletCustomerLoginInfo");
                }
                if (userInfo == null)
                {
                    Int32.TryParse(CustomerId.ToString(), out int NewUserId);
                    if (NewUserId > 0)
                    {
                        string token = "";
                        var umodel = customerRepository.GetEntity(NewUserId);
                        if (umodel != null && umodel.CustomerState == CustomerStateEnum.Normal)
                        {
                            userInfo = new AppletCustomerInfo
                            {
                                MallBaseId = umodel.MallBaseId,
                                MallName = "",
                                Mobile = umodel.ContactNumber,
                                CustomerId = NewUserId,
                                CustomerName = umodel.CustomerName,
                                OpenId = umodel.OpenId,
                                Photo = umodel.WeChatPhoto,
                                Source = umodel.CustomerSourceType,
                                CustomerToken = token,
                                Blacklist = 0,
                                GroupId = umodel.Group_Id,
                                IsAdmin = 0,
                                AdminId = 0,
                                SaleId = umodel.CreateBy
                            };
                            AppletCustomerSet(CacheKey.AppletB2B_Login_Info_ + CustomerId, userInfo, Config.JwtExpirTime);
                        }
                    }
                }
                return userInfo;
            }
            return null;
        }

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