using Mall.Common;
using Mall.Model.Extend.User;
using Mall.Repository.BaseSetUp;
using Mall.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mall.Module.User
{
   /// <summary>
   /// 用户查看微信日志处理类
   /// </summary>
   public class MemberLookModule
    {
        /// <summary>
        /// 用户查看微信日志仓储层对象
        /// </summary>
        private readonly RB_Member_LookRepository member_LookRepository = new RB_Member_LookRepository();
        /// <summary>
        /// 用户
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 基础配置
        /// </summary>
        private readonly RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();

        /// <summary>
        /// 获取用户查看微信日志分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Member_Look_Extend> GetMemberLookPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Member_Look_Extend query)
        {
            return member_LookRepository.GetMemberLookPageRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 获取用户查看日志列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Member_Look_Extend> GetMemberLookListModule(RB_Member_Look_Extend query)
        {
            return member_LookRepository.GetMemberLookListRepository(query);
        }

        /// <summary>
        /// 新增用户查看日志
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddMemberLookModule(RB_Member_Look_Extend model)
        {
            #region 验证当月时长已存在
            string STime = GetMondayDate().ToString("yyyy-MM-dd");//本周一
            string ETime = GetSundayDate().ToString("yyyy-MM-dd");//本周日
            var list = member_LookRepository.GetMemberLookListRepository(new RB_Member_Look_Extend() { MallBaseId = model.MallBaseId, UserId = model.UserId, CreateBy = model.CreateBy, StartTime = STime, EndTime = ETime });
            if (list.Any()) {
                return false;
            }
            #endregion

            var newId = member_LookRepository.Insert(model);
            model.LookId = newId;
            return newId > 0;
        }

        /// <summary>
        /// 获取用户查看次数
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetWeChatLookUser(int userId, AppletUserInfo userInfo, out bool IsLook)
        {
            string STime = GetMondayDate().ToString("yyyy-MM-dd");//本周一
            string ETime = GetSundayDate().ToString("yyyy-MM-dd");//本周日
            //首先查询是否已查看
            IsLook = false;
            var list = member_LookRepository.GetMemberLookListRepository(new RB_Member_Look_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userId, CreateBy = userInfo.UserId, StartTime = STime, EndTime = ETime });
            if (list.Any())
            {
                IsLook = true;
            }
            //查询本周已查看次数   ld 2021-11-15 修改为周次数
            int LookNum = member_LookRepository.GetMemberLookNum(userInfo.MallBaseId, userInfo.UserId, STime, ETime);
            //查询用户可查看次数
            var umodel = member_UserRepository.GetEntity(userInfo.UserId);
            int TotalNum = umodel.LookTimes;
            if (umodel.LookTimes <= 0) {
                //查询配置表中
                var baseModel = mallBaseRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_MallBase_Extend() { MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                if (baseModel != null) {
                    TotalNum = baseModel.LookWeChatTimes;
                }
            }

            return new
            {
                IsLook,
                TotalNum,
                SurplusNum = TotalNum - LookNum > 0 ? TotalNum - LookNum : 0
            };
        }

        #region 计算本周日期
        /// <summary>
        /// 计算本周的周一日期
        /// </summary>
        /// <returns></returns>
        private DateTime GetMondayDate()
        {
            return GetMondayDate(DateTime.Now);
        }
        /// <summary>
        /// 计算本周周日的日期
        /// </summary>
        /// <returns></returns>
        private DateTime GetSundayDate()
        {
            return GetSundayDate(DateTime.Now);
        }
        /// <summary>
        /// 计算某日起始日期（礼拜一的日期）
        /// </summary>
        /// <param name="someDate">该周中任意一天</param>
        /// <returns>返回礼拜一日期，后面的具体时、分、秒和传入值相等</returns>
        private DateTime GetMondayDate(DateTime someDate)
        {
            int i = someDate.DayOfWeek - DayOfWeek.Monday;
            if (i == -1) i = 6;// i值 > = 0 ，因为枚举原因，Sunday排在最前，此时Sunday-Monday=-1，必须+7=6。
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return someDate.Subtract(ts);
        }
        /// <summary>
        /// 计算某日结束日期（礼拜日的日期）
        /// </summary>
        /// <param name="someDate">该周中任意一天</param>
        /// <returns>返回礼拜日日期，后面的具体时、分、秒和传入值相等</returns>
        private DateTime GetSundayDate(DateTime someDate)
        {
            int i = someDate.DayOfWeek - DayOfWeek.Sunday;
            if (i != 0) i = 7 - i;// 因为枚举原因，Sunday排在最前，相减间隔要被7减。
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return someDate.Add(ts);
        }
        #endregion
    }
}
