using Edu.Model.Entity.EduTask;
using Edu.Model.ViewModel.EduTask;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Edu.Common.Enum.Course;
using System.Threading.Tasks;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Grade;
using Edu.Repository.Grade;

namespace Edu.Repository.EduTask
{
    /// <summary>
    /// 上课计划调整仓储层
    /// </summary>
    public class RB_Change_ClassPlanRepository : BaseRepository<RB_Change_ClassPlan>
    {
        /// <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_RoomRepository class_RoomRepository = new RB_Class_RoomRepository();

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

        /// <summary>
        /// 教务单据仓储层对象
        /// </summary>
        private readonly RB_Education_ReceiptRepository education_ReceiptRepository = new RB_Education_ReceiptRepository();
        /// <summary>
        /// 课程日志记录表
        /// </summary>
        private readonly Log.RB_Class_LogRepository classLogRepository = new Log.RB_Class_LogRepository();
       
        /// <summary>
        /// 获取调课计划列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Change_ClassPlan_ViewModel> GetChangeClassPlanListRepository(RB_Change_ClassPlan_ViewModel query)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@" 
SELECT A.*,IFNULL(B.ClassName,'') AS ClassName
FROM RB_Change_ClassPlan AS A LEFT JOIN rb_class AS B ON A.ClassId=B.ClassId
WHERE 1=1
");
            if (query != null)
            {
                if (!string.IsNullOrEmpty(query.Q_Change_ClassPlan_Ids))
                {
                    builder.AppendFormat(@" AND A.{0} IN ({1}) ", nameof(RB_Change_ClassPlan_ViewModel.Id), query.Q_Change_ClassPlan_Ids);
                }
            }
            return Get<RB_Change_ClassPlan_ViewModel>(builder.ToString()).ToList();
        }


        /// <summary>
        /// 审核通过后更新调课信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateChangeClassPlan(object Id)
        {
            //查询当前调课信息
            bool flag = false;
            var receiptModel = education_ReceiptRepository.GetEntity(Id);
            if (receiptModel == null || receiptModel.Id == 0)
            {
                return false;
            }
            if (receiptModel.ReceiptType != Common.Enum.Finance.ReceiptTypeEnum.ChangeClass)
            {
                return false;
            }
            var model = GetEntity(receiptModel.RelationId);
            if (model == null || model.Id == 0)
            {
                return false;
            }
            else
            {//更新信息 
                string logContent = "";
                StringBuilder builder = new StringBuilder();

                List<Model.Entity.Log.RB_Class_Log> classLogList = new List<Model.Entity.Log.RB_Class_Log>();
                if (model.MoveType == 1)//固定日期
                {
                    List<ChangePlanItem> oldChangePlanItemList = new List<ChangePlanItem>();
                    List<ChangePlanItem> newChangePlanItemList = new List<ChangePlanItem>();
                    //原数据
                    if (!string.IsNullOrWhiteSpace(model.SourceData))
                    {
                        oldChangePlanItemList = Common.Plugin.JsonHelper.DeserializeObject<List<ChangePlanItem>>(model.SourceData);
                    }
                    //目标数据
                    if (!string.IsNullOrWhiteSpace(model.TargetData))
                    {
                        newChangePlanItemList = Common.Plugin.JsonHelper.DeserializeObject<List<ChangePlanItem>>(model.TargetData);
                    }
                    if (model.ChangeType == 1)//1.调课
                    {
                        foreach (var item in oldChangePlanItemList)
                        {
                            var newChangePlanItemModel = newChangePlanItemList.Where(x => x.ClassPlanId == item.ClassPlanId).FirstOrDefault();
                            if (item.ClassDate != newChangePlanItemModel.ClassDate)
                            {
                                logContent += string.Format("日期由【{0}】修改为【{1}】.", Common.ConvertHelper.FormatDate(item.ClassDate), Common.ConvertHelper.FormatDate(newChangePlanItemModel.ClassDate));
                                builder.AppendFormat(" update RB_Class_Plan SET  ClassDate='{0}' where ClassPlanId ={1};", Common.ConvertHelper.FormatDate(newChangePlanItemModel.ClassDate), item.ClassPlanId);
                            }
                            foreach (var itemOldTime in item.PlanTimeList)//修改或者删除之前的
                            {
                                var newTimeModel = newChangePlanItemModel.PlanTimeList.Where(x => x.ClassTimeId > 0 && x.ClassTimeId == itemOldTime.ClassTimeId).FirstOrDefault();//以前与现在都有只是修改了日期
                                if (newTimeModel != null && newTimeModel.ClassTimeId > 0)
                                {
                                    if (newTimeModel.StartTime != itemOldTime.StartTime)
                                    {
                                        logContent += string.Format("{0}上课开始时间由【{1}】修改为【{2}】.", Common.ConvertHelper.FormatDate(newChangePlanItemModel.ClassDate), itemOldTime.StartTime, newTimeModel.EndTime);
                                    }
                                    if (newTimeModel.EndTime != itemOldTime.EndTime)
                                    {
                                        logContent += string.Format("{0}上课结束时间由【{1}】修改为【{2}】.", Common.ConvertHelper.FormatDate(newChangePlanItemModel.ClassDate), itemOldTime.EndTime, newTimeModel.EndTime);
                                    }
                                    if (newTimeModel.StartTime != itemOldTime.StartTime || newTimeModel.EndTime != itemOldTime.EndTime)
                                    {
                                        builder.AppendFormat(" update rb_class_time SET  StartTime='{0}' ,EndTime='{1}' where ClassTimeId ={2};", newTimeModel.StartTime, newTimeModel.EndTime, newTimeModel.ClassTimeId);
                                    }
                                }
                                else
                                {
                                    builder.AppendFormat(" DELETE  FROM  rb_class_time where classtimeId  in({0});", itemOldTime.ClassTimeId);
                                    logContent += string.Format("删除{0}上课时间【{1}】-【{2}】.", Common.ConvertHelper.FormatDate(item.ClassDate), itemOldTime.StartTime, itemOldTime.EndTime);
                                }
                            }
                            foreach (var itemNewTime in newChangePlanItemModel.PlanTimeList.Where(x => x.ClassTimeId == 0))//新增上课时间
                            {
                                builder.AppendFormat("INSERT into rb_class_time (ClassId,ClassPlanId,StartTime,EndTime,Group_Id,School_Id,ClassStatus)VALUES({0},{1},'{2}','{3}',{4},{5},{6});", model.ClassId, item.ClassPlanId, itemNewTime.StartTime, itemNewTime.EndTime, model.Group_Id, model.School_Id, 0);
                                logContent += string.Format("{0}新增上课开始时间【{1}】-【{2}】.", Common.ConvertHelper.FormatDate(item.ClassDate), itemNewTime.StartTime, itemNewTime.EndTime);
                            }
                        }
                    }
                    else if (model.ChangeType == 2 || model.ChangeType == 3)//更新老师或者更新教室
                    {

                        if (model.ChangeType == 2)
                        {
                            builder.AppendFormat(" update RB_Class_Plan SET  TeacherId={0} where ClassPlanId in({1})", newChangePlanItemList.FirstOrDefault().TeacherId, string.Join(",", oldChangePlanItemList.Select(x => x.ClassPlanId)));
                            string tIds = string.Join(",", oldChangePlanItemList.Select(x => x.TeacherId)) + "," + newChangePlanItemList.FirstOrDefault().TeacherId;
                            var teacherList = teacherRepository.GetTeacherListRepository(new Model.ViewModel.User.RB_Teacher_ViewModel() { QTIds = tIds });
                            foreach (var item in oldChangePlanItemList)
                            {

                                logContent += string.Format(Common.ConvertHelper.FormatDate(item.ClassDate) + "的讲师由【{0}】修改为【{1}】.",
                               (teacherList?.Where(qitem => qitem.TId == item.TeacherId)?.FirstOrDefault()?.TeacherName ?? ""),
                               (teacherList?.Where(qitem => qitem.TId == newChangePlanItemList.FirstOrDefault().TeacherId)?.FirstOrDefault()?.TeacherName ?? "")
                               );
                            }
                        }
                        else if (model.ChangeType == 3)
                        {
                            builder.AppendFormat(" update RB_Class_Plan SET  ClassRoomId={0} where ClassPlanId in({1})", newChangePlanItemList.FirstOrDefault().ClassRoomId, string.Join(",", oldChangePlanItemList.Select(x => x.ClassPlanId)));
                            string roomIds = string.Join(",", oldChangePlanItemList.Select(x => x.ClassRoomId)) + "," + newChangePlanItemList.FirstOrDefault().ClassRoomId;
                            var roomList = class_RoomRepository.GetClassRoomListRepository(new RB_Class_Room_ViewModel() { QRoomIds = roomIds });
                            foreach (var item in oldChangePlanItemList)
                            {
                                logContent += string.Format(Common.ConvertHelper.FormatDate(item.ClassDate) + "的教室由【{0}】修改为【{1}】.",
                                (roomList?.Where(qitem => qitem.RoomId == item.ClassRoomId)?.FirstOrDefault()?.RoomName ?? ""),
                               (roomList?.Where(qitem => qitem.RoomId == newChangePlanItemList.FirstOrDefault().ClassRoomId)?.FirstOrDefault()?.RoomName ?? "")
                               );
                            }
                        }
                    }
                    else if (model.ChangeType == 4)//取消课程
                    {
                        var oldPlanList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel()
                        {
                            ClassId = model.ClassId,
                            QClassPlanIds = string.Join(",", oldChangePlanItemList.Select(x => x.ClassPlanId)),
                        });
                        List<int> deletePlanList = new List<int>();
                        List<int> deletePlanTimeList = new List<int>();
                        foreach (var item in oldPlanList.GroupBy(x => x.ClassPlanId))
                        {
                            var tempPlanTimeList = oldPlanList.Where(x => x.ClassPlanId == item.Key);
                            var oldPlanTimeModel = oldChangePlanItemList.Where(x => x.ClassPlanId == item.Key).FirstOrDefault();
                            if (tempPlanTimeList.Count() == oldPlanTimeModel.PlanTimeList.Count())
                            {
                                deletePlanList.Add(item.Key);
                            }
                            deletePlanTimeList.AddRange(oldPlanTimeModel.PlanTimeList.Select(x => x.ClassTimeId));
                        }
                        foreach (var item in oldChangePlanItemList)
                        {
                            foreach (var itemTime in item.PlanTimeList)
                            {
                                logContent += string.Format("删除{0}上课时间【{1} - {2}】.", Common.ConvertHelper.FormatDate(item.ClassDate), itemTime.StartTime, itemTime.EndTime);
                            }
                        }
                        if (deletePlanList != null && deletePlanList.Any())
                        {
                            builder.AppendFormat(" UPDATE RB_Class_Plan SET  Status=1 WHERE ClassPlanId IN({0});", string.Join(",", deletePlanList.Select(x => x)));
                        }
                        if (deletePlanTimeList != null && deletePlanTimeList.Any())
                        {
                            builder.AppendFormat(" DELETE  FROM  rb_class_time WHERE classtimeId  IN({0});", string.Join(",", deletePlanTimeList.Select(x => x)));
                        }
                    }
                }
                else
                {
                    //全局修改
                    AllChangePlanItem allChangePlanModel = new AllChangePlanItem();
                    //目标数据
                    if (!string.IsNullOrWhiteSpace(model.TargetData))
                    {
                        allChangePlanModel = Common.Plugin.JsonHelper.DeserializeObject<AllChangePlanItem>(model.TargetData);
                    }
                    if (model.ChangeType == 1)
                    {
                        var oldPlanList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel()
                        {
                            ClassId = model.ClassId,
                            StartTime = model.CreateTime.ToString("yyyy-MM-dd 00:00:00")
                        });
                        #region 班级计划
                        //默认上课时间
                        var defaultPlanTimeList = new List<ClassTimeItem>();
                        var BasicMinutes = allChangePlanModel.ClassHourMinute;
                        foreach (var tItem in allChangePlanModel.DefaultTimeList)
                        {
                            ClassTimeItem tModel = new ClassTimeItem()
                            {
                                DateList = new List<string>(),
                                TimeList = new List<TimeItem>()
                            };
                            tModel.DateList = tItem.DateList;
                            foreach (var subItem in tItem.TimeList)
                            {
                                var startDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + subItem.StartTime + ":00");
                                var endDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + subItem.EndTime + ":00");
                                TimeSpan span = endDate.Subtract(startDate);
                                var timeModel = new TimeItem()
                                {
                                    StartTime = subItem.StartTime,
                                    EndTime = subItem.EndTime,
                                    TimeHour = subItem.TimeHour,
                                };
                                if (timeModel.TimeHour <= 0)
                                {
                                    timeModel.TimeHour = Convert.ToDecimal(span.TotalMinutes / BasicMinutes);
                                }
                                tModel.TimeList.Add(timeModel);
                                defaultPlanTimeList.Add(tModel);
                            }
                        }

                        //班级上课计划列表
                        List<RB_Class_Plan_ViewModel> classPlanList = new List<RB_Class_Plan_ViewModel>();
                        if (allChangePlanModel.ClassHours > 0)
                        {
                            var srartDate = Convert.ToDateTime(allChangePlanModel.OpenTimeStr);
                            //按周排课和按月排课
                            if (allChangePlanModel.ClassStyle == ClassStyleEnum.Week || allChangePlanModel.ClassStyle == ClassStyleEnum.Month)
                            {
                                int i = 0;
                                decimal totalHours = 0;
                                while (allChangePlanModel.ClassHours > totalHours)
                                {
                                    var newDate = srartDate.AddDays(i);
                                    foreach (var item in allChangePlanModel.WeekDayList)
                                    {
                                        var planModel = new RB_Class_Plan_ViewModel()
                                        {
                                            ClassId = model.ClassId,
                                            ClassPlanId = 0,
                                            ClassRoomId = allChangePlanModel.ClassRoomId,
                                            Group_Id = model.Group_Id,
                                            School_Id = model.School_Id,
                                            PlanTimeList = new List<RB_Class_Time_ViewModel>(),
                                            TeacherId = allChangePlanModel.TeacherId,
                                            ClassDate = newDate
                                        };
                                        if (allChangePlanModel.ClassStyle == ClassStyleEnum.Week)
                                        {
                                            switch (item)
                                            {
                                                case "1":
                                                    if (newDate.DayOfWeek == DayOfWeek.Monday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                                case "2":
                                                    if (newDate.DayOfWeek == DayOfWeek.Tuesday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                                case "3":
                                                    if (newDate.DayOfWeek == DayOfWeek.Wednesday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                                case "4":
                                                    if (newDate.DayOfWeek == DayOfWeek.Thursday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                                case "5":
                                                    if (newDate.DayOfWeek == DayOfWeek.Friday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                                case "6":
                                                    if (newDate.DayOfWeek == DayOfWeek.Saturday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                                case "7":
                                                    if (newDate.DayOfWeek == DayOfWeek.Sunday)
                                                    {
                                                        var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                        if (timeList != null && timeList.Count > 0)
                                                        {
                                                            var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                            totalHours += dayHours;
                                                            classPlanList.Add(planModel);
                                                        }
                                                    }
                                                    break;
                                            }
                                        }
                                        else if (allChangePlanModel.ClassStyle == ClassStyleEnum.Month)
                                        {
                                            if (newDate.Day == Convert.ToInt32(item))
                                            {
                                                var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                                if (timeList != null && timeList.Count > 0)
                                                {
                                                    var dayHours = CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                                    totalHours += dayHours;
                                                    classPlanList.Add(planModel);
                                                }
                                            }
                                        }
                                    }
                                    i++;
                                }
                            }
                            //固定日期
                            else if (allChangePlanModel.ClassStyle == ClassStyleEnum.FixedDate)
                            {
                                foreach (var item in allChangePlanModel.WeekDayList)
                                {
                                    var planModel = new RB_Class_Plan_ViewModel()
                                    {
                                        ClassId = model.ClassId,
                                        ClassPlanId = 0,
                                        ClassRoomId = allChangePlanModel.ClassRoomId,
                                        Group_Id = model.Group_Id,
                                        School_Id = model.School_Id,
                                        PlanTimeList = new List<RB_Class_Time_ViewModel>(),
                                        TeacherId = allChangePlanModel.TeacherId,
                                        ClassDate = Convert.ToDateTime(item)
                                    };
                                    var timeList = defaultPlanTimeList.Where(qitem => qitem.DateList.Contains(item))?.FirstOrDefault()?.TimeList;
                                    if (timeList != null && timeList.Count > 0)
                                    {
                                        CalcDayClassHoursModule(timeList, planModel.PlanTimeList, allChangePlanModel.ClassHourMinute, BasicMinutes);
                                        classPlanList.Add(planModel);
                                    }
                                }
                            }
                            //约课
                            else
                            {

                            }
                        }

                        Task.Run(() =>
                        {
                            if (oldPlanList != null && oldPlanList.Any())//删除剩余的排课日期和时间
                            {
                                string ids = string.Join(",", oldPlanList.Select(qitem => qitem.ClassPlanId));
                                if (!string.IsNullOrEmpty(ids))
                                {
                                    flag = class_TimeRepository.DeleteClassTimeByPlanIdsRepository(ids);
                                    if (flag)
                                    {
                                        flag = class_PlanRepository.DeleteClassPlanRepository(ids);
                                    }
                                }
                            }
                            if (classPlanList != null && classPlanList.Any())
                            {
                                foreach (var item in classPlanList)
                                {
                                    if (!class_PlanRepository.CheckExistsRepository(item))
                                    {
                                        //添加班级上课计划
                                        var newClassPlanId = class_PlanRepository.Insert(item);
                                        flag = newClassPlanId > 0;
                                        if (item.PlanTimeList != null && item.PlanTimeList.Any() && newClassPlanId > 0)
                                        {
                                            foreach (var subItem in item.PlanTimeList)
                                            {
                                                subItem.ClassTimeId = 0;
                                                subItem.ClassPlanId = newClassPlanId;
                                                subItem.ClassId = model.ClassId;
                                                subItem.Group_Id = model.Group_Id;
                                                subItem.School_Id = model.School_Id;
                                                //添加班级上课计划的上课时间
                                                class_TimeRepository.Insert(subItem);
                                            }
                                        }
                                    }
                                }
                                if (flag)
                                {
                                    classLogRepository.AddClassLogRepository(
                                      new Model.Entity.Log.RB_Class_Log()
                                      {
                                          LogType = Common.Enum.Course.ClassLogTypeEnum.Class,
                                          LogContent = "从" + allChangePlanModel.OpenTimeStr + "开始" + (Common.Plugin.EnumHelper.ToName(allChangePlanModel.ClassStyle)),
                                          ClassId = model.ClassId,
                                          Group_Id = model.Group_Id,
                                          School_Id = model.School_Id,
                                          CreateBy = model.CreateBy
                                      });
                                }
                            }
                        });
                        #endregion
                    }
                    else if (model.ChangeType == 2 || model.ChangeType == 3)
                    {
                        if (model.ChangeType == 2)
                        {
                            builder.AppendFormat(" UPDATE RB_Class_Plan SET  TeacherId={0} WHERE DATE_FORMAT(ClassDate,'%Y-%m-%d')>=DATE_FORMAT('{1}','%Y-%m-%d')", allChangePlanModel.TeacherId, model.TakeEffectTime.Value.ToString("yyyy-MM-dd"));
                            string tIds = allChangePlanModel.TeacherId.ToString();
                            var teacherList = teacherRepository.GetTeacherListRepository(new Model.ViewModel.User.RB_Teacher_ViewModel() { QTIds = tIds });
                            logContent += string.Format("全局将讲师修改为【{0}】.", (teacherList?.Where(qitem => qitem.TId == allChangePlanModel.TeacherId)?.FirstOrDefault()?.TeacherName ?? ""));
                        }
                        else if (model.ChangeType == 3)
                        {
                            builder.AppendFormat(" UPDATE RB_Class_Plan SET  ClassRoomId={0} WHERE DATE_FORMAT(ClassDate,'%Y-%m-%d')>=DATE_FORMAT('{1}','%Y-%m-%d')", allChangePlanModel.ClassRoomId, model.TakeEffectTime.Value.ToString("yyyy-MM-dd"));
                            string roomIds = allChangePlanModel.ClassRoomId.ToString();
                            var roomList = class_RoomRepository.GetClassRoomListRepository(new RB_Class_Room_ViewModel() { QRoomIds = roomIds });
                            logContent += string.Format("全局将教室修改为【{0}】.", (roomList?.Where(qitem => qitem.RoomId == allChangePlanModel.ClassRoomId)?.FirstOrDefault()?.RoomName ?? ""));
                        }
                    }
                    else if (model.ChangeType == 4)
                    {
                        var oldPlanList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel()
                        {
                            ClassId = model.ClassId,
                            StartTime = model.TakeEffectTime.Value.ToString("yyyy-MM-dd")
                        });
                        if (oldPlanList != null && oldPlanList.Any())//删除剩余的排课日期和时间
                        {
                            if (oldPlanList != null && oldPlanList.Any())
                            {
                                builder.AppendFormat(" UPDATE RB_Class_Plan SET  Status=1 WHERE ClassPlanId IN({0});", string.Join(",", oldPlanList.Select(x => x.ClassPlanId)));
                                builder.AppendFormat(" DELETE  FROM  rb_class_time WHERE ClassPlanId  IN({0});", string.Join(",", oldPlanList.Select(x => x.ClassPlanId)));
                            }
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(builder.ToString()))
                {
                    flag = class_PlanRepository.Execute(builder.ToString()) > 0;
                }

                if (!string.IsNullOrEmpty(logContent) && flag)
                {
                    classLogRepository.AddClassLogRepository(
                        new Model.Entity.Log.RB_Class_Log()
                        {
                            LogType = ClassLogTypeEnum.Class,
                            LogContent = logContent,
                            ClassId = model.ClassId,
                            Group_Id = model.Group_Id,
                            School_Id = model.School_Id,
                            CreateBy = model.CreateBy
                        });
                }
            }
            return flag;
        }


        /// <summary>
        /// 计算每天课时
        /// </summary>
        /// <param name="timeList"></param>
        /// <param name="classTimeList"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private decimal CalcDayClassHoursModule(List<TimeItem> timeList, List<RB_Class_Time_ViewModel> classTimeList, int ClassHourMinute, int BasicMinutes)
        {
            decimal dayClassHours = 0;
            decimal dayMinutes = 0;
            foreach (var sItem in timeList)
            {
                var timeModel = new RB_Class_Time_ViewModel()
                {
                    StartTime = sItem.StartTime,
                    EndTime = sItem.EndTime,
                    TimeHour = sItem.TimeHour,
                };
                classTimeList.Add(timeModel);

                var startDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + sItem.StartTime + ":00");
                var endDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + sItem.EndTime + ":00");
                TimeSpan span = endDate.Subtract(startDate);
                if (span.TotalMinutes > 0)
                {
                    dayMinutes += Convert.ToDecimal(span.TotalMinutes);
                }
            }

            if (ClassHourMinute > 0)
            {
                dayClassHours = dayMinutes / ClassHourMinute;
            }
            else
            {
                dayClassHours = dayMinutes / BasicMinutes;
            }
            return dayClassHours;
        }
    }
}