using Edu.AOP.CustomerAttribute;
using Edu.Common.Enum;
using Edu.Common.Enum.Course;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Log;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 班级管理处理类
    /// </summary>
    public class ClassModule
    {
        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 班级上课计划仓储层对象
        /// </summary>
        private readonly RB_Class_PlanRepository class_PlanRepository = new RB_Class_PlanRepository();

        /// <summary>
        /// 班级上课计划上课时间仓储层对象
        /// </summary>
        private readonly RB_Class_TimeRepository class_TimeRepository = new RB_Class_TimeRepository();

        /// <summary>
        /// 班级价格仓储层对象
        /// </summary>
        private readonly RB_Class_StepPriceRepository class_StepPriceRepository = new RB_Class_StepPriceRepository();

        /// <summary>
        /// 订单学员仓储层对象
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

        /// <summary>
        /// 课程仓储层对象
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();

        /// <summary>
        /// 订单仓储层对象
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();
        /// <summary>
        /// 课程日志记录表
        /// </summary>
        private readonly RB_Class_LogRepository classLogRepository = new RB_Class_LogRepository();
        /// <summary>
        /// 课程签到记录表
        /// </summary>
        private readonly RB_Class_CheckRepository classCheckRepository = new RB_Class_CheckRepository();

        /// <summary>
        /// 课程日志记录表
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();

        /// <summary>
        /// 教室仓储层对象
        /// </summary>
        private readonly RB_Class_RoomRepository class_RoomRepository = new RB_Class_RoomRepository();

        /// <summary>
        /// 教师仓储层对象
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

        /// <summary>
        /// 开启班级收支仓储层对象
        /// </summary>
        private readonly RB_Class_FinanceRepository classFinanceRepository = new RB_Class_FinanceRepository();

        /// <summary>
        /// 班级签到仓储层对象
        /// </summary>
        private readonly RB_Class_CheckRepository class_CheckRepository = new RB_Class_CheckRepository();

        /// <summary>
        /// 课程基础配置
        /// </summary>
        private readonly RB_Class_ConfigRepository class_ConfigRepository = new RB_Class_ConfigRepository();


        /// <summary>
        /// 课程基础配置
        /// </summary>
        private readonly RB_Class_LessonPlanDetailsRepository ClassLessonPlanDetailsRepository = new RB_Class_LessonPlanDetailsRepository();

        /// <summary>
        /// 课程基础配置
        /// </summary>
        private readonly RB_Class_LessonPlanProjectsRepository ClassLessonPlanProjectsRepository = new RB_Class_LessonPlanProjectsRepository();
        private readonly RB_Class_LessonCommentRepository classLessonCommentRepository = new RB_Class_LessonCommentRepository();



        /// <summary>
        /// 课程基础配置
        /// </summary>
        private readonly RB_Class_LessonPlanRepository ClassLessonPlanRepository = new RB_Class_LessonPlanRepository();

        /// <summary>
        /// 获取班级列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassListModule(RB_Class_ViewModel query)
        {
            return classRepository.GetClassListRepository(query);
        }


        /// <summary>
        /// 获取班级课程名称以及老师信息列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassAndCourseListRepository(RB_Class_ViewModel query)
        {
            return classRepository.GetClassAndCourseListRepository(query);
        }

        /// <summary>
        /// 获取班级上课时间列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Time_ViewModel> GetClassTimeListRepository(RB_Class_Time_ViewModel query)
        {
            return class_TimeRepository.GetClassTimeListRepository(query);
        }

        /// <summary>
        /// 获取班级分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <param name="isGetStepPrice">是否查询阶梯价格</param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Class_ViewModel query, bool isGetStepPrice = false)
        {
            var list = classRepository.GetClassPageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                var classTimeList = new List<RB_Class_Time_ViewModel>();
                var classOrderList = new List<RB_Order_ViewModel>();
                var stepPriceList = new List<RB_Class_StepPrice_ViewModel>();
                string ids = string.Join(",", list.Select(qitem => qitem.ClassId));
                if (!string.IsNullOrEmpty(ids))
                {
                    classTimeList = class_TimeRepository.GetClassTimeListRepository(ids);
                    classOrderList = orderRepository.GetClassOrderPeopleNum(ids);
                }
                if (isGetStepPrice)
                {
                    stepPriceList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { QClassIds = ids })?.ToList() ?? new List<RB_Class_StepPrice_ViewModel>();
                }

                //课程计划上课日期
                foreach (var item in list)
                {
                    item.NewPlanDateTime = classTimeList?.Where(qitem => qitem.ClassId == item.ClassId)?.FirstOrDefault()?.NewPlanDateTime;
                    item.OrderStudentCount = classOrderList?.Where(qitem => qitem.ClassId == item.ClassId)?.FirstOrDefault()?.GuestNum ?? 0;
                    if (isGetStepPrice)
                    {
                        item.ClassStepPriceList = stepPriceList?.Where(qitem => qitem.ClassId == item.ClassId)?.ToList() ?? new List<RB_Class_StepPrice_ViewModel>();
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 获取班级日志分页列表
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowsCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Class_Log_ViewModel> GetClassLogPageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Class_Log_ViewModel query)
        {
            return classLogRepository.GetClassLogPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 检查班级是否存在
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool ExistsClassModule(RB_Class_ViewModel model)
        {
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
               new WhereHelper (nameof(RB_Class_ViewModel.ClassName),model.ClassName.Trim()),
            };
            if (model.ClassId > 0)
            {
                wheres.Add(new WhereHelper(nameof(RB_Class_ViewModel.ClassId), model.ClassId, OperatorEnum.NotEqual));
            }
            return classRepository.Exists(wheres);
        }

        /// <summary>
        /// 新增修改班级
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual bool SetClassModule(RB_Class_ViewModel model)
        {
            bool flag = false;
            if (model.ClassId > 0)
            {
                var oldModel = GetClassModule(model.ClassId);
                if (oldModel.Teacher_Id != model.Teacher_Id && model.Teacher_Id > 0 && oldModel.Teacher_Id > 0)
                {
                    class_PlanRepository.UpdatePlanTeacherIdRepository(model.Teacher_Id, model.ClassId);
                }
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Class_ViewModel.ClassName),model.ClassName},
                    { nameof(RB_Class_ViewModel.CouseId),model.CouseId},
                    { nameof(RB_Class_ViewModel.Teacher_Id),model.Teacher_Id},
                    { nameof(RB_Class_ViewModel.Assist_Id),model.Assist_Id},
                    { nameof(RB_Class_ViewModel.UpdateBy),model.UpdateBy},
                    { nameof(RB_Class_ViewModel.UpdateTime),model.UpdateTime},
                    { nameof(RB_Class_ViewModel.ClassPersion),model.ClassPersion},
                    { nameof(RB_Class_ViewModel.OpenTime),model.OpenTime},
                    { nameof(RB_Class_ViewModel.EndOrderTime),model.EndOrderTime},
                    { nameof(RB_Class_ViewModel.OriginalPrice),model.OriginalPrice},
                    { nameof(RB_Class_ViewModel.SellPrice),model.SellPrice},
                    { nameof(RB_Class_ViewModel.IsStepPrice),model.IsStepPrice},
                    { nameof(RB_Class_ViewModel.ClassRoomId),model.ClassRoomId},
                    { nameof(RB_Class_ViewModel.IsOpenCommission),model.IsOpenCommission},
                    { nameof(RB_Class_ViewModel.CommissionType),model.CommissionType},
                    { nameof(RB_Class_ViewModel.CommissionValue),model.CommissionValue},
                    { nameof(RB_Class_ViewModel.ClassHours),model.ClassHours},
                    { nameof(RB_Class_ViewModel.ClassStyle),model.ClassStyle},
                    { nameof(RB_Class_ViewModel.InnerRemark),model.InnerRemark},
                    { nameof(RB_Class_ViewModel.ClassType),model.ClassType},
                    { nameof(RB_Class_ViewModel.DefaultTimeJson),model.DefaultTimeJson},
                    { nameof(RB_Class_ViewModel.DateJson),model.DateJson},
                    { nameof(RB_Class_ViewModel.School_Id),model.School_Id},
                    { nameof(RB_Class_ViewModel.IsSubscribe),model.IsSubscribe},
                    { nameof(RB_Class_ViewModel.IsDeduction),model.IsDeduction},
                    { nameof(RB_Class_ViewModel.Point),model.Point},
                    { nameof(RB_Class_ViewModel.CourseClassType),model.CourseClassType},
                    { nameof(RB_Class_ViewModel.StudentNumType),model.StudentNumType},
                };
                flag = classRepository.Update(fileds, new WhereHelper(nameof(RB_Class_ViewModel.ClassId), model.ClassId));
            }
            else
            {
                var newId = classRepository.Insert(model);
                model.ClassId = newId;
                flag = newId > 0;
                var classLogModel = new Model.Entity.Log.RB_Class_Log()
                {
                    LogType = Common.Enum.Course.ClassLogTypeEnum.CreateClass,
                    LogContent = "创建班级",
                    ClassId = newId,
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    CreateBy = model.CreateBy,
                    CreateTime = System.DateTime.Now
                };
                classLogRepository.AddClassLogRepository(classLogModel);
            }

            #region 阶梯报价
            //未开启阶梯价格
            if (model.IsStepPrice == 0)
            {
                class_StepPriceRepository.DeleteClassStepPriceRepository(model.ClassId);
            }
            else//开启阶梯价格
            {
                var oldStepPriceList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { ClassId = model.ClassId });
                //以前没有阶梯报价信息【直接新增】
                if (oldStepPriceList == null || (oldStepPriceList != null && oldStepPriceList.Count == 0))
                {
                    if (model.ClassStepPriceList != null && model.ClassStepPriceList.Count > 0)
                    {
                        foreach (var item in model.ClassStepPriceList)
                        {
                            item.ClassStepPriceId = 0;
                            item.ClassId = model.ClassId;
                            item.Group_Id = model.Group_Id;
                            item.School_Id = model.School_Id;
                            class_StepPriceRepository.Insert(item);
                        }
                    }
                }
                else//以前有阶梯报价
                {
                    //现在没有阶梯报价了【直接删除以前的阶梯报价】
                    if (model.ClassStepPriceList == null || (model.ClassStepPriceList != null && model.ClassStepPriceList.Count == 0))
                    {
                        class_StepPriceRepository.DeleteClassStepPriceRepository(model.ClassId);
                    }
                    //找出差异的数据
                    var deleteList = oldStepPriceList.Where(qitem => !model.ClassStepPriceList.Any(oldItem => qitem.ClassStepPriceId == oldItem.ClassStepPriceId)).ToList();
                    foreach (var dItem in deleteList)
                    {
                        if (dItem.ClassStepPriceId > 0)
                        {
                            class_StepPriceRepository.Delete(dItem.ClassStepPriceId);
                        }
                    }
                    foreach (var priceItem in model.ClassStepPriceList)
                    {
                        priceItem.ClassId = model.ClassId;
                        priceItem.Group_Id = model.Group_Id;
                        priceItem.School_Id = model.School_Id;
                        if (priceItem.ClassStepPriceId == 0)
                        {
                            class_StepPriceRepository.Insert(priceItem);
                        }
                        else
                        {
                            class_StepPriceRepository.Update(priceItem);
                        }
                    }
                }
            }
            #endregion

            #region 班级计划
            //默认上课时间
            var defaultPlanTimeList = new List<RB_Class_Time_ViewModel>();
            foreach (var tItem in model.DefaultPlanTimeList)
            {
                defaultPlanTimeList.Add(new RB_Class_Time_ViewModel()
                {
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    ClassId = model.ClassId,
                    ClassPlanId = 0,
                    ClassTimeId = 0,
                    StartTime = tItem.StartTime,
                    EndTime = tItem.EndTime
                });
            }

            //班级上课计划列表
            List<RB_Class_Plan_ViewModel> classPlanList = CreateClassPlanList(model, defaultPlanTimeList);

            model.ClassPlanList = classPlanList;
            if (model.ClassPlanList != null && model.ClassPlanList.Count > 0)
            {
                foreach (var item in model.ClassPlanList)
                {
                    item.ClassPlanId = 0;
                    if (!class_PlanRepository.CheckExistsRepository(item))
                    {
                        //添加班级上课计划
                        var newClassPlanId = class_PlanRepository.Insert(item);
                        if (item.PlanTimeList != null && item.PlanTimeList.Count > 0)
                        {
                            foreach (var subItem in item.PlanTimeList)
                            {
                                subItem.ClassTimeId = 0;
                                subItem.ClassPlanId = newClassPlanId;
                                //添加班级上课计划的上课时间
                                class_TimeRepository.Insert(subItem);
                            }
                        }
                    }
                }
            }
            #endregion

            return flag;
        }

        /// <summary>
        /// 修改班级状态
        /// </summary>
        /// <param name="ClassStatus"></param>
        /// <param name="classId"></param>
        /// <returns></returns>
        public virtual bool SetClassStatusModule(ClassStatusEnum ClassStatus, int classId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
               { nameof(RB_Class_ViewModel.ClassStatus),(int)ClassStatus},
            };
            return classRepository.Update(fileds, new WhereHelper(nameof(RB_Class_ViewModel.ClassId), classId));
        }

        /// <summary>
        /// 更新班级完成进度
        /// </summary>
        /// <param name="classId">班级Id</param>
        /// <returns></returns>
        public virtual bool SetClassProcessModule(int classId)
        {
            int CompleteProgress = 0;//进度数
            var classModel = classRepository.GetEntity(classId);
            //班级完成的总分钟数
            var FinishMinutes = class_CheckRepository.GetClassFinishMinutesRepository(classId.ToString())?.FirstOrDefault()?.FinishMinutes ?? 0;
            if (FinishMinutes > 0)
            {
                //基础课时分钟数
                var BasicMinutes = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = classModel.Group_Id })?.BasicMinutes ?? 45;
                //完成课时数
                var finishHours = FinishMinutes / BasicMinutes;
                if (classModel.ClassHours > 0)
                {
                    CompleteProgress = Convert.ToInt32(finishHours / Convert.ToDecimal(classModel.ClassHours) * 100);
                }
                else if (classModel.ClassHours <= 0 && finishHours > 0)
                {
                    CompleteProgress = 100;
                }
            }
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
               { nameof(RB_Class_ViewModel.CompleteProgress),CompleteProgress},
            };
            return classRepository.Update(fileds, new WhereHelper(nameof(RB_Class_ViewModel.ClassId), classId));
        }

        /// <summary>
        /// 更新班级结课日期
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public bool UpdateClassEndDateModule(int classId)
        {
            return classRepository.UpdateClassEndDateRepository(classId);
        }

        /// <summary>
        /// 生成班级上课计划表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private List<RB_Class_Plan_ViewModel> CreateClassPlanList(RB_Class_ViewModel model, List<RB_Class_Time_ViewModel> defaultPlanTimeList)
        {
            var planList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel() { ClassId = model.ClassId, StartTime = DateTime.Now.ToString("yyyy-MM-dd") });
            if (planList != null && planList.Count > 0)
            {
                string ids = string.Join(",", planList.Select(qitem => qitem.ClassPlanId));
                if (!string.IsNullOrEmpty(ids))
                {
                    var flag1 = class_TimeRepository.DeleteClassTimeByPlanIdsRepository(ids);
                    var flag2 = class_PlanRepository.DeleteClassPlanRepository(ids);
                }
            }

            List<RB_Class_Plan_ViewModel> classPlanList = new List<RB_Class_Plan_ViewModel>();
            double totalMinutes = 0;
            foreach (var item in defaultPlanTimeList)
            {
                var startDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + item.StartTime + ":00");
                var endDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + item.EndTime + ":00");
                TimeSpan span = endDate.Subtract(startDate);
                if (span.TotalMinutes > 0)
                {
                    totalMinutes += span.TotalMinutes;
                }
            }
            //计算每天课时数
            var dayClassHour = totalMinutes / 45.0;
            if (dayClassHour > 0)
            {
                var totalDay = model.ClassHours / dayClassHour;
                var srartDate = model.OpenTime;
                switch (model.ClassStyle)
                {
                    //按周排课
                    case Common.Enum.Course.ClassStyleEnum.Week:
                        int i = 0;
                        while (classPlanList.Count < totalDay)
                        {
                            var newDate = srartDate.AddDays(i);
                            foreach (var item in model.WeekDayList)
                            {
                                switch (item)
                                {
                                    case "1":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Monday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                    case "2":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Tuesday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                    case "3":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Wednesday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                    case "4":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Thursday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                    case "5":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Friday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                    case "6":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Saturday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                    case "7":
                                        if (newDate.DayOfWeek == System.DayOfWeek.Sunday)
                                        {
                                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                                            {
                                                ClassDate = newDate,
                                                ClassId = model.ClassId,
                                                ClassPlanId = 0,
                                                ClassRoomId = model.ClassRoomId,
                                                Group_Id = model.Group_Id,
                                                School_Id = model.School_Id,
                                                PlanTimeList = defaultPlanTimeList,
                                                TeacherId = model.Teacher_Id,
                                            });
                                        }
                                        break;
                                }
                            }
                            i++;
                        }
                        break;
                    //按月排课
                    case Common.Enum.Course.ClassStyleEnum.Month:
                        int j = 0;
                        while (classPlanList.Count < totalDay)
                        {
                            var newDate = srartDate.AddDays(j);
                            foreach (var item in model.WeekDayList)
                            {
                                if (newDate.Day == Convert.ToInt32(item))
                                {
                                    classPlanList.Add(new RB_Class_Plan_ViewModel()
                                    {
                                        ClassDate = newDate,
                                        ClassId = model.ClassId,
                                        ClassPlanId = 0,
                                        ClassRoomId = model.ClassRoomId,
                                        Group_Id = model.Group_Id,
                                        School_Id = model.School_Id,
                                        PlanTimeList = defaultPlanTimeList,
                                        TeacherId = model.Teacher_Id,
                                    });
                                }
                            }
                            j++;
                        }
                        break;
                    //固定日期排课
                    case Common.Enum.Course.ClassStyleEnum.FixedDate:
                        foreach (var item in model.WeekDayList)
                        {
                            classPlanList.Add(new RB_Class_Plan_ViewModel()
                            {
                                ClassDate = Convert.ToDateTime(item),
                                ClassId = model.ClassId,
                                ClassPlanId = 0,
                                ClassRoomId = model.ClassRoomId,
                                Group_Id = model.Group_Id,
                                School_Id = model.School_Id,
                                PlanTimeList = defaultPlanTimeList,
                                TeacherId = model.Teacher_Id,
                            });
                        }
                        break;
                }
            }
            return classPlanList;
        }

        /// <summary>
        /// 根据班级编号获取班级详细信息
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public RB_Class_ViewModel GetClassModule(object ClassId)
        {
            var extModel = classRepository.GetEntity<RB_Class_ViewModel>(ClassId);
            if (extModel != null && extModel.ClassId > 0)
            {
                //课程梯度价格
                extModel.ClassStepPriceList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { ClassId = extModel.ClassId })?.ToList() ?? new List<RB_Class_StepPrice_ViewModel>();
                //课程计划上课日期
                extModel.ClassPlanList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel() { ClassId = extModel.ClassId })?.ToList() ?? new List<RB_Class_Plan_ViewModel>();
                //班级上课计划时间列表
                var timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel() { ClassId = extModel.ClassId })?.ToList() ?? new List<RB_Class_Time_ViewModel>();
                if (extModel.ClassPlanList != null && extModel.ClassPlanList.Count > 0 && timeList != null && timeList.Count > 0)
                {
                    foreach (var item in extModel.ClassPlanList)
                    {
                        item.PlanTimeList = timeList?.Where(qitem => qitem.ClassPlanId == item.ClassPlanId)?.ToList() ?? new List<RB_Class_Time_ViewModel>();
                    }
                }
                if (!string.IsNullOrEmpty(extModel.DefaultTimeJson))
                {
                    extModel.DefaultTimeList = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Class_Time_ViewModel>>(extModel.DefaultTimeJson);
                }
                if (!string.IsNullOrEmpty(extModel.DateJson) && extModel.ClassStyle != Common.Enum.Course.ClassStyleEnum.OnLine)
                {
                    extModel.WeekDayList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(extModel.DateJson);
                }
            }
            return extModel;
        }

        /// <summary>
        /// 删除班级
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public bool RemoveClassModule(object ClassId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Class_ViewModel.Status),(int)DateStateEnum.Delete},
            };
            return classRepository.Update(fileds, new WhereHelper(nameof(RB_Class_ViewModel.ClassId), ClassId));
        }

        /// <summary>
        /// 获取班级计划列表
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <param name="monthStr">月份</param>
        /// <returns></returns>
        public object GetClassPlanModule(int classId, string monthStr)
        {
            List<object> list = new List<object>();
            var timeList = new List<RB_Class_Time_ViewModel>();
            var planList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel() { ClassId = classId, QMonth = monthStr })?.OrderBy(qitem => qitem.ClassDate);
            if (planList != null && planList.Count() > 0)
            {
                string Ids = string.Join(",", planList.Select(qitem => qitem.ClassPlanId));
                if (!string.IsNullOrEmpty(Ids))
                {
                    timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel() { QClassPlanIds = Ids });
                }
                DateTime today = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                foreach (var item in planList)
                {
                    item.PlanTimeList = timeList?.Where(qitem => qitem.ClassPlanId == item.ClassPlanId)?.ToList();
                    list.Add(new
                    {
                        IsEndDate = item.ClassDate <= today,
                        item.ClassPlanId,
                        item.ClassId,
                        item.ClassDate,
                        ClassDateStr = Common.ConvertHelper.FormatDate(item.ClassDate),
                        item.ClassRoomId,
                        item.RoomName,
                        item.TeacherId,
                        item.TeacherName,
                        item.UserIcon,
                        TimeList = item?.PlanTimeList?.Select(qitem => new { qitem.ClassTimeId, qitem.StartTime, qitem.EndTime })?.OrderBy(qitem => qitem.StartTime)
                    });
                }
            }
            return list;
        }

        /// <summary>
        /// 根据计划编号删除上课计划
        /// </summary>
        /// <param name="ClassPlanId"></param>
        /// <param name="UserInfo">用户信息</param>
        /// <returns></returns>
        public bool RemoveClassPlanModule(int ClassPlanId, UserInfo UserInfo)
        {
            var planModel = class_PlanRepository.GetEntity(ClassPlanId);
            classLogRepository.AddClassLogRepository(new Model.Entity.Log.RB_Class_Log()
            {
                LogType = Common.Enum.Course.ClassLogTypeEnum.Class,
                LogContent = "删除【" + Common.ConvertHelper.FormatDate(planModel?.ClassDate) + "】上课计划",
                ClassId = planModel.ClassId,
                CreateBy = UserInfo.Id,
                Group_Id = UserInfo.Group_Id,
                School_Id = UserInfo.School_Id,
            });
            UpdateClassEndDateModule(planModel.ClassId);
            return class_PlanRepository.DeleteOne(new WhereHelper(nameof(RB_Class_Plan_ViewModel.ClassPlanId), ClassPlanId));
        }

        /// <summary>
        /// 检查班级上课日期是否存在
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool CheckPlanModule(RB_Class_Plan_ViewModel extModel)
        {
            List<WhereHelper> list = new List<WhereHelper>()
            {
                new WhereHelper (nameof(RB_Class_Plan_ViewModel.ClassId),extModel.ClassId),
                new WhereHelper (nameof(RB_Class_Plan_ViewModel.ClassDate),extModel.ClassDate),
                new WhereHelper (nameof(RB_Class_Plan_ViewModel.Status),(int)DateStateEnum.Normal),
            };
            if (extModel.ClassPlanId > 0)
            {
                list.Add(new WhereHelper(nameof(RB_Class_Plan_ViewModel.ClassPlanId), extModel.ClassPlanId, OperatorEnum.NotEqual));
            }
            return class_PlanRepository.Exists(list);
        }

        /// <summary>
        /// 新增修改班级上课计划
        /// </summary>
        /// <param name="extModel"></param>
        /// <param name="createBy">操作人</param>
        /// <returns></returns>
        public virtual bool SetClassPlanModule(RB_Class_Plan_ViewModel extModel, int createBy)
        {
            bool flag;
            string logContent = "";
            if (extModel.ClassPlanId > 0)
            {
                var oldPlanModel = class_PlanRepository.GetEntity(extModel.ClassPlanId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Class_Plan_ViewModel.ClassRoomId),extModel.ClassRoomId },
                    {nameof(RB_Class_Plan_ViewModel.TeacherId),extModel.TeacherId },
                    {nameof(RB_Class_Plan_ViewModel.ClassDate),extModel.ClassDate },
                };

                if (oldPlanModel.ClassRoomId != extModel.ClassRoomId)
                {
                    string roomIds = oldPlanModel.ClassRoomId + "," + extModel.ClassRoomId;
                    var roomList = class_RoomRepository.GetClassRoomListRepository(new RB_Class_Room_ViewModel() { QRoomIds = roomIds });
                    logContent += string.Format(",教室由【{0}】修改为【{1}】.",
                        (roomList?.Where(qitem => qitem.RoomId == oldPlanModel.ClassRoomId)?.FirstOrDefault()?.RoomName ?? ""),
                        (roomList?.Where(qitem => qitem.RoomId == extModel.ClassRoomId)?.FirstOrDefault()?.RoomName ?? "")
                        );
                }
                if (oldPlanModel.TeacherId != extModel.TeacherId)
                {
                    string tIds = oldPlanModel.TeacherId + "," + extModel.TeacherId;
                    var teacherList = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel() { QTIds = tIds });
                    logContent += string.Format(",讲师由【{0}】修改为【{1}】.",
                        (teacherList?.Where(qitem => qitem.TId == oldPlanModel.TeacherId)?.FirstOrDefault()?.TeacherName ?? ""),
                        (teacherList?.Where(qitem => qitem.TId == extModel.TeacherId)?.FirstOrDefault()?.TeacherName ?? "")
                        );
                }
                if (oldPlanModel.ClassDate != extModel.ClassDate)
                {
                    logContent += string.Format(",日期由【{0}】修改为【{1}】.", Common.ConvertHelper.FormatDate(oldPlanModel.ClassDate), Common.ConvertHelper.FormatDate(extModel.ClassDate));
                }

                flag = class_PlanRepository.Update(fileds, new WhereHelper(nameof(RB_Class_Plan_ViewModel.ClassPlanId), extModel.ClassPlanId));
            }
            else
            {
                var newId = class_PlanRepository.Insert(extModel);
                extModel.ClassPlanId = newId;
                flag = newId > 0;
                logContent = "新增【" + Common.ConvertHelper.FormatDate(extModel?.ClassDate) + "】上课计划";
            }
            var oldPlanList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel()
            {
                ClassId = extModel.ClassId,
                ClassPlanId = extModel.ClassPlanId,
            });

            //原来没有计划
            if (oldPlanList == null || (oldPlanList != null && oldPlanList.Count == 0))
            {
                foreach (var item in extModel.PlanTimeList)
                {
                    item.ClassId = extModel.ClassId;
                    item.ClassPlanId = extModel.ClassPlanId;
                    item.Group_Id = extModel.Group_Id;
                    item.School_Id = extModel.School_Id;
                    item.ClassTimeId = 0;
                    flag = class_TimeRepository.Insert(item) > 0;
                }
            }
            //以前有计划
            else
            {
                //现在没有设置时间【直接删除以前的时间】
                if (extModel.PlanTimeList == null || (extModel.PlanTimeList != null && extModel.PlanTimeList.Count == 0))
                {
                    class_TimeRepository.DeleteClassTimeByPlanIdsRepository(extModel.ClassPlanId.ToString());
                }
                //找出差异的数据
                var deleteList = oldPlanList.Where(qitem => !extModel.PlanTimeList.Any(oldItem => qitem.ClassTimeId == oldItem.ClassTimeId)).ToList();
                foreach (var dItem in deleteList)
                {
                    if (dItem.ClassTimeId > 0)
                    {
                        logContent += string.Format(",删除{0}上课时间【{1} - {2}】", Common.ConvertHelper.FormatDate(extModel.ClassDate), dItem.StartTime, dItem.EndTime);
                        class_TimeRepository.Delete(dItem.ClassTimeId);
                    }
                }
                foreach (var item in extModel.PlanTimeList)
                {
                    item.ClassId = extModel.ClassId;
                    item.ClassPlanId = extModel.ClassPlanId;
                    item.Group_Id = extModel.Group_Id;
                    item.School_Id = extModel.School_Id;
                    if (item.ClassTimeId == 0)
                    {
                        logContent += string.Format(",新增{0}上课时间【{1} - {2}】", Common.ConvertHelper.FormatDate(extModel.ClassDate), item.StartTime, item.EndTime);
                        flag = class_TimeRepository.Insert(item) > 0;
                    }
                    else
                    {
                        var oldModel = oldPlanList?.Where(qitem => qitem.ClassTimeId == item.ClassTimeId)?.FirstOrDefault();
                        if (oldModel != null)
                        {
                            if (oldModel.StartTime != item.StartTime)
                            {
                                logContent += string.Format(",{0}上课开始时间由【{1}】修改为【{2}】", Common.ConvertHelper.FormatDate(extModel.ClassDate), oldModel.StartTime, item.EndTime);
                            }
                            if (oldModel.EndTime != item.EndTime)
                            {
                                logContent += string.Format(",{0}上课结束时间由【{1}】修改为【{2}】", Common.ConvertHelper.FormatDate(extModel.ClassDate), oldModel.EndTime, item.EndTime);
                            }
                        }
                        flag = class_TimeRepository.Update(item);
                    }
                }
            }
            if (!string.IsNullOrEmpty(logContent))
            {
                classLogRepository.AddClassLogRepository(
                    new Model.Entity.Log.RB_Class_Log()
                    {
                        LogType = Common.Enum.Course.ClassLogTypeEnum.Class,
                        LogContent = logContent,
                        ClassId = extModel.ClassId,
                        Group_Id = extModel.Group_Id,
                        School_Id = extModel.School_Id,
                        CreateBy = createBy
                    });
            }
            return flag;
        }

        /// <summary>
        /// 获取班级学员列表
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <returns></returns>
        public object GetClassStudentListModule(int classId, int school_Id, int group_Id)
        {
            List<object> list = new List<object>();
            var orderStudentList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel()
            {
                ClassId = classId,
                Group_Id = group_Id,
                School_Id = school_Id
            }).Where(x => x.GuestState == 1).ToList();
            var classModel = GetClassModule(classId);
            var courseModel = courseRepository.GetEntity((classModel?.CouseId ?? 0));
            if (orderStudentList != null && orderStudentList.Count > 0)
            {
                foreach (var item in orderStudentList)
                {
                    list.Add(new
                    {
                        UserIcon = "",
                        item.Id,
                        SexStr = item.Sex == 1 ? "男" : "女",
                        item.GuestName,
                        item.Age,
                        CreateTimeStr = Common.ConvertHelper.FormatTime(item.CreateTime),
                        item.Mobile,
                        item.OrderId,
                        ClassHours = classModel?.ClassHours ?? 0,
                        IsRenew = courseModel?.IsRenew ?? 0
                    });
                }
            }
            return list;
        }


        /// <summary>
        /// 根据班级id获取订单学员信息
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public List<RB_Order_Guest_ViewModel> GetOrderGuest(RB_Order_Guest_ViewModel model)
        {
            return order_GuestRepository.GetList(model);
        }

        /// <summary>
        /// 更新学生的退课信息
        /// </summary>
        /// <param name="Ids"></param>
        /// <param name="DropOutRemark"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool UpdateClassStudentDropOutModule(string ids, string dropOutRemark, int classId, int createBy, int group_Id, int school_Id, string studentName)
        {
            bool flag = false;
            foreach (var item in ids.Split(","))
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Order_Guest_ViewModel.GuestState),2},
                    {nameof(RB_Order_Guest_ViewModel.DropOutRemark),dropOutRemark}
                };

                    //写日志
                    flag = order_GuestRepository.Update(fileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), item));
                }
            }
            if (flag)
            {
                var classLogModel = new Model.Entity.Log.RB_Class_Log()
                {
                    LogType = Common.Enum.Course.ClassLogTypeEnum.DropOutStudent,
                    LogContent = studentName + " 学员因" + dropOutRemark + "退课",
                    ClassId = classId,
                    Group_Id = group_Id,
                    School_Id = school_Id,
                    CreateBy = createBy,
                    CreateTime = System.DateTime.Now
                };
                classLogRepository.AddClassLogRepository(classLogModel);
            }
            return flag;
        }

        /// <summary>
        /// 更新学生的退课信息
        /// </summary>
        /// <param name="Ids"></param>
        /// <param name="DropOutRemark"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool AddClassStudentDropOutModule(RB_Order_Guest_ViewModel model, string CreateName)
        {
            //写日志
            bool flag = order_GuestRepository.Insert(model) > 0;
            if (flag)
            {
                //更新学生的状态
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_ViewModel.StuStatus),3},
                };

                //写日志
                studentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_ViewModel.StuId), model.StudentId));
                var classLogModel = new Model.Entity.Log.RB_Class_Log()
                {
                    LogType = Common.Enum.Course.ClassLogTypeEnum.AddStudent,
                    LogContent = CreateName + "邀请  " + model.GuestName + " 加入班级",
                    ClassId = model.ClassId,
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    CreateBy = model.CreateBy,
                    CreateTime = System.DateTime.Now
                };
                classLogRepository.AddClassLogRepository(classLogModel);
            }
            return flag;
        }


        /// <summary>
        /// 新增签到
        /// </summary>
        /// <param name="Ids"></param>
        /// <param name="DropOutRemark"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool AddClassCheckModule(List<RB_Class_Check_ViewModel> list)
        {
            //写日志
            bool flag = true;
            foreach (var item in list)
            {
                if (flag)
                {
                    if (item.ClassCheckId > 0)
                    {
                        flag = classCheckRepository.Update(item);
                    }
                    else
                    {
                        flag = classCheckRepository.Insert(item) > 0;
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取班级上课记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Plan_ViewModel> GetClassPlanLogPageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Class_Plan_ViewModel query)
        {
            return class_PlanRepository.GetClassPlanLogPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }


        /// <summary>
        /// 获取班级上课计划
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Plan_ViewModel> GetClassPlanModelRepository(RB_Class_Plan_ViewModel query)
        {
            return class_PlanRepository.GetClassPlanModelRepository(query);
        }

        /// <summary>
        /// 获取每天签到记录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Check_ViewModel> GetClassCheckListRepository(RB_Class_Check_ViewModel query)
        {
            return classCheckRepository.GetClassCheckListRepository(query);
        }



        /// <summary>
        /// 获取教室列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Check_ViewModel> GetClassCheckList(RB_Class_Check_ViewModel query)
        {
            return classCheckRepository.GetClassCheckList(query);
        }


        /// <summary>
        /// 获取班级上课计划列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Plan_ViewModel> GetClassPlanListRepository(RB_Class_Plan_ViewModel query)
        {
            return class_PlanRepository.GetClassPlanListRepository(query);
        }

        /// <summary>
        /// 获取学生列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_ViewModel> GetStudentListRepository(RB_Student_ViewModel query)
        {
            return studentRepository.GetStudentListRepository(query);
        }


        #region 班级收支信息
        /// <summary>
        /// 获取班级收支信息列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_Finance_ViewModel> GetClassFinanceListRepository(RB_Class_Finance_ViewModel query)
        {
            return classFinanceRepository.GetClassFinanceListRepository(query);
        }

        /// <summary>
        /// 新增/修改班级收支设置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetClassFinance(RB_Class_Finance_ViewModel model)
        {

            var oldModel = GetClassFinanceListRepository(model).FirstOrDefault();
            if (oldModel == null || oldModel.FinanceId == 0)
            {
                return classFinanceRepository.Insert(model) > 0;
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Class_Finance_ViewModel.IsOpen),model.IsOpen},
                    {nameof(RB_Class_Finance_ViewModel.UpdateBy),model.UpdateBy},
                    {nameof(RB_Class_Finance_ViewModel.UpdateTime),model.UpdateTime}
                };
                return order_GuestRepository.Update(fileds, new WhereHelper(nameof(RB_Class_Finance_ViewModel.FinanceId), oldModel.FinanceId));
            }

        }

        #endregion

        #region 老师教案
        /// <summary>
        /// 新增/修改老师教案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool SetClassLessPlan(Class_LessonPlan_ViewModel model)
        {

            bool flag = false;
            if (model.LessonPlanList != null && model.LessonPlanList.Any())
            {
                foreach (var item in model.LessonPlanList)
                {
                    int LessonPlanId = 0;
                    item.ClassId = model.ClassId;
                    item.ClassPlanId = model.ClassPlanId;
                    item.Group_Id = model.Group_Id;
                    item.School_Id = model.School_Id;
                    item.IsTemplate = model.IsTemplate;
                    item.CourseNum = model.CourseNum;
                    item.LessonPlan = model.LessonPlan;
                    item.CreateBy = model.CreateBy;
                    item.CreateTime = model.CreateTime;
                    item.UpdateBy = model.UpdateBy;
                    item.UpdateTime = model.UpdateTime;
                    if (item.LessonPlanId > 0)//更新
                    {
                        LessonPlanId = item.LessonPlanId;
                        flag = ClassLessonPlanRepository.Update(item);
                        //删除之前有，现在没有的数据
                        var detailsList = GetLessonPlanDetailsListRepository(new RB_Class_LessonPlanDetails_ViewModel { Group_Id = item.Group_Id, School_Id = item.School_Id, LessonPlanId = item.LessonPlanId });
                        if (item.LessonPlanDetailsList != null && item.LessonPlanDetailsList.Any())
                        {
                            List<int> detailsList1 = detailsList.Select(x => x.LessonPlanDetailsId).ToList();
                            List<int> detailsList2 = item.LessonPlanDetailsList.Where(x => x.LessonPlanDetailsId > 0).Select(x => x.LessonPlanDetailsId).ToList();
                            var deleDetailsList = detailsList1.Except(detailsList2).ToList();
                            foreach (var itemDele in deleDetailsList)
                            {
                                ClassLessonPlanDetailsRepository.Delete(detailsList.Where(x => x.LessonPlanDetailsId == itemDele).FirstOrDefault());
                            }
                        }
                        else
                        {
                            ClassLessonPlanDetailsRepository.DeleteBatch(detailsList);
                        }

                        //删除之前有，现在没有的数据
                        var projectsList = GetLessonPlanProjectsListRepository(new RB_Class_LessonPlanProjects_ViewModel { Group_Id = item.Group_Id, School_Id = item.School_Id, LessonPlanId = item.LessonPlanId });
                        if (item.LessonPlanDetailsList != null && item.LessonPlanDetailsList.Any())
                        {
                            List<int> projectsList1 = projectsList.Select(x => x.LessonPlanProjectsId).ToList();
                            List<int> projectsList2 = item.LessonPlanProjectsList.Where(x => x.LessonPlanProjectsId > 0).Select(x => x.LessonPlanProjectsId).ToList();
                            var deleProjectsList = projectsList1.Except(projectsList2).ToList();
                            foreach (var itemDele in deleProjectsList)
                            {
                                ClassLessonPlanProjectsRepository.Delete(projectsList.Where(x => x.LessonPlanProjectsId == itemDele).FirstOrDefault());
                            }
                        }
                        else
                        {
                            ClassLessonPlanProjectsRepository.DeleteBatch(projectsList);
                        }
                    }
                    else
                    {
                        LessonPlanId = ClassLessonPlanRepository.Insert(item);
                        flag = LessonPlanId > 0;
                    }

                    foreach (var itemDetails in item.LessonPlanDetailsList)
                    {
                        itemDetails.LessonPlanId = LessonPlanId;
                        itemDetails.School_Id = item.School_Id;
                        itemDetails.Group_Id = item.Group_Id;
                        if (itemDetails.LessonPlanDetailsId == 0)
                        {
                            ClassLessonPlanDetailsRepository.Insert(itemDetails);
                        }
                        else
                        {
                            ClassLessonPlanDetailsRepository.Update(itemDetails);
                        }
                    }
                    foreach (var itemProjects in item.LessonPlanProjectsList)
                    {
                        itemProjects.LessonPlanId = LessonPlanId;
                        itemProjects.School_Id = item.School_Id;
                        itemProjects.Group_Id = item.Group_Id;
                        if (itemProjects.LessonPlanProjectsId == 0)
                        {
                            ClassLessonPlanProjectsRepository.Insert(itemProjects);
                        }
                        else
                        {
                            ClassLessonPlanProjectsRepository.Update(itemProjects);
                        }
                    }
                }
            }

            return flag;
        }
        /// <summary>
        /// 新增/修改老师教案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool UpdateClassLessPlan(Class_LessonPlan_ViewModel model)
        {
            bool flag = false;
            if (model.LessonPlanList != null && model.LessonPlanList.Any())
            {
                foreach (var item in model.LessonPlanList)
                {
                    foreach (var itemDetails in item.LessonPlanDetailsList)
                    {
                        Dictionary<string, object> fileds = new Dictionary<string, object>()
                        {
                            {nameof(RB_Class_LessonPlanDetails_ViewModel.Summary),itemDetails.Summary}
                        };
                        ClassLessonPlanDetailsRepository.Update(fileds, new WhereHelper(nameof(RB_Class_LessonPlanDetails_ViewModel.LessonPlanDetailsId), itemDetails.LessonPlanDetailsId));
                    }
                }
                return true;
            }

            return flag;
        }

        /// <summary>
        /// 获取老师教案详情分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_LessonPlanDetails_ViewModel> GetLessonPlanDetailsListRepository(RB_Class_LessonPlanDetails_ViewModel query)
        {
            return ClassLessonPlanDetailsRepository.GetLessonPlanDetailsListRepository(query);
        }


        /// <summary>
        /// 获取老师教案项目分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_LessonPlanProjects_ViewModel> GetLessonPlanProjectsListRepository(RB_Class_LessonPlanProjects_ViewModel query)
        {
            return ClassLessonPlanProjectsRepository.GetLessonPlanProjectsListRepository(query);
        }

        /// <summary>
        /// 获取老师教案分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_LessonPlan_ViewModel> GetLessonPlanPageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Class_LessonPlan_ViewModel query)
        {
            return ClassLessonPlanRepository.GetLessonPlanPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }


        /// <summary>
        /// 获取老师教案列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Class_LessonPlan_ViewModel> GetLessonPlanListRepository(RB_Class_LessonPlan_ViewModel query)
        {
            return ClassLessonPlanRepository.GetLessonPlanListRepository(query);
        }





        /// <summary>
        /// 获取老师计划列表
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <param name="monthStr">月份</param>
        /// <returns></returns>
        public List<RB_Class_Plan_ViewModel> GetTeacherPlanModule(RB_Class_ViewModel model)
        {
            var timeList = new List<RB_Class_Time_ViewModel>();
            var planList = class_PlanRepository.GetTeacherPlanListRepository(new RB_Class_Plan_ViewModel() { School_Id = model.School_Id, TeacherId = model.Teacher_Id, Group_Id = model.Group_Id, StartTime = model.StartTime, EndTime = model.EndTime });
            if (planList != null && planList.Any())
            {
                string Ids = string.Join(",", planList.Select(qitem => qitem.ClassPlanId));
                if (!string.IsNullOrEmpty(Ids))
                {
                    timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel() { QClassPlanIds = Ids });
                }
                string ClassIds = string.Join(",", planList.GroupBy(x => x.ClassId).Select(x => x.Key));
                var orderStudentList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel()
                {
                    ClassIds = ClassIds,
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id
                }).Where(x => x.GuestState == 1).ToList();
                foreach (var item in planList)
                {
                    item.PlanTimeList = new List<RB_Class_Time_ViewModel>();
                    item.PlanTimeList = timeList.Where(x => x.ClassPlanId == item.ClassPlanId).ToList();
                    item.GuestList = new List<RB_Order_Guest_ViewModel>();
                    item.GuestList = orderStudentList.Where(x => x.ClassId == item.ClassId).ToList();
                }
            }
            return planList;
        }

        /// <summary>
        /// 获取备案评论分页列表
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowsCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Class_LessonComment_ViewModel> GetLessonCommentList(RB_Class_LessonComment_ViewModel query)
        {
            return classLessonCommentRepository.GetLessonCommentList(query);
        }

        /// <summary>
        /// 评论/删除评论
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetLessonComment(RB_Class_LessonComment_ViewModel model)
        {
            if (model.LessonCommentId == 0)
            {
                return classLessonCommentRepository.Insert(model) > 0;
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Class_LessonComment_ViewModel.Status),1}
                };
                return classLessonCommentRepository.Update(fileds, new WhereHelper(nameof(RB_Class_LessonComment_ViewModel.LessonCommentId), model.LessonCommentId));
            }
        }

        #endregion

        #region 根据学生id获取最近的上课信息
        /// <summary>
        /// 根据学生id获取教师账户
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetListByStudentId(int Student_Id, int Group_Id)
        {
            var list = classRepository.GetListByStudentId(Student_Id, Group_Id);
            if (list != null && list.Any())
            {
                string classPlanIds = string.Join(",", list.Select(x => x.ClassPlanId));
                var timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel { QClassPlanIds = classPlanIds, Group_Id = Group_Id });
                if (timeList != null && timeList.Any())
                {
                    foreach (var item in list)
                    {
                        item.ClassTimeList = new List<RB_Class_Time_ViewModel>();
                        item.ClassTimeList = timeList.Where(x => x.ClassPlanId == item.ClassPlanId).ToList();
                        item.ClassTimeList.ForEach(x => x.NewPlanDateTime = item.ClassDate.Value.ToString("yyyy-MM-dd") + " " + x.StartTime);
                    }
                }
            }
            return list;
        }



        /// <summary>
        /// 获取学生上课计划列表
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <param name="monthStr">月份</param>
        /// <returns></returns>
        public List<RB_Class_Plan_ViewModel> GetStudentPlanModule(RB_Class_Plan_ViewModel model)
        {
            var timeList = new List<RB_Class_Time_ViewModel>();
            var planList = class_PlanRepository.GetStudentPlanListRepository(model);
            if (planList != null && planList.Any())
            {
                string Ids = string.Join(",", planList.Select(qitem => qitem.ClassPlanId));
                if (!string.IsNullOrEmpty(Ids))
                {
                    timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel() { QClassPlanIds = Ids });
                }
                string ClassIds = string.Join(",", planList.GroupBy(x => x.ClassId).Select(x => x.Key));
                //var orderStudentList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel()
                //{
                //    ClassIds = ClassIds,
                //    Group_Id = model.Group_Id,
                //    School_Id = model.School_Id
                //}).Where(x => x.GuestState == 1).ToList();
                foreach (var item in planList)
                {
                    item.PlanTimeList = new List<RB_Class_Time_ViewModel>();
                    item.PlanTimeList = timeList.Where(x => x.ClassPlanId == item.ClassPlanId).ToList();
                    //item.GuestList = new List<RB_Order_Guest_ViewModel>();
                    //item.GuestList = orderStudentList.Where(x => x.ClassId == item.ClassId).ToList();
                }
            }
            return planList;
        }


        /// <summary>
        /// 获取app约课
        /// </summary>
        /// <param name="Group_Id"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetStuAppointment(int Group_Id)
        {
            return classRepository.GetStuAppointment(Group_Id);
        }


        #endregion


        #region  教师上课挂件查询
        /// <summary>
        /// 获取班级上课时间
        /// </summary>
        /// <param name="classIds"></param>
        /// <returns></returns>
        public List<RB_Class_Time_Extend> GetClassTimeByRoomId(int RoomId, int Group_Id)
        {
            return class_TimeRepository.GetClassTimeByRoomId(RoomId, Group_Id);
        }

        public int GetNowClassHours(RB_Class_Time_Extend model)
        {
            int classHours = 0;
            //班级完成的总分钟数
            var FinishMinutes = class_CheckRepository.GetClassFinishMinutesRepository(model.ClassId.ToString())?.FirstOrDefault()?.FinishMinutes ?? 0;
            //基础课时分钟数
            var BasicMinutes = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = model.Group_Id })?.BasicMinutes ?? 45;

            var nowHours = model.NewEndPlanDateTime.Value.Subtract(model.NewPlanDateTime.Value).TotalSeconds;
            if (FinishMinutes > 0)
            {
                //完成课时数
                classHours = Convert.ToInt32((FinishMinutes + Convert.ToDecimal(nowHours)) / BasicMinutes);
            }
            else
            {
                classHours = Convert.ToInt32(FinishMinutes / BasicMinutes);
            }
            return classHours;

        }


        /// <summary>
        /// 更新课堂随拍
        /// </summary>
        /// <param name="SuiPai"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateTimeSuiPai(string SuiPai, int Id)
        {

            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Class_Time_ViewModel.SuiPai),SuiPai},
            };
            return class_TimeRepository.Update(fileds, new WhereHelper(nameof(RB_Class_Time_ViewModel.ClassTimeId), Id));
        }


        /// <summary>
        /// 更新课堂上课状态
        /// </summary>
        /// <param name="SuiPai"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateTimeClassStatus(int classStatus, int Id)
        {

            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Class_Time_ViewModel.ClassStatus),classStatus},
            };
            return class_TimeRepository.Update(fileds, new WhereHelper(nameof(RB_Class_Time_ViewModel.ClassTimeId), Id));
        }

        /// <summary>
        /// 更新课堂视频
        /// </summary>
        /// <param name="SuiPai"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateTimeClassVideo(string videoUrl, int Id)
        {

            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Class_Time_ViewModel.VideoUrl),videoUrl},
            };
            return class_TimeRepository.Update(fileds, new WhereHelper(nameof(RB_Class_Time_ViewModel.ClassTimeId), Id));
        }
        #endregion
    }
}
