using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Edu.Common;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.System;
using Edu.Model.Entity.EduTask;
using Edu.Model.Entity.Sell;
using Edu.Model.ViewModel.EduTask;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Sell;
using Edu.Repository.Grade;
using Edu.Repository.Sell;
using VT.FW.DB;

namespace Edu.Repository.EduTask
{
    public class RB_Student_LeaveRepository : BaseRepository<RB_Student_Leave>
    {
        // <summary>
        /// 订单学员仓储层对象
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

        /// <summary>
        /// 教务单据仓储层对象
        /// </summary>
        private readonly RB_Education_ReceiptRepository education_ReceiptRepository = new RB_Education_ReceiptRepository();
        /// <summary>
        /// 课程基础配置
        /// </summary>
        private readonly RB_Class_ConfigRepository class_ConfigRepository = new RB_Class_ConfigRepository();
        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();
        /// <summary>
        /// 课程签到记录表
        /// </summary>
        private readonly RB_Class_CheckRepository classCheckRepository = new RB_Class_CheckRepository();
        /// <summary>
        /// 班级上课计划仓储层对象
        /// </summary>
        private readonly RB_Class_PlanRepository class_PlanRepository = new RB_Class_PlanRepository();

        /// <summary>
        /// 订单仓储层对象
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();

        /// <summary>
        /// 账户仓储层
        /// </summary>
        private readonly User.RB_AccountRepository accountRepository = new User.RB_AccountRepository();
        /// <summary>
        /// 日志仓储对象
        /// </summary>
        private readonly Log.RB_User_ChangeLogRepository user_ChangeLogRepository = new Log.RB_User_ChangeLogRepository();
        /// <summary>
        /// 班级上课计划上课时间仓储层对象
        /// </summary>
        private readonly RB_Class_TimeRepository class_TimeRepository = new RB_Class_TimeRepository();

        /// <summary>
        /// 学员补课记录表仓储层对象
        /// </summary>
        private readonly BackClass.RB_Student_MakeupRepository student_MakeupRepository = new BackClass.RB_Student_MakeupRepository();
        /// <summary>
        /// 获取请假列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Leave_ViewModel> GetStudentLeaveListRepository(RB_Student_Leave_ViewModel query)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"  SELECT A.*,IFNULL(B.ClassName,'') AS ClassName FROM RB_Student_Leave AS A LEFT JOIN rb_class AS B ON A.ClassId=B.ClassId WHERE 1=1 ");
            if (query != null)
            {
                if (!string.IsNullOrEmpty(query.Q_Student_Leave_Ids))
                {
                    builder.AppendFormat(@" AND A.{0} IN ({1}) ", nameof(RB_Student_Leave_ViewModel.Id), query.Q_Student_Leave_Ids);
                }
            }
            return Get<RB_Student_Leave_ViewModel>(builder.ToString()).ToList();
        }


        /// <summary>
        /// 审核通过后更新学生签到表
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateStundetLeave(object Id, int CreateById)
        {
            //查询当前调课信息
            bool flag = false;
            var receiptModel = education_ReceiptRepository.GetEntity(Id);
            if (receiptModel == null || receiptModel.Id == 0)
            {
                return false;
            }
            if (receiptModel.ReceiptType != Common.Enum.Finance.ReceiptTypeEnum.LeaveClass)
            {
                return false;
            }
            var model = GetEntity(receiptModel.RelationId);
            if (model == null || model.Id == 0)
            {
                return false;
            }
            else //更新学生的信息
            {
                /// <summary>
                /// 请假时间信息
                /// </summary>
                List<LeaveInfoModel> LeaveInfoList = new List<LeaveInfoModel>();
                if (!string.IsNullOrWhiteSpace(model.LeaveInfo))
                {
                    LeaveInfoList = Common.Plugin.JsonHelper.DeserializeObject<List<LeaveInfoModel>>(model.LeaveInfo);
                }

                //学生信息
                List<RB_Order_Guest_ViewModel> orderGuestList = new List<RB_Order_Guest_ViewModel>();

                //班级上课计划列表
                List<RB_Class_Plan_ViewModel> planList = new List<RB_Class_Plan_ViewModel>();
                //班级上课时间列表
                List<RB_Class_Time_ViewModel> timeList = new List<RB_Class_Time_ViewModel>();

                string orderGuestIds = model.OrderGuestId.ToString();
                if (!string.IsNullOrWhiteSpace(orderGuestIds))
                {
                    orderGuestList = order_GuestRepository.GetStopingStudentPage(new RB_Order_Guest_ViewModel
                    {
                        OrderGuestIds = orderGuestIds
                    });
                }

                string classTimeIds = model.ClassTimeIds;
                if (!string.IsNullOrWhiteSpace(classTimeIds))
                {
                    timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel { QClassTimeIds = classTimeIds });
                    if (timeList != null && timeList.Any())
                    {
                        string classPlanIds = string.Join(",", timeList.Select(x => x.ClassPlanId));

                        if (!string.IsNullOrWhiteSpace(classPlanIds))
                        {
                            planList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel { QClassPlanIds = classPlanIds });
                        }
                    }
                }

                List<RB_Class_Check_ViewModel> classCheckList = new List<RB_Class_Check_ViewModel>();

                //判断当天是否有已签到数据
                var checkLogList = classCheckRepository.GetClassCheckList(new RB_Class_Check_ViewModel
                {
                    Group_Id = model.Group_Id,
                    ClassId = model.ClassId,
                    Q_ClassTimeIds = model.ClassTimeIds,
                });


                foreach (var item in timeList)
                {

                    DateTime? dateTime = planList.Where(x => x.ClassPlanId == item.ClassPlanId).FirstOrDefault()?.ClassDate;
                    if (!dateTime.HasValue)
                    {
                        try
                        {
                            dateTime = Convert.ToDateTime(LeaveInfoList.Where(x => x.ClassTimeId == item.ClassTimeId).FirstOrDefault().ClassDate);
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "UpdateStundetLeave");
                        }
                    }
                    var signModel = checkLogList?.Where(qitem => qitem.ClassTimeId == item.ClassTimeId && qitem.ClassId == item.ClassId && qitem.OrderGuestId == model.OrderGuestId)?.FirstOrDefault();
                    RB_Class_Check_ViewModel invitationModel = new RB_Class_Check_ViewModel()
                    {
                        ClassCheckId = (signModel != null && signModel.ClassCheckId > 0) ? signModel.ClassCheckId : 0,
                        ClassId = model.ClassId,
                        Group_Id = model.Group_Id,
                        School_Id = model.School_Id,
                        CheckStatus = 2,
                        StudyNum = 0,
                        Status = 0,
                        TeacherId = planList.Where(x => x.ClassPlanId == item.ClassPlanId).FirstOrDefault()?.TeacherId ?? 0,
                        ClassRoomId = planList.Where(x => x.ClassPlanId == item.ClassPlanId).FirstOrDefault()?.ClassRoomId ?? 0,
                        ClassDate = dateTime.Value,
                        ClassTimeId = item.ClassTimeId,
                        OrderGuestId = model.OrderGuestId,
                        CreateBy = CreateById,
                        CreateTime = DateTime.Now
                    };
                    classCheckList.Add(invitationModel);
                }
                if (classCheckList != null && classCheckList.Any())
                {

                    var orderModel = orderRepository.GetEntity(orderGuestList.FirstOrDefault().OrderId);

                    var classModel = classRepository.GetEntity<RB_Class_ViewModel>(model.ClassId);
                    var sellerInfo = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel { Id = orderModel.EnterID, Group_Id = model.Group_Id }).FirstOrDefault();//UserReidsCache.GetUserLoginInfo(orderModel.EnterID);

                    flag= AddClassCheckModule(classCheckList, timeList, orderGuestList, orderModel, classModel, sellerInfo);
                }
            }

            return flag;
        }



        /// <summary>
        /// 新增签到
        /// </summary>
        /// <param name="Ids"></param>
        /// <param name="DropOutRemark"></param>
        /// <returns></returns>
        public virtual bool AddClassCheckModule(List<RB_Class_Check_ViewModel> list, List<RB_Class_Time_ViewModel> timeList, List<RB_Order_Guest_ViewModel> orderGuestList, RB_Order orderModel, RB_Class_ViewModel classModel, Model.ViewModel.User.RB_Account_ViewModel sellerInfo)
        {
            //写日志
            bool flag = true;
            foreach (var item in list)
            {
                //基础课时分钟数
                var BasicMinutes = 0;
                BasicMinutes = class_ConfigRepository.GetClassMinutesRepository(item.ClassId);
                var timeModel = timeList.Where(x => x.ClassTimeId == item.ClassTimeId).FirstOrDefault();
                if (flag)
                {
                    var guestModel = orderGuestList.Where(x => x.Id == item.OrderGuestId).FirstOrDefault();
                    item.CurrentDeductionHours = timeModel?.TimeHour ?? 0;
                    decimal currentDeductionHours = item.CurrentDeductionHours;
                    if (item.CheckStatus == 2)
                    {
                        currentDeductionHours = 0;
                    }
                    if (item.ClassCheckId > 0)
                    {
                        Dictionary<string, object> fileds = new Dictionary<string, object>()
                        {
                            { nameof(RB_Class_Check_ViewModel.CheckStatus),item.CheckStatus},
                            { nameof(RB_Class_Check_ViewModel.StudyNum),item.StudyNum},
                            { nameof(RB_Class_Check_ViewModel.CurrentDeductionHours),currentDeductionHours},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>()
                        {
                          new WhereHelper (nameof(RB_Class_Check_ViewModel.ClassCheckId),item.ClassCheckId)
                        };
                        flag = classCheckRepository.Update(fileds, wheres);
                    }
                    else
                    {
                        item.CurrentDeductionHours = currentDeductionHours;
                        item.MakeUpStatus = 1;
                        var newId = classCheckRepository.Insert(item);
                        item.ClassCheckId = newId;
                        flag = newId > 0;
                    }
                    var oldModel = classCheckRepository.GetGuestFinishMinutesRepository(item.OrderGuestId.ToString(), ClassCheckId: item.ClassCheckId)?.FirstOrDefault();
                    if (flag)
                    {
                        //更新学员完成课时
                        var completeHours = (oldModel?.FinishClassHours ?? 0) + currentDeductionHours;
                        Dictionary<string, object> orderFileds = new Dictionary<string, object>()
                        {
                            {nameof(RB_Order_Guest_ViewModel.CompleteHours),completeHours }
                        };

                        string LogContent = "";
                        var shenyuHours = guestModel.ValidClassHours - completeHours;
                        //已上课时>=有效课时，如果是，修改学员状态为停课，并且备注“有效课时消耗完毕，系统自动停课”
                        if (completeHours > guestModel.ValidClassHours)
                        {
                            orderFileds.Add(nameof(RB_Order_Guest_ViewModel.GuestState),(int)GuestStateEnum.StopClasses);
                            orderFileds.Add(nameof(RB_Order_Guest_ViewModel.ChangeEffectTime), DateTime.Now);
                            orderFileds.Add(nameof(RB_Order_Guest_ViewModel.DropOutRemark), "有效课时消耗完毕，系统自动停课");
                            LogContent = guestModel.GuestName + "有效课时消耗完毕，系统自动停课!";

                            // var orderModel = orderRepository.GetEntity(guestModel.OrderId);
                            var shengyuMoney = orderModel.PreferPrice - orderModel.Income + orderModel.Refund - orderModel.PlatformTax - orderModel.DiscountMoney - orderModel.LessPrice;
                            // var classModel = classRepository.GetEntity<RB_Class_ViewModel>(guestModel.ClassId);
                            // var sellerInfo = UserReidsCache.GetUserLoginInfo(orderModel.EnterID);
                            #region 欠费提醒（销售）
                            var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(orderModel.EnterID);
                            if (!string.IsNullOrEmpty(queryTargetWorkId))
                            {
                                // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                var path = $"/sale/myOrder?OrderId={guestModel.OrderId}";
                                path = HttpUtility.UrlEncode(path);
                                string markdownContent = $"`停课通知` 学员欠费停课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>当前状态：<font color='warning'>停课</font>\n>关联单号：{guestModel.OrderId}\n>\n>待收金额：<font color='warning'>￥{shengyuMoney.ToString("0.00")}</font>\n>停课理由：费用不足，系统自动触发停课限制\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={orderModel.EnterID}&target={path})";
                                Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                {
                                    CategoryId = PushMessageCategoryEnum.SalePeople,
                                    Content = markdownContent,
                                    CoverImg = "",
                                    CreateByName = "系统",
                                    JumpUrl = "",
                                    WorkMsgType = "markdown",
                                    SendTime = DateTime.Now,
                                    SendType = 0,
                                    Title = "学员欠费停课通知",
                                    Platform = 5,
                                    ReceiveId = queryTargetWorkId
                                };
                                Common.Message.MessageHelper.SendMessage(modelWork);

                            }
                            #endregion

                            #region 欠费提醒（管理者）
                            var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_Arrears");
                            if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                            {
                                queryNotifyManager.ForEach(x =>
                                {
                                    var path = $"/sale/orderStatistics?OrderId={guestModel.OrderId}";
                                    path = HttpUtility.UrlEncode(path);

                                    string markdownContent = $"`停课通知` 学员欠费停课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>当前状态：<font color='warning'>停课</font>\n>关联单号：{guestModel.OrderId}({sellerInfo.AccountName})\n>\n>待收金额：<font color='warning'>￥{shengyuMoney.ToString("0.00")}</font>\n>停课理由：费用不足，系统自动触发停课限制\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                                    Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                    {
                                        CategoryId = PushMessageCategoryEnum.SalePeople,
                                        Content = markdownContent,
                                        CoverImg = "",
                                        CreateByName = "系统",
                                        JumpUrl = "",
                                        WorkMsgType = "markdown",
                                        SendTime = DateTime.Now,
                                        SendType = 0,
                                        Title = "学员欠费停课通知",
                                        Platform = 5,
                                        ReceiveId = x.WorkUserId
                                    };
                                    Common.Message.MessageHelper.SendMessage(modelWork);
                                });
                            }
                            #endregion
                        }
                        else if (guestModel.TotalHours > guestModel.ValidClassHours && shenyuHours < 12)
                        {
                            // var orderModel = orderRepository.GetEntity(guestModel.OrderId);
                            var shengyuMoney = orderModel.PreferPrice - orderModel.Income + orderModel.Refund - orderModel.PlatformTax - orderModel.DiscountMoney - orderModel.LessPrice;
                            //  var classModel = classRepository.GetEntity<RB_Class_ViewModel>(guestModel.ClassId);
                            //  var sellerInfo = UserReidsCache.GetUserLoginInfo(orderModel.EnterID);
                            #region 即将欠费提醒（销售）
                            var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(orderModel.EnterID);
                            if (!string.IsNullOrEmpty(queryTargetWorkId))
                            {
                                // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                var path = $"/sale/myOrder?OrderId={guestModel.OrderId}";
                                path = HttpUtility.UrlEncode(path);
                                string markdownContent = $"`欠费预警` 学员即将欠费通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>剩余课时：<font color='warning'>{shenyuHours}</font>\n>关联单号：{guestModel.OrderId}\n>\n>待收金额：<font color='warning'>￥{shengyuMoney.ToString("0.00")}</font>\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={orderModel.EnterID}&target={path})";
                                Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                {
                                    CategoryId = PushMessageCategoryEnum.SalePeople,
                                    Content = markdownContent,
                                    CoverImg = "",
                                    CreateByName = "系统",
                                    JumpUrl = "",
                                    WorkMsgType = "markdown",
                                    SendTime = DateTime.Now,
                                    SendType = 0,
                                    Title = "学员即将欠费通知",
                                    Platform = 5,
                                    ReceiveId = queryTargetWorkId
                                };
                                Common.Message.MessageHelper.SendMessage(modelWork);

                            }
                            #endregion
                            #region 即将欠费提醒（管理者）
                            var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_Arrears");
                            if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                            {
                                queryNotifyManager.ForEach(x =>
                                {
                                    var path = $"/sale/orderStatistics?OrderId={guestModel.OrderId}";
                                    path = HttpUtility.UrlEncode(path);

                                    string markdownContent = $"`欠费预警` 学员即将欠费通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>剩余课时：<font color='warning'>{shenyuHours}</font>\n>关联单号：{guestModel.OrderId}({sellerInfo.AccountName})\n>\n>待收金额：<font color='warning'>￥{shengyuMoney.ToString("0.00")}</font>\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                                    Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                    {
                                        CategoryId = PushMessageCategoryEnum.SalePeople,
                                        Content = markdownContent,
                                        CoverImg = "",
                                        CreateByName = "系统",
                                        JumpUrl = "",
                                        WorkMsgType = "markdown",
                                        SendTime = DateTime.Now,
                                        SendType = 0,
                                        Title = "学员即将欠费通知",
                                        Platform = 5,
                                        ReceiveId = x.WorkUserId
                                    };
                                    Common.Message.MessageHelper.SendMessage(modelWork);
                                });
                            }
                            #endregion
                        }
                        else if (guestModel.TotalHours == guestModel.ValidClassHours && shenyuHours < 12 && shenyuHours > 0)
                        {
                            //  var orderModel = orderRepository.GetEntity(guestModel.OrderId);
                            var shengyuMoney = orderModel.PreferPrice - orderModel.Income + orderModel.Refund - orderModel.PlatformTax - orderModel.DiscountMoney - orderModel.LessPrice;
                            //   var classModel = classRepository.GetEntity<RB_Class_ViewModel>(guestModel.ClassId);
                            //  var sellerInfo = UserReidsCache.GetUserLoginInfo(orderModel.EnterID);
                            #region 即将结课提醒 (销售端)
                            var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(orderModel.EnterID);
                            if (!string.IsNullOrEmpty(queryTargetWorkId))
                            {
                                // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                var path = $"/sale/myOrder?OrderId={guestModel.OrderId}";
                                path = HttpUtility.UrlEncode(path);

                                string markdownContent = $"`结课预警` 学员即将结课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>剩余课时：<font color='warning'>{shenyuHours}</font>\n>是否续班：<font color='{(orderModel.RenewOrderId > 0 ? "info" : "warning")}'>{(orderModel.RenewOrderId > 0 ? "已续班(" + orderModel.RenewOrderId + ")" : "未续班")}</font>\n>关联单号：{guestModel.OrderId}\n>\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={orderModel.EnterID}&target={path})";
                                Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                {
                                    CategoryId = PushMessageCategoryEnum.SalePeople,
                                    Content = markdownContent,
                                    CoverImg = "",
                                    CreateByName = "系统",
                                    JumpUrl = "",
                                    WorkMsgType = "markdown",
                                    SendTime = DateTime.Now,
                                    SendType = 0,
                                    Title = "学员即将结课通知",
                                    Platform = 5,
                                    ReceiveId = queryTargetWorkId
                                };
                                Common.Message.MessageHelper.SendMessage(modelWork);

                            }
                            #endregion

                            #region 即将结课提醒 (管理端)
                            var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_EndClass");
                            if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                            {
                                queryNotifyManager.ForEach(x =>
                                {
                                    // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                    var path = $"/sale/orderStatistics?OrderId={guestModel.OrderId}";
                                    path = HttpUtility.UrlEncode(path);

                                    string markdownContent = $"`结课预警` 学员即将结课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>剩余课时：<font color='warning'>{shenyuHours}</font>\n>是否续班：<font color='{(orderModel.RenewOrderId > 0 ? "info" : "warning")}'>{(orderModel.RenewOrderId > 0 ? "已续班(" + orderModel.RenewOrderId + ")" : "未续班")}</font>\n>关联单号：{guestModel.OrderId} ({sellerInfo.AccountName})\n>\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                                    Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                    {
                                        CategoryId = PushMessageCategoryEnum.SalePeople,
                                        Content = markdownContent,
                                        CoverImg = "",
                                        CreateByName = "系统",
                                        JumpUrl = "",
                                        WorkMsgType = "markdown",
                                        SendTime = DateTime.Now,
                                        SendType = 0,
                                        Title = "学员即将结课通知",
                                        Platform = 5,
                                        ReceiveId = x.WorkUserId
                                    };
                                    Common.Message.MessageHelper.SendMessage(modelWork);
                                });
                            }
                            #endregion
                        }
                        else if (guestModel.TotalHours == guestModel.ValidClassHours && shenyuHours == 0)
                        {
                            //  var orderModel = orderRepository.GetEntity(guestModel.OrderId);
                            var shengyuMoney = orderModel.PreferPrice - orderModel.Income + orderModel.Refund - orderModel.PlatformTax - orderModel.DiscountMoney - orderModel.LessPrice;
                            //  var classModel = classRepository.GetEntity<RB_Class_ViewModel>(guestModel.ClassId);
                            //  var sellerInfo = UserReidsCache.GetUserLoginInfo(orderModel.EnterID);
                            #region 即将结课提醒 (销售端)
                            var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(orderModel.EnterID);
                            if (!string.IsNullOrEmpty(queryTargetWorkId))
                            {
                                // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                var path = $"/sale/myOrder?OrderId={guestModel.OrderId}";
                                path = HttpUtility.UrlEncode(path);

                                string markdownContent = $"`结课通知` 学员已结课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>剩余课时：<font color='warning'>{shenyuHours}</font>\n>是否续班：<font color='{(orderModel.RenewOrderId > 0 ? "info" : "warning")}'>{(orderModel.RenewOrderId > 0 ? "已续班(" + orderModel.RenewOrderId + ")" : "未续班")}</font>\n>关联单号：{guestModel.OrderId}\n>\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={orderModel.EnterID}&target={path})";
                                Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                {
                                    CategoryId = PushMessageCategoryEnum.SalePeople,
                                    Content = markdownContent,
                                    CoverImg = "",
                                    CreateByName = "系统",
                                    JumpUrl = "",
                                    WorkMsgType = "markdown",
                                    SendTime = DateTime.Now,
                                    SendType = 0,
                                    Title = "学员已结课通知",
                                    Platform = 5,
                                    ReceiveId = queryTargetWorkId
                                };
                                Common.Message.MessageHelper.SendMessage(modelWork);

                            }
                            #endregion

                            #region 即将结课提醒 (销售端)
                            var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_EndClass");
                            if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                            {
                                queryNotifyManager.ForEach(x =>
                                {
                                    // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                    var path = $"/sale/orderStatistics?OrderId={guestModel.OrderId}";
                                    path = HttpUtility.UrlEncode(path);

                                    string markdownContent = $"`结课通知` 学员已结课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>剩余课时：<font color='warning'>{shenyuHours}</font>\n>是否续班：<font color='{(orderModel.RenewOrderId > 0 ? "info" : "warning")}'>{(orderModel.RenewOrderId > 0 ? "已续班(" + orderModel.RenewOrderId + ")" : "未续班")}</font>\n>关联单号：{guestModel.OrderId} ({sellerInfo.AccountName})\n>\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                                    Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                    {
                                        CategoryId = PushMessageCategoryEnum.SalePeople,
                                        Content = markdownContent,
                                        CoverImg = "",
                                        CreateByName = "系统",
                                        JumpUrl = "",
                                        WorkMsgType = "markdown",
                                        SendTime = DateTime.Now,
                                        SendType = 0,
                                        Title = "学员已结课通知",
                                        Platform = 5,
                                        ReceiveId = x.WorkUserId
                                    };
                                    Common.Message.MessageHelper.SendMessage(modelWork);
                                });
                            }
                            #endregion
                        }

                        if (item.CheckStatus == 1)
                        {
                            #region 通知缺勤信息
                            var param = new RB_Class_Plan_ViewModel()
                            {
                                ClassTimeId = item.ClassTimeId
                            };
                            var planModel = class_PlanRepository.GetClassPlanListExtRepository(param).FirstOrDefault();
                            var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_Absence");
                            if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                            {
                                queryNotifyManager.ForEach(x =>
                                {
                                    // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                                    var path = $"/stuMan/studentManage?OrderId={guestModel.OrderId}";
                                    path = HttpUtility.UrlEncode(path);

                                    string markdownContent = $"`缺勤通知` 学员缺勤信息告知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>缺勤时间：<font color='warning'>{planModel.ClassDate}({planModel.StartTime}-{planModel.EndTime})</font>\n>关联单号：{guestModel.OrderId}\n>班级名称：<font>{planModel.ClassName}</font>\n>带班老师：<font>{planModel.TeacherName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                                    Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                                    {
                                        CategoryId = PushMessageCategoryEnum.SalePeople,
                                        Content = markdownContent,
                                        CoverImg = "",
                                        CreateByName = "系统",
                                        JumpUrl = "",
                                        WorkMsgType = "markdown",
                                        SendTime = DateTime.Now,
                                        SendType = 0,
                                        Title = "学员缺勤通知",
                                        Platform = 5,
                                        ReceiveId = x.WorkUserId
                                    };
                                    Common.Message.MessageHelper.SendMessage(modelWork);
                                });
                            }

                            #endregion
                        }

                        flag = order_GuestRepository.Update(orderFileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), item.OrderGuestId));
                        if (flag && !string.IsNullOrEmpty(LogContent))
                        {
                            user_ChangeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                            {
                                Id = 0,
                                Type = 3,
                                CreateBy = item.CreateBy,
                                CreateTime = DateTime.Now,
                                Group_Id = item.Group_Id,
                                LogContent = LogContent,
                                School_Id = item.School_Id,
                                SourceId = guestModel.Id
                            });
                        }
                        //缺勤和请假
                        if (item.CheckStatus == 1 || item.CheckStatus == 2)
                        {
                            flag = CalcGuestHoursModule(guestModel, item, orderModel, classModel, sellerInfo);
                        }
                    }
                }
            }
            return flag;
        }



        /// <summary>
        /// 计算学员缺课课时
        /// </summary>
        /// <param name="guestModel"></param>
        /// <param name="checkModel"></param>
        /// <returns></returns>
        public bool CalcGuestHoursModule(RB_Order_Guest guestModel, RB_Class_Check_ViewModel checkModel, RB_Order orderModel, RB_Class_ViewModel classModel, Model.ViewModel.User.RB_Account_ViewModel sellerInfo)
        {
            bool flag = true;
            if (guestModel.GuestState == GuestStateEnum.Normal)
            {
                decimal NoFinishHours = 0;
                //获取以前所有签到列表【倒叙】
                var checkList = classCheckRepository.GetClassCheckListRepository(new RB_Class_Check_ViewModel()
                {
                    ClassId = checkModel.ClassId,
                    OrderGuestId = checkModel.OrderGuestId,
                    EndDate = Common.ConvertHelper.FormatDate(checkModel.ClassDate)
                }).OrderByDescending(qitem => qitem.ClassDate).ToList();
                for (var i = 0; i < checkList.Count; i++)
                {
                    if ((checkList[i].CheckStatus == 1) && (checkList[i].MakeUpStatus == 3 || checkList[i].MakeUpStatus == 4 || checkList[i].MakeUpStatus == 1))
                    {
                        NoFinishHours += checkList[i].CurrentDeductionHours;
                    }
                    else
                    {
                        break;
                    }
                }
                Dictionary<string, object> fileds = new Dictionary<string, object>();
                Dictionary<string, object> checkFileds = new Dictionary<string, object>();
                //缺勤课时超过12课时更新学员状态为【停课】
                if (NoFinishHours >= Common.Config.AbsentHours)
                {
                    fileds.Add(nameof(RB_Order_Guest_ViewModel.GuestState), (int)GuestStateEnum.StopClasses);
                    checkFileds.Add(nameof(RB_Class_Check_ViewModel.IsAbsentHours), 1);
                    checkFileds.Add(nameof(RB_Class_Check_ViewModel.MakeUpStatus), 4);

                    var shengyuMoney = orderModel.PreferPrice - orderModel.Income + orderModel.Refund - orderModel.PlatformTax - orderModel.DiscountMoney - orderModel.LessPrice;

                    #region 欠费提醒（销售）
                    var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(orderModel.EnterID);
                    if (!string.IsNullOrEmpty(queryTargetWorkId))
                    {
                        // 学员名称（名称+电话），剩余课时，关联单号，待收金额，班级老师，班级名称
                        var path = $"/sale/myOrder?OrderId={guestModel.OrderId}";
                        path = HttpUtility.UrlEncode(path);
                        string markdownContent = $"`停课通知` 学员欠费停课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>当前状态：<font color='warning'>停课</font>\n>关联单号：{guestModel.OrderId}\n>\n>待收金额：<font color='warning'>￥{shengyuMoney.ToString("0.00")}</font>\n>停课理由：连续缺课超过{Config.AbsentHours}课时，系统自动停课\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={orderModel.EnterID}&target={path})";
                        Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                        {
                            CategoryId = PushMessageCategoryEnum.SalePeople,
                            Content = markdownContent,
                            CoverImg = "",
                            CreateByName = "系统",
                            JumpUrl = "",
                            WorkMsgType = "markdown",
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "学员欠费停课通知",
                            Platform = 5,
                            ReceiveId = queryTargetWorkId
                        };
                        Common.Message.MessageHelper.SendMessage(modelWork);

                    }
                    #endregion

                    #region 欠费提醒（管理者）
                    var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_Arrears");
                    if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                    {
                        queryNotifyManager.ForEach(x =>
                        {
                            var path = $"/sale/orderStatistics?OrderId={guestModel.OrderId}";
                            path = HttpUtility.UrlEncode(path);

                            string markdownContent = $"`停课通知` 学员欠费停课通知\n>**概要信息** \n>学员名称：{guestModel.GuestName}({guestModel.Mobile})\n>当前状态：<font color='warning'>停课</font>\n>关联单号：{guestModel.OrderId}({sellerInfo.AccountName})\n>\n>待收金额：<font color='warning'>￥{shengyuMoney.ToString("0.00")}</font>\n>停课理由：连续缺课超过{Config.AbsentHours}课时，系统自动停课\n>班级名称：<font>{classModel.ClassName}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                            Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                            {
                                CategoryId = PushMessageCategoryEnum.SalePeople,
                                Content = markdownContent,
                                CoverImg = "",
                                CreateByName = "系统",
                                JumpUrl = "",
                                WorkMsgType = "markdown",
                                SendTime = DateTime.Now,
                                SendType = 0,
                                Title = "学员欠费停课通知",
                                Platform = 5,
                                ReceiveId = x.WorkUserId
                            };
                            Common.Message.MessageHelper.SendMessage(modelWork);
                        });
                    }
                    #endregion
                }
                if (fileds != null && fileds.Count > 0 && checkFileds != null && checkFileds.Count > 0)
                {
                    List<WhereHelper> wheres = new List<WhereHelper>()
                    {
                        new WhereHelper (nameof(RB_Order_Guest_ViewModel.Id),guestModel.Id),
                    };
                    flag = order_GuestRepository.Update(fileds, wheres);
                    List<WhereHelper> checkWheres = new List<WhereHelper>()
                    {
                        new WhereHelper (nameof(RB_Class_Check_ViewModel.ClassCheckId),checkModel.ClassCheckId),
                    };
                    flag = classCheckRepository.Update(checkFileds, checkWheres);
                }

                if (flag && checkModel.CheckStatus == 1 && checkModel.IsUpdateMakeUp != 1)
                {
                    //请假的 因为不扣课时， 无法进补课
                    flag = student_MakeupRepository.SetStudentMakeUpRepository(new RB_Student_Makeup()
                    {
                        Id = 0,
                        ClassCheckId = checkModel.ClassCheckId,
                        ClassDate = checkModel.ClassDate,
                        ClassId = checkModel.ClassId,
                        CreateBy = checkModel.CreateBy,
                        CreateTime = checkModel.CreateTime,
                        Group_Id = checkModel.Group_Id,
                        MakeUpStatus = 1,
                        OrderGuestId = checkModel.OrderGuestId
                    });
                }
            }
            return flag;
        }

    }
}
