using Edu.Model.CacheModel;
using Edu.Model.Entity.EduTask;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.EduTask;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.EduTask;
using Edu.Repository.Grade;
using Edu.Repository.User;
using System.Collections.Generic;
using System.Linq;
using VT.FW.AOP.CustomerAttribute;
using VT.FW.DB;

namespace Edu.Module.EduTask
{
    /// <summary>
    /// 调课计划处理类
    /// </summary>
    public class ChangeClassPlanModule
    {
        /// <summary>
        /// 教务单据仓储层对象
        /// </summary>
        private readonly RB_Education_ReceiptRepository education_ReceiptRepository = new RB_Education_ReceiptRepository();

        /// <summary>
        /// 调课计划仓储层对象
        /// </summary>
        private readonly RB_Change_ClassPlanRepository change_ClassPlanRepository = new RB_Change_ClassPlanRepository();

        /// <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 RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

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

        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 检查是否重复【固定日期】
        /// </summary>
        /// <param name="ClassId"></param>
        /// <param name="changeList"></param>
        /// <param name="timeList"></param>
        /// <returns></returns>
        public List<object> GetRepeatListModule(int ClassId, List<ChangePlanItem> changeList, List<TimeItem> timeList)
        {
            List<object> list = new List<object>();
            var planList = new List<RB_Class_Plan_ViewModel>();
            if (changeList != null && changeList.Count > 0)
            {
                foreach (var item in changeList)
                {
                    var planModel = new RB_Class_Plan_ViewModel()
                    {
                        ClassPlanId=0,
                        ClassId=ClassId,
                        ClassDate=item.ClassDate,
                        ClassRoomId=item.ClassRoomId,
                        TeacherId=item.TeacherId,
                        PlanTimeList=new List<RB_Class_Time_ViewModel> (),
                    };
                    if (timeList != null && timeList.Count > 0)
                    {
                        foreach (var subItem in timeList)
                        {
                            planModel.PlanTimeList.Add(new RB_Class_Time_ViewModel
                            {
                                StartTime = subItem.StartTime,
                                EndTime = subItem.EndTime,
                                TimeHour = subItem.TimeHour,
                            });
                        }
                    }
                    planList.Add(planModel);
                }
            }
            if (timeList != null && timeList.Count > 0 && planList!=null && planList.Count>0)
            {
                list = GetRepeatDataModule(planList, 2);
            }
            return list;
        }


        /// <summary>
        /// 全局老师、教室调整
        /// </summary>
        /// <param name="ClassId"></param>
        /// <param name="changeList"></param>
        /// <param name="timeList"></param>
        /// <returns></returns>
        public List<object> GetAllRepeatListModule(int ClassId, string TakeEffectTime, int TeacherId = 0, int ClassRoomId = 0)
        {
            List<object> list = new List<object>();
            var classPlanList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel()
            {
                ClassId = ClassId,
                StartTime = TakeEffectTime,
            });

            list = GetRepeatDataModule(classPlanList, 1, TeacherId: TeacherId, ClassRoomId: ClassRoomId);
            return list;
        }

        /// <summary>
        /// 全局验证上课日期和时间
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<object> GetAllDateAndTimeRepeatListModule(int ClassId, AllChangePlanItem model, UserInfo user)
        {
            List<object> list = new List<object>();
            var oldClass = classRepository.GetEntity(ClassId);
            var oldPlanList = class_PlanRepository.GetClassPlanListExtRepository(new RB_Class_Plan_ViewModel()
            {
                ClassId = ClassId,
                EndTime = Common.ConvertHelper.FormatDate(model.OpenTimeStr)
            });
            //已经完成的上课计划
            var finishClassHours = oldPlanList?.Sum(qitem => qitem.TimeHour) ?? 0;
            var BasicMinutes = class_ConfigRepository.GetBasicMinutesRepository(user.Group_Id);
            RB_Class_ViewModel classModel = new RB_Class_ViewModel()
            {
                ClassHours = oldClass.ClassHours,
                ClassStyle = model.ClassStyle,
                WeekDayList = new List<string>(),
                Teacher_Id = model.TeacherId,
                ClassRoomId = model.ClassRoomId,
            };
            if (model.DefaultTimeList != null && model.DefaultTimeList.Count > 0)
            {
                foreach (var item in model.DefaultTimeList)
                {
                    if (item.DateList != null && item.DateList.Count > 0)
                    {
                        classModel.WeekDayList.AddRange(item.DateList);
                    }
                }
            }
            var planList = class_PlanRepository.CreateClassPlanRepository(classModel, model.DefaultTimeList, finishClassHours, BasicMinutes, defaultOpenTime: model.OpenTimeStr);
            list = GetRepeatDataModule(planList,2);
            return list;
        }

        /// <summary>
        /// 获取冲突的数据
        /// </summary>
        /// <param name="classPlanList">上课计划</param>
        /// <param name="ChangeType">1-全局调整(教室或者老师)，2-全局调整(上课计划)</param>
        /// <param name="TeacherId">老师编号</param>
        /// <param name="ClassRoomId">教室编号</param>
        /// <returns></returns>
        public List<object> GetRepeatDataModule(List<RB_Class_Plan_ViewModel> classPlanList,int ChangeType, int TeacherId=0,int ClassRoomId=0)
        {
            List<object> list = new List<object>();
            List<TimeItem> timeList = new List<TimeItem>();
            //冲突的上课计划编号
            List<int> ids = new List<int>();
            if (classPlanList != null && classPlanList.Count > 0)
            {
                string planIds = string.Join(",", classPlanList.Select(qitem => qitem.ClassPlanId));
                var classTimeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel()
                {
                    QClassPlanIds = planIds
                });
                foreach (var item in classPlanList)
                {
                    if (ChangeType == 1)
                    {
                        item.PlanTimeList = classTimeList?.Where(qitem => qitem.ClassPlanId == item.ClassPlanId)?.ToList() ?? new List<RB_Class_Time_ViewModel>();
                    }
                    if (ChangeType == 2&&item.PlanTimeList != null && item.PlanTimeList.Count > 0)
                    {
                        foreach (var subItem in item.PlanTimeList)
                        {
                            timeList.Add(new TimeItem
                            {
                                StartTime = Common.ConvertHelper.FormatDate(item.ClassDate) + " " + subItem.StartTime + ":00",
                                EndTime = Common.ConvertHelper.FormatDate(item.ClassDate) + " " + subItem.EndTime + ":00",
                            });
                        }
                    }
                }
                var repeatList = CheckClassPlanModule(classPlanList[0].ClassId, timeList);
                if (repeatList != null && repeatList.Count > 0)
                {
                    foreach (var item in classPlanList)
                    {
                        var tempRepeatList = repeatList?.Where(qitem => qitem.ClassDate == item.ClassDate)?.ToList();
                        if (tempRepeatList != null && tempRepeatList.Count > 0)
                        {
                            var newTeacherId = 0;
                            var newClassRoomId = 0;
                            if (ChangeType == 1)
                            {
                                newTeacherId = TeacherId;
                                newClassRoomId = ClassRoomId;
                            }
                            else
                            {
                                newTeacherId = item.TeacherId;
                                newClassRoomId = item.ClassRoomId;
                            }
                            if (newTeacherId > 0)
                            {
                                var tempTeacherList = tempRepeatList?.Where(qitem => qitem.TeacherId == newTeacherId)?.ToList();
                                if (tempTeacherList != null && tempTeacherList.Count > 0)
                                {
                                    var tempIds = Common.ConvertHelper.StringToList(string.Join(",", tempTeacherList.GroupBy(qitem => qitem.ClassPlanId).Select(qitem => qitem.Key)));
                                    if (tempIds != null && tempIds.Count > 0)
                                    {
                                        ids.AddRange(tempIds);
                                    }
                                }
                            }
                            if (newClassRoomId > 0)
                            {
                                var classroomList = tempRepeatList?.Where(qitem => qitem.ClassRoomId == newClassRoomId)?.ToList();
                                if (classroomList != null && classroomList.Count > 0)
                                {
                                    var tempIds = Common.ConvertHelper.StringToList(string.Join(",", classroomList.GroupBy(qitem => qitem.ClassPlanId).Select(qitem => qitem.Key)));
                                    if (tempIds != null && tempIds.Count > 0)
                                    {
                                        ids.AddRange(tempIds);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (ids != null && ids.Count > 0)
            {
                List<RB_Class_Room_ViewModel> roomList = new List<RB_Class_Room_ViewModel>();
                List<RB_Teacher_ViewModel> teacherList = new List<RB_Teacher_ViewModel>();
                List<int> roomIds = Common.ConvertHelper.StringToList(string.Join(",", classPlanList.Select(qitem => qitem.ClassRoomId)));
                List<int> teacherIds= Common.ConvertHelper.StringToList(string.Join(",", classPlanList.Select(qitem => qitem.TeacherId)));
                if (roomIds != null && roomIds.Count > 0)
                {
                    roomIds.Add(ClassRoomId);
                }
                if (teacherIds != null && teacherIds.Count > 0)
                {
                    teacherIds.Add(TeacherId);
                }
                if (roomIds!=null&& roomIds.Count>0)
                {
                    roomList = class_RoomRepository.GetClassRoomListRepository(new RB_Class_Room_ViewModel()
                    {
                        QRoomIds =string.Join(",", roomIds)
                    });
                }
                if (teacherIds!=null&& teacherIds.Count > 0)
                {
                    teacherList = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel()
                    {
                        QTIds = string.Join(",", teacherIds)
                    });
                }
                //冲突的数据
                var planOtherList = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel()
                {
                    QClassPlanIds = string.Join(",", ids)
                });
                var classOtherTimeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel()
                {
                    QClassPlanIds = string.Join(",", ids)
                });

                foreach (var item in classPlanList)
                {
                    List<object> PlanRepeatList = new List<object>();
                    var tempRepeatList = planOtherList?.Where(qitem => qitem.ClassDate == item.ClassDate)?.ToList();
                    if (tempRepeatList != null && tempRepeatList.Count > 0)
                    {
                        foreach (var subItem in tempRepeatList)
                        {
                            var tempObj = new
                            {
                                subItem.ClassPlanId,
                                subItem.ClassId,
                                subItem.ClassName,
                                ClassDate = Common.ConvertHelper.FormatDate(subItem.ClassDate),
                                subItem.TeacherId,
                                subItem.TeacherName,
                                subItem.ClassRoomId,
                                subItem.RoomName,
                                PlanTimeList = classOtherTimeList.Where(qitem => qitem.ClassPlanId == subItem.ClassPlanId).Select(qitem => new
                                {
                                    qitem.StartTime,
                                    qitem.EndTime,
                                    qitem.TimeHour
                                }),
                            };
                            PlanRepeatList.Add(tempObj);
                        }

                        string TeacherName = "";
                        string RoomName = "";
                        var newTeacherId = 0;
                        var newClassRoomId = 0;
                        //调整老师或者教室
                        if (ChangeType == 1)
                        {
                            newTeacherId = TeacherId > 0 ? TeacherId : item.TeacherId;
                            newClassRoomId = ClassRoomId > 0 ? ClassRoomId : item.ClassRoomId;
                            TeacherName = teacherList?.Where(qitem => qitem.TId == newTeacherId)?.FirstOrDefault()?.TeacherName ?? "";
                            RoomName = roomList?.Where(qitem => qitem.RoomId == newClassRoomId)?.FirstOrDefault()?.RoomName ?? "";
                        }
                        //调整上课日期或上课时间
                        else
                        {
                            newTeacherId = item.TeacherId;
                            newClassRoomId = item.ClassRoomId;
                            TeacherName = teacherList?.Where(qitem => qitem.TId == item.TeacherId)?.FirstOrDefault()?.TeacherName ?? "";
                            RoomName = roomList?.Where(qitem => qitem.RoomId == item.ClassRoomId)?.FirstOrDefault()?.RoomName ?? "";
                        }
                        var obj = new
                        {
                            item.ClassPlanId,
                            ClassDate = Common.ConvertHelper.FormatDate(item.ClassDate),
                            TeacherId = newTeacherId,
                            TeacherName,
                            ClassRoomId = newClassRoomId,
                            RoomName,
                            PlanTimeList = item.PlanTimeList.Select(qitem => new
                            {
                                qitem.StartTime,
                                qitem.EndTime,
                            }),
                            PlanRepeatList
                        };
                        list.Add(obj);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 检查上课计划是否存在时间上的交集【HK2021-07-28新增】
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="timeList"></param>
        /// <returns></returns>
        public List<RB_Class_Plan_ViewModel> CheckClassPlanModule(int classId, List<TimeItem> timeList)
        {
            return class_PlanRepository.CheckClassPlanRepository(classId, timeList);
        }

        /// <summary>
        /// 新增修改调课计划
        /// </summary>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetChangeClassPlanModule(RB_Change_ClassPlan_ViewModel extModel, string receiptFile)
        {
            bool flag = false;
            if (extModel.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Change_ClassPlan_ViewModel.ChangeType),extModel.ChangeType },
                    {nameof(RB_Change_ClassPlan_ViewModel.MoveType),extModel.MoveType },
                    {nameof(RB_Change_ClassPlan_ViewModel.TakeEffectTime),extModel.TakeEffectTime },
                    {nameof(RB_Change_ClassPlan_ViewModel.SourceData),extModel.SourceData },
                    {nameof(RB_Change_ClassPlan_ViewModel.TargetData),extModel.TargetData },
                    {nameof(RB_Change_ClassPlan_ViewModel.UpdateBy),extModel.UpdateBy },
                    {nameof(RB_Change_ClassPlan_ViewModel.UpdateTime),extModel.UpdateTime },
                };
                flag = change_ClassPlanRepository.Update(fileds, new WhereHelper(nameof(RB_Change_ClassPlan_ViewModel.Id), extModel.Id));
            }
            else
            {
                var newId = change_ClassPlanRepository.Insert(extModel);
                extModel.Id = newId;
                flag = newId > 0;
                if (flag)
                {
                    var educationReceipt = new RB_Education_Receipt()
                    {
                        Id = 0,
                        Title = "调课申请",
                        ReceiptType = Common.Enum.Finance.ReceiptTypeEnum.ChangeClass,
                        RelationId = newId,
                        ClassId = extModel.ClassId,
                        Group_Id = extModel.Group_Id,
                        School_Id = extModel.School_Id,
                        CreateBy = extModel.CreateBy,
                        CreateTime = extModel.CreateTime,
                        UpdateBy = extModel.UpdateBy,
                        UpdateTime = extModel.UpdateTime,
                        VerifyStatus = Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit,
                        ReceiptFile = receiptFile
                    };
                    flag = education_ReceiptRepository.SetEducationReceiptRepository(educationReceipt, out string message);
                }
            }
            return flag;
        }
    }
}
