using Edu.Common.Enum;
using Edu.Model.ViewModel.Reserve;
using Edu.Repository.Reserve;
using System;
using System.Collections.Generic;
using System.Text;
using VT.FW.AOP.CustomerAttribute;
using VT.FW.DB;
using System.Linq;
using Edu.Repository.Course;
using Edu.Common.Enum.System;
using Edu.Cache.User;
using Edu.Model.CacheModel;
using Edu.Repository.User;
using Edu.Common.Message;
using Edu.Model.ViewModel.Grade;
using Edu.Repository.Grade;
using Edu.Repository.Customer;
using Edu.Model.ViewModel.User;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Customer;
using Edu.Model.Entity.Customer;

namespace Edu.Module.Duty
{
    /// <summary>
    /// 访客约课处理类
    /// </summary>
    public class VisitorReserveModule
    {
        /// <summary>
        /// 访客约课仓储层对象
        /// </summary>
        private readonly RB_Visitor_ReserveRepository visitor_ReserveRepository = new RB_Visitor_ReserveRepository();

        /// <summary>
        /// 约课班级信息仓储层对象
        /// </summary>
        private readonly RB_Reserve_ClassRepository reserve_ClassRepository = new RB_Reserve_ClassRepository();

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

        /// <summary>
        /// 账号管理仓储层对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();
        
        /// <summary>
        /// 学员仓储层对象
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();

        /// <summary>
        /// 学员协助人员
        /// </summary>
        private readonly RB_Student_AssistRepository student_AssistRepository = new RB_Student_AssistRepository();

        /// <summary>
        /// 学员日志仓储层对象
        /// </summary>
        private readonly RB_Student_LogRepository student_LogRepository = new RB_Student_LogRepository();

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

        /// <summary>
        /// 获取访客约课分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetVisitorReservePageModule(int pageIndex, int pageSize, out long rowsCount, RB_Visitor_Reserve_Extend query)
        {
            return visitor_ReserveRepository.GetVisitorReservePageRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 获取访客约课列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Visitor_Reserve_Extend> GetVisitorReserveListModule(RB_Visitor_Reserve_Extend query)
        {
            return visitor_ReserveRepository.GetVisitorReserveListRepository(query);
        }

        /// <summary>
        /// 新增修改访客约课
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetVisitorReserveModule(RB_Visitor_Reserve_Extend model,out string message)
        {
            message = "";
            bool flag;
            var reserveClass = new RB_Reserve_Class_Extend()
            {
                ClassContent = model.ClassContent,
                CreateTime = model.CreateTime,
                CreateBy = model.CreateBy,
                ClassRoomId = model.ClassRoomId,
                ClassDate = model.ClassDate,
                ClassTime = model.ClassTime,
                Group_Id = model.Group_Id,
                ReserveClassId = 0,
                School_Id = model.School_Id,
                Status = DateStateEnum.Normal,
                TeacherId = model.TeacherId,
                UpdateBy = model.UpdateBy,
                UpdateTime = model.UpdateTime,
                EndTime=model.EndTime,
                TrialLessonId=model.TrialLessonId
            };
            if (model.ReserveClassId <= 0)
            {
                var newFlag = SetReserveClassModule(reserveClass, out string newMsg);
                if (!newFlag)
                {
                    message = newMsg;
                    return false;
                }
                model.ReserveClassId = reserveClass.ReserveClassId;
            }
            if (visitor_ReserveRepository.ExistsVisitorReserveRepository(model))
            {
                //message = string.Format("已存在此访客的预约试听课信息,请重新选择!");
                //return false;
            }
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Visitor_Reserve_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Visitor_Reserve_Extend.UpdateTime),model.UpdateTime },
                    {nameof(RB_Visitor_Reserve_Extend.ReserveClassId),model.ReserveClassId },
                    {nameof(RB_Visitor_Reserve_Extend.Remark),model.Remark },
                };
                flag = visitor_ReserveRepository.Update(fileds, new WhereHelper(nameof(RB_Visitor_Reserve_Extend.Id), model.Id));
            }
            else
            {
                var newId = visitor_ReserveRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
                if (flag) 
                {
                    //获取学生信息
                    var smodel = studentRepository.GetEntity(model.Visitor_Id);
                    if (smodel != null && smodel.StuId > 0)
                    {
                        var assistTeacher = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend()
                        {
                            StuId = smodel.StuId
                        })?.FirstOrDefault(qitem => qitem.AssistType == Common.Enum.User.AssistTypeEnum.Teacher);
                        string logTitle = "新增协同人员";
                        string logContent = "";
                        var empModel = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
                        {
                            AccountType = Common.Enum.User.AccountTypeEnum.Teacher,
                            AccountId = model.TeacherId
                        })?.FirstOrDefault();
                        if (assistTeacher == null)
                        {
                            logTitle = "新增协同人员";
                            student_AssistRepository.Insert(new RB_Student_Assist()
                            {
                                CreateBy = model.UpdateBy,
                                CreateTime = DateTime.Now,
                                Id = 0,
                                Status = DateStateEnum.Normal,
                                StuId = smodel.StuId,
                                AssistId = empModel?.Id ?? 0,
                                AssistType = Common.Enum.User.AssistTypeEnum.Teacher,
                            });
                            logContent += string.Format("新增协同人员:" + empModel?.EmployeeName);
                        }
                        else
                        {
                            logTitle = "修改协同人员";
                            string oldName = accountRepository.GetEmployeeInfo(assistTeacher.AssistId)?.EmployeeName ?? "";
                            Dictionary<string, object> fileds = new Dictionary<string, object>()
                            {
                                {nameof(RB_Student_Assist.AssistId),(empModel?.Id??0) }
                            };
                            student_AssistRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Assist.Id), assistTeacher.Id));
                            logContent += string.Format("修改协同人员：由【{0}】=>【{1}】", oldName, empModel?.EmployeeName);
                        }
                        student_LogRepository.AddStuLogRepository(smodel.StuId, Common.Enum.Log.StudentLogTypeEnum.BasicInfo, logTitle, logContent, model.UpdateBy);
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取访客约课
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Visitor_Reserve_Extend GetVisitorReserveModule(int Id)
        {
            var extModel = visitor_ReserveRepository.GetEntity<RB_Visitor_Reserve_Extend>(Id);
            return extModel;
        }

        /// <summary>
        /// 删除访客约课
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveVisitorReserveModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Visitor_Reserve_Extend.Status),(int)DateStateEnum.Delete  },
            };
            var flag = visitor_ReserveRepository.Update(fileds, new WhereHelper(nameof(RB_Visitor_Reserve_Extend.Id), Id));
            return flag;
        }

        /// <summary>
        /// 删除访客约课
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool UpdateVisitorReserveStatusModule(int Id,int ReserveStatus,string Remark)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Visitor_Reserve_Extend.ReserveStatus),ReserveStatus },
            };
            if (!string.IsNullOrEmpty(Remark))
            {
                fileds.Add(nameof(RB_Visitor_Reserve_Extend.Remark), Remark);
            }
            var flag = visitor_ReserveRepository.Update(fileds, new WhereHelper(nameof(RB_Visitor_Reserve_Extend.Id), Id));
            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_Reserve_Class_Extend> GetReserveClassPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Reserve_Class_Extend query)
        {
            var list = reserve_ClassRepository.GetReserveClassPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string ids = string.Join(",", list.Select(qitem => qitem.ReserveClassId));
                var visitorList = visitor_ReserveRepository.GetVisitorReserveStaticsListRepository(new RB_Visitor_Reserve_Extend()
                {
                    Q_ReserveClassIds = ids
                });
                List<RB_Student_OrderGuest_ViewModel> stuOrderList = new List<RB_Student_OrderGuest_ViewModel>();
                if (visitorList != null && visitorList.Count > 0)
                {
                    string visitorIds = string.Join(",", visitorList.Select(qitem => qitem.Visitor_Id));
                    if (!string.IsNullOrEmpty(visitorIds))
                    {
                        stuOrderList= student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel()
                        {
                            QStudentIds = visitorIds
                        });
                    }
                }
          
                foreach (var item in list)
                {
                    var tempList = visitorList?.Where(qitem => qitem.ReserveClassId == item.ReserveClassId);
                    item.JoinNum = tempList?.Count()??0;
                    item.VisitorList = tempList?.ToList() ?? new List<RB_Visitor_Reserve_Extend>();
                    int OrderCount = 0;
                    foreach (var subItem in tempList)
                    {
                        OrderCount += stuOrderList.Where(qitem => qitem.Student_Id == subItem.Visitor_Id)?.Count() ?? 0;
                    }
                    item.OrderCount = OrderCount;
                    if (item.OrderCount > 0)
                    {
                        item.ConversionRates = decimal.Round(item.JoinNum / item.OrderCount, 2);
                    }
                    else
                    {
                        item.ConversionRates = 0;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取约课班级列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Reserve_Class_Extend> GetReserveClassListModule(RB_Reserve_Class_Extend query)
        {
            return reserve_ClassRepository.GetReserveClassListRepository(query);
        }

        /// <summary>
        /// 新增修改约课班级
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetReserveClassModule(RB_Reserve_Class_Extend model,out string message)
        {
            bool flag;
            message = "";
            var UserInfo = UserReidsCache.GetUserLoginInfo(model.CreateBy);
            var chooseDateTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(model.ClassDate) + " " + model.ClassTime);
            var chooseEndTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(model.ClassDate) + " " + model.EndTime);

            #region 教师验证
            if (CheckClassTeacherModule(chooseDateTime, chooseEndTime, model, out string newMsg))
            {
                message = newMsg;
                return false;
            }
            #endregion

            #region 验证教室
            if (CheckClassRoomModule(chooseDateTime, chooseEndTime, model,out string roomMessage))
            {
                message = roomMessage;
                return false;
            }
            #endregion

            if (model.ReserveClassId > 0)
            {
                var oldModel = GetReserveClassModule(model.ReserveClassId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Reserve_Class_Extend.TeacherId),model.TeacherId  },
                    {nameof(RB_Reserve_Class_Extend.ClassDate),model.ClassDate  },
                    {nameof(RB_Reserve_Class_Extend.ClassTime),model.ClassTime  },
                    {nameof(RB_Reserve_Class_Extend.EndTime),model.EndTime  },
                    {nameof(RB_Reserve_Class_Extend.ClassRoomId),model.ClassRoomId  },
                    {nameof(RB_Reserve_Class_Extend.ClassContent),model.ClassContent  },
                    {nameof(RB_Reserve_Class_Extend.UpdateBy),model.UpdateBy  },
                    {nameof(RB_Reserve_Class_Extend.UpdateTime),model.UpdateTime  },
                    {nameof(RB_Reserve_Class_Extend.TrialLessonId),model.TrialLessonId  },
                };
                flag = reserve_ClassRepository.Update(fileds, new WhereHelper(nameof(RB_Reserve_Class_Extend.ReserveClassId), model.ReserveClassId));
                if (flag && model.TeacherId != oldModel.TeacherId)
                {
                    var teacherList = accountRepository.GetAccountListRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                    {
                        Group_Id = model.Group_Id,
                        QAccountIds = (model?.TeacherId??0) +","+(oldModel?.TeacherId??0),
                        AccountType= Common.Enum.User.AccountTypeEnum.Teacher
                    });
                    Common.Message.PushMessageModel pushModel = new Common.Message.PushMessageModel()
                    {
                        CategoryId = PushMessageCategoryEnum.ReserveClass,
                        Content = "您有新的试听课信息!请查收",
                        CoverImg = "",
                        CreateByName = UserInfo.AccountName,
                        JumpUrl = $"/course/classPlan?ClassType=2",
                        SendTime = DateTime.Now,
                        SendType = 0,
                        Title = "试听课",
                        Platform = 2,
                        ReceiveId = (teacherList.Where(qitem=>qitem.AccountId==model.TeacherId)?.FirstOrDefault()?.Id??0).ToString(),
                    };
                    Common.Message.PushMessageModel pushModel2 = new Common.Message.PushMessageModel()
                    {
                        CategoryId = PushMessageCategoryEnum.ReserveClass,
                        Content = "您有试听课被取消!请查收",
                        CoverImg = "",
                        CreateByName = UserInfo.AccountName,
                        JumpUrl = $"/course/classPlan?ClassType=2",
                        SendTime = DateTime.Now,
                        SendType = 0,
                        Title = "试听课",
                        Platform = 2,
                        ReceiveId = (teacherList.Where(qitem => qitem.AccountId == oldModel.TeacherId)?.FirstOrDefault()?.Id ?? 0).ToString(),
                    };
                    List<PushMessageModel> messageList = new List<PushMessageModel>
                    {
                        pushModel,
                        pushModel2
                    };
                    Common.Message.MessageHelper.SendMessage(messageList);
                }
            }
            else
            {
                var newId = reserve_ClassRepository.Insert(model);
                model.ReserveClassId = newId;
                flag = newId > 0;
                var teacherModel = accountRepository.GetAccountListRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                {
                    Group_Id = model.Group_Id,
                    AccountId = model.TeacherId,
                    AccountType = Common.Enum.User.AccountTypeEnum.Teacher
                })?.FirstOrDefault();
                Common.Message.PushMessageModel pushModel = new Common.Message.PushMessageModel()
                {
                    CategoryId = PushMessageCategoryEnum.ReserveClass,
                    Content = "您有新的试听课信息!请查收",
                    CoverImg = "",
                    CreateByName = UserInfo.AccountName,
                    JumpUrl = $"/course/classPlan?ClassType=2",
                    SendTime = DateTime.Now,
                    SendType = 0,
                    Title = "试听课",
                    Platform = 2,
                    ReceiveId = (teacherModel?.Id ?? 0).ToString(),
                };
                if (flag)
                {
                    Common.Message.MessageHelper.SendMessage(pushModel);
                }
            }
            return flag;
        }

        /// <summary>
        /// 检查老师是否有上课安排
        /// </summary>
        /// <param name="chooseDateTime"></param>
        /// <param name="chooseEndTime"></param>
        /// <param name="model"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool CheckClassTeacherModule(DateTime chooseDateTime, DateTime chooseEndTime, RB_Reserve_Class_Extend model, out string message)
        {
            message = "";
            var planList = class_PlanRepository.GetClassPlanListExtRepository(new RB_Class_Plan_ViewModel()
            {
                TeacherId = model.TeacherId,
                QClassDateStr = Common.ConvertHelper.FormatDate(model.ClassDate),
                Group_Id = model.Group_Id
            });
            if (planList != null && planList.Count > 0)
            {
                foreach (var item in planList)
                {
                    var startTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(item.ClassDate) + " " + item.StartTime);
                    var endTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(item.ClassDate) + " " + item.EndTime);
                    if (chooseDateTime < endTime && chooseEndTime > startTime)
                    {
                        message = string.Format("此教师已有 {0} {1}-{2}【{3}】正常上课计划!请重新选择时间", Common.ConvertHelper.FormatDate(model.ClassDate), item.StartTime, item.EndTime, item.ClassName);
                        return true;
                    }
                }
            }
            var checkModel = new RB_Reserve_Class_Extend()
            {
                ClassDate = model.ClassDate,
                ClassTime = model.ClassTime,
                EndTime = model.EndTime,
                ReserveClassId = model.ReserveClassId,
                TeacherId = model.TeacherId
            };
            if (CheckReserveClassExistsModule(checkModel))
            {
                message = string.Format("此教师已有 {0} {1}-{2} 试听课计划!请重新选择时间", Common.ConvertHelper.FormatDate(model.ClassDate), model.ClassTime, model.EndTime);
                return true;
            }
            return false;
        }


        /// <summary>
        /// 检查教室是否重复
        /// </summary>
        /// <param name="chooseDateTime"></param>
        /// <param name="chooseEndTime"></param>
        /// <param name="model"></param>
        /// <param name="RoomMessage"></param>
        /// <returns></returns>
        public bool CheckClassRoomModule(DateTime chooseDateTime, DateTime chooseEndTime, RB_Reserve_Class_Extend model,out string RoomMessage)
        {
            RoomMessage = "";
            var planList = class_PlanRepository.GetClassPlanListExtRepository(new RB_Class_Plan_ViewModel()
            {
                ClassRoomId=model.ClassRoomId,
                QClassDateStr = Common.ConvertHelper.FormatDate(model.ClassDate),
                Group_Id = model.Group_Id
            });
            if (planList != null && planList.Count > 0)
            {
                foreach (var item in planList)
                {
                    var startTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(item.ClassDate) + " " + item.StartTime);
                    var endTime = Convert.ToDateTime(Common.ConvertHelper.FormatDate(item.ClassDate) + " " + item.EndTime);
                    if (chooseDateTime < endTime && chooseEndTime > startTime)
                    {
                        RoomMessage = string.Format("此教室已有 {0} {1}-{2}【{3}】正常上课计划!请重新选择时间", Common.ConvertHelper.FormatDate(model.ClassDate), item.StartTime, item.EndTime, item.ClassName);
                        return true;
                    }
                }
            }
            var checkModel = new RB_Reserve_Class_Extend()
            {
                ClassDate = model.ClassDate,
                ClassTime = model.ClassTime,
                EndTime = model.EndTime,
                ReserveClassId = model.ReserveClassId,
                ClassRoomId = model.ClassRoomId
            };
            if (CheckReserveClassExistsModule(checkModel))
            {
                RoomMessage = string.Format("此教室已有 {0} {1}-{2} 试听课计划!请重新选择时间", Common.ConvertHelper.FormatDate(model.ClassDate), model.ClassTime, model.EndTime);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 检查预约课程是否存在
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CheckReserveClassExistsModule(RB_Reserve_Class_Extend model)
        {
            return reserve_ClassRepository.ExistsReserveClassRepository(model);
        }

    
        /// <summary>
        /// 根据编号获取约课班级
        /// </summary>
        /// <param name="ReserveClassId"></param>
        /// <returns></returns>
        public RB_Reserve_Class_Extend GetReserveClassModule(int ReserveClassId)
        {
            var extModel = reserve_ClassRepository.GetReserveClassListRepository(new RB_Reserve_Class_Extend() { ReserveClassId = ReserveClassId })?.FirstOrDefault();
            return extModel;
        }

        /// <summary>
        /// 根据编号删除约课班级
        /// </summary>
        /// <param name="ReserveClassId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool RemoveReserveClassModule(int ReserveClassId, UserInfo UserInfo, out string message)
        {
            message = "";
            var visitorReserve = visitor_ReserveRepository.GetVisitorReserveStaticsListRepository(new RB_Visitor_Reserve_Extend()
            {
                Q_ReserveClassIds = ReserveClassId.ToString()
            });
            if ((visitorReserve?.Count ?? 0) > 0)
            {
                message = "此试听课存在客户报名信息,不能删除!";
                return false;
            }
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Visitor_Reserve_Extend.Status),(int)DateStateEnum.Delete  },
            };
            var flag = reserve_ClassRepository.Update(fileds, new WhereHelper(nameof(RB_Reserve_Class_Extend.ReserveClassId), ReserveClassId));
            var model = GetReserveClassModule(ReserveClassId);
            if (model != null)
            {
                var teacherModel = accountRepository.GetAccountListRepository(new RB_Account_ViewModel()
                {
                    Group_Id = model.Group_Id,
                    AccountId = model.TeacherId,
                    AccountType = Common.Enum.User.AccountTypeEnum.Teacher
                })?.FirstOrDefault();
                Common.Message.PushMessageModel pushModel = new Common.Message.PushMessageModel()
                {
                    CategoryId = PushMessageCategoryEnum.ReserveClass,
                    Content = "您有试听课信息被取消!请查收",
                    CoverImg = "",
                    CreateByName = UserInfo.AccountName,
                    JumpUrl = $"/course/classPlan?ClassType=2",
                    SendTime = DateTime.Now,
                    SendType = 0,
                    Title = "试听课",
                    Platform = 2,
                    ReceiveId = (teacherModel?.Id ?? 0).ToString(),
                };
                if (flag)
                {
                    Common.Message.MessageHelper.SendMessage(pushModel);
                }
            }
            return flag;
        }
    }
}
