using Edu.Common.Enum;
using Edu.Model.ViewModel.Customer;
using Edu.Repository.Customer;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Text;
using VT.FW.DB;
using System.Linq;
using Edu.Model.ViewModel.User;
using Edu.Common.Plugin;
using Edu.Repository.System;
using Edu.Model.Entity.System;
using Edu.Model.ViewModel.System;
using Edu.Cache.Customer;
using Edu.Repository.StudyAbroad;
using Edu.Model.ViewModel.StudyAbroad;
using Edu.Common.Enum.System;

namespace Edu.Module.Customer
{
    /// <summary>
    /// 客户学员处理类对象
    /// </summary>
    public class CustomerStudentModule
    {
        /// <summary>
        /// 学员约访表仓储层对象
        /// </summary>
        private readonly RB_Student_AppointmentRepository student_AppointmentRepository = new RB_Student_AppointmentRepository();

        /// <summary>
        /// 学员跟进仓储层对象
        /// </summary>
        private readonly RB_Student_FollowRepository student_FollowRepository = new RB_Student_FollowRepository();

        /// <summary>
        /// 学员到访表仓储层对象
        /// </summary>
        private readonly RB_Student_VisitRepository student_VisitRepository = new RB_Student_VisitRepository();

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

        /// <summary>
        /// 校区仓储层对象
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();

        /// <summary>
        /// 员工对象仓储层对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

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

        /// <summary>
        /// 学员协助人员仓储层对象
        /// </summary>
        private readonly RB_Student_AssistRepository student_AssistRepository = new RB_Student_AssistRepository();

        /// <summary>
        /// 客户阶段仓储层对象
        /// </summary>
        private readonly RB_StageRepository stageRepository = new RB_StageRepository();

        /// <summary>
        /// 客户类型仓储层对象
        /// </summary>
        private readonly RB_Student_TypeRepository student_TypeRepository = new RB_Student_TypeRepository();

        /// <summary>
        /// 学习目的仓储层对象
        /// </summary>
        private readonly RB_LearningGoalsRepository learningGoalsRepository = new RB_LearningGoalsRepository();

        /// <summary>
        /// 来源渠道仓储层对象
        /// </summary>
        private readonly RB_ChannelRepository channelRepository = new RB_ChannelRepository();

        /// <summary>
        /// 客户需求仓储层对象
        /// </summary>
        private readonly RB_NeedsRepository needsRepository = new RB_NeedsRepository();

        private readonly Rb_dictvalueRepository dictvalueRepository = new Rb_dictvalueRepository();

        /// <summary>
        /// 留学就业项目仓储层对象
        /// </summary>
        private readonly RB_StudyAbroadRepository studyAbroadRepository = new RB_StudyAbroadRepository();

        /// <summary>
        /// 学员仓储层对象
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();


        #region 学员约访

        /// <summary>
        /// 获取学员约访分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Appointment_Extend> GetStudentAppointmentPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_Appointment_Extend query)
        {
            return student_AppointmentRepository.GetStudentAppointmentPageRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 新增学员约访
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStudentAppointmentModule(RB_Student_Appointment_Extend model)
        {
            bool flag = false;
            string logContent = "";
            string logTitle = "";
            if (model.Id > 0)
            {
                var oldModel = GetStudentAppointmentModule(model.Id);
                if (oldModel.AppointmentPoint != model.AppointmentPoint)
                {
                    logContent += string.Format("约访地点：由【{0}】=>【{1}】,", oldModel.AppointmentPoint, model.AppointmentPoint);
                }
                if (oldModel.AppointmentTime != model.AppointmentTime)
                {
                    logContent += string.Format("约访时间：由【{0}】=>【{1}】,", oldModel.AppointmentTime, model.AppointmentTime);
                }
                if (oldModel.Remark != model.Remark)
                {
                    logContent += string.Format("备注：由【{0}】=>【{1}】,", oldModel.Remark, model.Remark);
                }
                if (oldModel.Feedback != model.Feedback)
                {
                    logContent += string.Format("反馈：由【{0}】=>【{1}】,", oldModel.Feedback, model.Feedback);
                }
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_Appointment_Extend.AppointmentPoint),model.AppointmentPoint },
                    {nameof(RB_Student_Appointment_Extend.AppointmentTime),model.AppointmentTime },
                    {nameof(RB_Student_Appointment_Extend.Remark),model.Remark },
                };
                flag = student_AppointmentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Appointment_Extend.Id), model.Id));
                logTitle = "修改学员约访";
            }
            else
            {
                var newId = student_AppointmentRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
                logTitle = "新增学员约访";
                logContent = model.Remark;
                if (flag) {
                    //增加 跟进记录
                    #region 验证用户的类型
                    var assistList = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend() { StuId = model.StuId });
                    var assistModel = assistList.Where(x => x.AssistId == model.CreateBy).FirstOrDefault();
                    var AssistType = assistModel?.AssistType ?? 0;
                    #endregion
                    
                    student_FollowRepository.Insert(new Model.Entity.Customer.RB_Student_Follow()
                    {
                        StuId = model.StuId,
                        AssistType = AssistType,
                        CreateBy = model.CreateBy,
                        CreateTime = model.CreateTime,
                        Group_Id = model.Group_Id,
                        Id = 0,
                        Remark = $"客人约访：约访时间【{ Common.ConvertHelper.FormatTimeStr2(model.AppointmentTime)}】，约访地点【{model.AppointmentPoint}】，备注【{model.Remark}】",
                        Status = DateStateEnum.Normal,
                        UpdateBy = model.UpdateBy,
                        UpdateTime = model.UpdateTime
                    });
                }
            }
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.Appointment, logTitle, logContent, model.CreateBy);
            return flag;
        }

        /// <summary>
        /// 新增修改约访反馈
        /// </summary>
        /// <param name="Feedback"></param>
        /// <param name="Id"></param>
        /// <param name="OperateId"></param>
        /// <returns></returns>
        public bool SetStudentAppointmentFeedBackModule(string Feedback, int Id, int OperateId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_Appointment_Extend.Feedback),Feedback },
            };
            var oldModel = GetStudentAppointmentModule(Id);
            string logTitle = "修改约访";
            string logContent = "";
            if (oldModel.Feedback != Feedback)
            {
                logContent += string.Format("反馈信息：由【{0}】=>【{1}】", oldModel.Feedback, Feedback);
            }
            bool flag = student_AppointmentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Appointment_Extend.Id), Id));
            student_LogRepository.AddStuLogRepository(oldModel.StuId, Common.Enum.Log.StudentLogTypeEnum.Appointment, logTitle, logContent, OperateId);
            return flag;
        }

        /// <summary>
        /// 根据编号获取学员约访信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Student_Appointment_Extend GetStudentAppointmentModule(object Id)
        {
            var extModel = student_AppointmentRepository.GetEntity<RB_Student_Appointment_Extend>(Id);
            return extModel;
        }

        /// <summary>
        /// 删除学员约访
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveStudentAppointmentModule(object Id, int Uid)
        {
            bool flag = false;
            var model = GetStudentAppointmentModule(Id);
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Student_Appointment_Extend.Status),(int)DateStateEnum.Delete}
            };
            flag = student_AppointmentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Appointment_Extend.Id), Id));
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.Appointment, "删除约访", "删除约访信息", Uid);
            return flag;
        }

        #endregion

        #region 学员跟进

        /// <summary>
        /// 获取学员跟进分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Follow_Extend> GetStudentFollowPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_Follow_Extend query)
        {
            return student_FollowRepository.GetStudentFollowPageRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 新增修改学员跟进
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStudentFollowModule(RB_Student_Follow_Extend model)
        {
            bool flag = false;
            string logContent = "";
            string logTitle = "";
            var assistList = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend() { StuId = model.StuId });
            if (model.Id > 0)
            {
                var oldModel = GetStudentFollowModule(model.Id);
                if (oldModel.Remark != model.Remark)
                {
                    logContent += string.Format("跟进内容：由【{0}】=>【{1}】", oldModel.Remark, model.Remark);
                }
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_Follow_Extend.Remark),model.Remark }
                };
                flag = student_FollowRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Follow_Extend.Id), model.Id));
                logTitle = "修改跟进内容";
            }
            else
            {
                #region 验证用户的类型

                var assistModel = assistList.Where(x => x.AssistId == model.CreateBy).FirstOrDefault();
                model.AssistType = assistModel?.AssistType ?? 0;
                #endregion
                var newId = student_FollowRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
                logTitle = "新增跟进";
                logContent = model.Remark;
             
            }
            try
            {
                var smodel = studentRepository.GetEntity(model.StuId);
                string markdownContent = $"`学员跟进通知` \n>**概要信息** \n>学员名称：{smodel?.StuName ?? ""}\n>跟进内容：{model.Remark} \n>";
                Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                {
                    CategoryId = PushMessageCategoryEnum.B2BCustomerStu,
                    Content = markdownContent,
                    CoverImg = "",
                    CreateByName = "系统",
                    JumpUrl = "",
                    WorkMsgType = "markdown",
                    SendTime = DateTime.Now,
                    SendType = 0,
                    Title = "新增学员跟进通知",
                    Platform = 5,
                };
                if (smodel != null && smodel.CreateBy > 0)
                {
                    var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(smodel.CreateBy);
                    if (!string.IsNullOrEmpty(queryTargetWorkId))
                    {
                        modelWork.ReceiveId = queryTargetWorkId;
                        Common.Message.MessageHelper.SendMessage(modelWork);
                    }
                }
                if (assistList != null && assistList.Count > 0)
                {
                    foreach (var item in assistList)
                    {
                        var queryTargetWorkId = accountRepository.GetWorkUserIdRepository(item.AssistId);
                        if (!string.IsNullOrEmpty(queryTargetWorkId))
                        {
                            modelWork.ReceiveId = queryTargetWorkId;
                            Common.Message.MessageHelper.SendMessage(modelWork);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetStudentFollowModule");
            }
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.Follow, logTitle, logContent, model.CreateBy);
            return flag;
        }

 

        /// <summary>
        /// 根据编号获取学员跟进信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Student_Follow_Extend GetStudentFollowModule(object Id)
        {
            var extModel = student_FollowRepository.GetEntity<RB_Student_Follow_Extend>(Id);
            return extModel;
        }

        /// <summary>
        /// 根据跟进编号删除学员跟进信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveStudentFollowModule(object Id, int Uid)
        {
            var model = GetStudentFollowModule(Id);
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_Follow_Extend.Status), (int)DateStateEnum.Delete}
            };
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.Follow, "删除跟进", "删除跟进信息", Uid);
            return student_FollowRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Follow_Extend.Id), Id));
        }
        #endregion

        #region 学员到访

        /// <summary>
        /// 获取学员到访分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Visit_Extend> GetStudentVisitPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_Visit_Extend query)
        {
            var list = student_VisitRepository.GetStudentVisitPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string sids = string.Join(",", list.Select(qitem => qitem.School_Id));
                string empIds = string.Join(",", list.Select(qitem => qitem.ReceptionPersion));
                var schoolList = schoolRepository.GetSchoolListRepository(new Model.ViewModel.User.RB_School_ViewModel()
                {
                    QSIds = sids
                });
                var empList = accountRepository.GetEmployeeListRepository(new Model.ViewModel.User.Employee_ViewModel()
                {
                    QIds = empIds
                });
                foreach (var item in list)
                {
                    item.SchoolName = schoolList?.FirstOrDefault(qitem => qitem.SId == item.School_Id)?.SName ?? "";
                    item.ReceptionPersionName = empList?.FirstOrDefault(qitem => qitem.Id == item.ReceptionPersion)?.EmployeeName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取到访列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Visit_Extend> GetStudentVisitListModule(RB_Student_Visit_Extend query)
        {
            var list = student_VisitRepository.GetStudentVisitListRepository(query);
            if (list != null && list.Count > 0)
            {
                string sids = string.Join(",", list.Select(qitem => qitem.School_Id));
                string empIds = string.Join(",", list.Select(qitem => qitem.ReceptionPersion));
                var schoolList = schoolRepository.GetSchoolListRepository(new Model.ViewModel.User.RB_School_ViewModel()
                {
                    QSIds = sids
                });
                var empList = accountRepository.GetEmployeeListRepository(new Model.ViewModel.User.Employee_ViewModel()
                {
                    QIds = empIds
                });
                foreach (var item in list)
                {
                    item.SchoolName = schoolList?.FirstOrDefault(qitem => qitem.SId == item.School_Id)?.SName ?? "";
                    item.ReceptionPersionName = empList?.FirstOrDefault(qitem => qitem.Id == item.ReceptionPersion)?.EmployeeName ?? "";
                    item.ReceptionPersionTel = empList?.FirstOrDefault(qitem => qitem.Id == item.ReceptionPersion)?.EmployeeTel ?? "";

                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改学员到访
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStudentVisitModule(RB_Student_Visit_Extend model)
        {
            bool flag = false;
            string logContent = "";
            string logTitle = "";
            if (model.Id > 0)
            {
                var oldModel = GetStudentVisitModule(model.Id);
                logTitle = "修改到访";
                if (oldModel.School_Id != model.School_Id)
                {
                    var schoolList = schoolRepository.GetSchoolListRepository(new Model.ViewModel.User.RB_School_ViewModel() { QSIds = oldModel.School_Id + "," + model.School_Id });
                    logContent += string.Format("校区：由【{0}】=>【{1}】,",
                        schoolList.FirstOrDefault(qitem => qitem.SId == oldModel.School_Id)?.SName,
                        schoolList.FirstOrDefault(qitem => qitem.SId == model.School_Id)?.SName);
                }
                if (oldModel.Date != model.Date)
                {
                    logContent += string.Format("日期：由【{0}】=>【{1}】,", Common.ConvertHelper.FormatDate(oldModel.Date), Common.ConvertHelper.FormatDate(model.Date));
                }
                if (oldModel.VisitTime != model.VisitTime)
                {
                    logContent += string.Format("到访时间：由【{0}】=>【{1}】,", oldModel.VisitTime, model.VisitTime);
                }
                if (oldModel.ReceptionPersion != model.ReceptionPersion)
                {
                    var empList = accountRepository.GetEmployeeListRepository(new Model.ViewModel.User.Employee_ViewModel()
                    {
                        QIds = oldModel.ReceptionPersion + "," + model.ReceptionPersion
                    });
                    logContent += string.Format("接待人：由【{0}】=>【{1}】,",
                        empList?.FirstOrDefault(qitem => qitem.Id == oldModel.ReceptionPersion)?.EmployeeName,
                        empList?.FirstOrDefault(qitem => qitem.Id == model.ReceptionPersion)?.EmployeeName);
                }
                if (oldModel.Remark != model.Remark)
                {
                    logContent += string.Format("备注：由【{0}】=>【{1}】,", oldModel.Remark, model.Remark);
                }
                if (oldModel.Feedback != model.Feedback)
                {
                    logContent += string.Format("反馈信息：由【{0}】=>【{1}】,", oldModel.Feedback, model.Feedback);
                }
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_Visit_Extend.School_Id),model.School_Id },
                    {nameof(RB_Student_Visit_Extend.Date),model.Date },
                    {nameof(RB_Student_Visit_Extend.VisitTime),model.VisitTime },
                    {nameof(RB_Student_Visit_Extend.ReceptionPersion),model.ReceptionPersion },
                    {nameof(RB_Student_Visit_Extend.Remark),model.Remark },
                };
                flag = student_VisitRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Visit_Extend.Id), model.Id));
            }
            else
            {
                var newId = student_VisitRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
                logTitle = "新增到访";
                logContent = model.Remark;
                if (flag)
                {
                    //增加 跟进记录
                    #region 验证用户的类型
                    var assistList = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend() { StuId = model.StuId });
                    var assistModel = assistList.Where(x => x.AssistId == model.CreateBy).FirstOrDefault();
                    var AssistType = assistModel?.AssistType ?? 0;
                    #endregion
                    student_FollowRepository.Insert(new Model.Entity.Customer.RB_Student_Follow()
                    {
                        StuId = model.StuId,
                        AssistType = AssistType,
                        CreateBy = model.CreateBy,
                        CreateTime = model.CreateTime,
                        Group_Id = model.Group_Id,
                        Id = 0,
                        Remark = $"客人到访：到访时间【{Common.ConvertHelper.FormatDate(model.Date) + " " + model.VisitTime}】，到访校区【{schoolRepository.GetEntity(model.School_Id)?.SName ?? ""}】，接待人【{accountRepository.GetEmployeeInfo(model.ReceptionPersion)?.EmployeeName ?? ""}】，备注【{model.Remark}】",
                        Status = DateStateEnum.Normal,
                        UpdateBy = model.UpdateBy,
                        UpdateTime = model.UpdateTime
                    });

                    //获取学生信息
                    //var smodel = studentRepository.GetEntity(model.StuId);
                    //if (smodel != null && smodel.StuStage == Common.Enum.User.StuStageEnum.NewStu)
                    //{
                    //    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    //        { nameof(RB_Student_ViewModel.StuStage), Common.Enum.User.StuStageEnum.PreliminaryCommunication}
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //            FiledName = nameof (RB_Student_ViewModel.StuId),
                    //                FiledValue = model.StuId,
                    //                OperatorEnum =OperatorEnum.Equal
                    //            }
                    //    };
                    //    studentRepository.Update(keyValues, wheres);
                    //    student_LogRepository.Insert(new Model.Entity.Customer.RB_Student_Log()
                    //    {
                    //        LogId = 0,
                    //        CreateBy = model.CreateBy,
                    //        CreateTime = DateTime.Now,
                    //        CreateType = 1,
                    //        Group_Id = model.Group_Id,
                    //        LogContent = "首次拜访，客户阶段由'" + (Common.Enum.User.StuStageEnum.NewStu.ToName()) + "'自动转换为'" + (Common.Enum.User.StuStageEnum.PreliminaryCommunication.ToName()) + "'",
                    //        LogTitle = "客户阶段变更",
                    //        LogType = Common.Enum.Log.StudentLogTypeEnum.BasicInfo,
                    //        StuId = model.StuId
                    //    });
                    //}
                }
            }
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.Visit, logTitle, logContent, model.CreateBy);
            return flag;
        }

        /// <summary>
        /// 新增修改反馈
        /// </summary>
        /// <param name="Feedback"></param>
        /// <param name="Id"></param>
        /// <param name="OperateId"></param>
        /// <returns></returns>
        public bool SetStudentVisitFeedbackModule(string Feedback, int Id, int OperateId, int IsVisit)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_Visit_Extend.Feedback),Feedback },
                {nameof(RB_Student_Visit_Extend.IsVisit),IsVisit },
            };
            var oldModel = GetStudentVisitModule(Id);
            string logTitle = "修改到访";
            string logContent = "";
            if (oldModel.Feedback != Feedback)
            {
                logContent += string.Format("反馈信息：由【{0}】=>【{1}】", oldModel.Feedback, Feedback);
            }
            if (oldModel.IsVisit != IsVisit)
            {
                logContent += string.Format("到访状态：由【{0}】=>【{1}】", oldModel.IsVisitStr, (IsVisit == 1 ? "已到访" : "未到访"));
            }
            bool flag = student_VisitRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Visit_Extend.Id), Id));
            student_LogRepository.AddStuLogRepository(oldModel.StuId, Common.Enum.Log.StudentLogTypeEnum.Visit, logTitle, logContent, OperateId);
            return flag;
        }

        /// <summary>
        /// 根据编号获取学员到访信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public RB_Student_Visit_Extend GetStudentVisitModule(object id)
        {
            var extModel = student_VisitRepository.GetEntity<RB_Student_Visit_Extend>(id);
            return extModel;
        }

        /// <summary>
        /// 根据到访编号删除学员到访信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveStudentVisitModule(object Id, int Uid)
        {
            var model = GetStudentVisitModule(Id);
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_Visit_Extend.Status), (int)DateStateEnum.Delete}
            };
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.Visit, "删除到访", "删除客户到访", Uid);
            return student_VisitRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Visit_Extend.Id), Id));
        }
        #endregion

        #region 学员日志

        /// <summary>
        /// 获取学员日志分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Log_Extend> GetStudentLogPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_Log_Extend query)
        {
            var list = student_LogRepository.GetStudentLogPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        #endregion

        #region 学员订单和合同

        

        /// <summary>
        /// 获取学员关联订单分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_OrderGuest_ViewModel> GetStuOrderGuestPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_OrderGuest_ViewModel query)
        {
            var list = student_OrderGuestRepository.GetStuOrderGuestPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                var tempList = list?.Where(qitem => qitem.OrderType == Common.Enum.Sale.OrderTypeEnum.StudyabroadOrder && qitem.SourceId > 0)?.ToList();
                List<RB_StudyAbroad_ViewModel> studyList = new List<RB_StudyAbroad_ViewModel>();
                if (tempList != null)
                {
                    string SourceIds = string.Join(",", tempList.Select(qitem => qitem.SourceId));
                    if (!string.IsNullOrEmpty(SourceIds))
                    {
                        studyList = studyAbroadRepository.GetStudyAbroadListRepository(new RB_StudyAbroad_ViewModel()
                        {
                            QIds = SourceIds
                        });
                    }
                }
                foreach (var item in list)
                {
                    if (item.OrderType == Common.Enum.Sale.OrderTypeEnum.StudyabroadOrder && item.SourceId > 0)
                    {
                        item.CourseId = item.SourceId;
                        item.CourseName = studyList?.Where(qitem => qitem.Id == item.SourceId)?.FirstOrDefault()?.Name ?? "";
                    }
                }
            }
            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_Student_OrderGuest_ViewModel> GetStuOrderGuestContractPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_OrderGuest_ViewModel query)
        {
            var list = student_OrderGuestRepository.GetStuContractGuestPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        #endregion

        #region 协助人员

        /// <summary>
        /// 新增修改协助人员
        /// </summary>
        /// <param name="StuId"></param>
        /// <param name="AssistList"></param>
        /// <returns></returns>
        public bool SetStudentAssistModule(int StuId, RB_Student_Assist_Extend model, int Uid)
        {
            bool flag = true;
            string logTitle = "协助人员";
            string logContent = "";
            var oldModel = student_AssistRepository.GetEntity(model.Id);
            model.CreateBy = Uid;
            model.CreateTime = DateTime.Now;
            List<Employee_ViewModel> empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
            {
                QIds = (oldModel?.AssistId ?? 0) + "," + model.AssistId
            });

            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_Assist_Extend.AssistType),model.AssistType },
                    {nameof(RB_Student_Assist_Extend.AssistId),model.AssistId },
                };
                if (oldModel!=null&&oldModel.AssistId != model.AssistId)
                {
                    logContent += string.Format("修改协同人员：【0】=>【{1}】",
                                 empList?.FirstOrDefault(qitem => qitem.Id == (oldModel?.AssistId ?? 0))?.EmployeeName,
                                 empList?.FirstOrDefault(qitem => qitem.Id == model.AssistId)?.EmployeeName
                                 );
                }
                if (oldModel != null && oldModel.AssistType != model.AssistType)
                {
                    logContent += string.Format("修改协同类型：【0】=>【{1}】", oldModel.AssistType.ToName(), model.AssistType.ToName());
                }
                flag = student_AssistRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Assist_Extend.Id), model.Id));
            }
            else
            {
                logContent += string.Format("新增协同人员:" + empList?.FirstOrDefault(qitem => qitem.Id == model.AssistId)?.EmployeeName);
                var newId = student_AssistRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }

            student_LogRepository.AddStuLogRepository(StuId, Common.Enum.Log.StudentLogTypeEnum.BasicInfo, logTitle, logContent, Uid);
            return flag;
        }


        /// <summary>
        /// 删除协助人员
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Uid"></param>
        /// <returns></returns>
        public bool RemoveStudentAssistModule(int Id, int Uid)
        {
            bool flag = false;
            string logTitle = "删除协助人员";
            string logContent = "";
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_Assist_Extend.Status),(int)DateStateEnum.Delete}
            };
            var model = student_AssistRepository.GetEntity(Id);

            var empModel = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
            {
                QIds = model.AssistId.ToString()
            })?.FirstOrDefault();
            logContent += string.Format("删除协助人员：{0}", empModel?.EmployeeName);
            student_LogRepository.AddStuLogRepository(model.StuId, Common.Enum.Log.StudentLogTypeEnum.BasicInfo, logTitle, logContent, Uid);
            flag = student_AssistRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Assist_Extend.Id), Id));
            return flag;
        }

        /// <summary>
        /// 检查协助类型是否存在
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public bool CheckAssistTypeExistsModule(RB_Student_Assist_Extend query)
        {
            List<WhereHelper> list = new List<WhereHelper>
            {
                new WhereHelper(nameof(RB_Student_Assist_Extend.AssistType), (int)query.AssistType),
                new WhereHelper(nameof(RB_Student_Assist_Extend.Status), (int)DateStateEnum.Normal),
                new WhereHelper(nameof(RB_Student_Assist_Extend.StuId), query.StuId)
            };
            if (query.Id > 0)
            {
                list.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Student_Assist_Extend.Id),
                    FiledValue = query.Id,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            return student_AssistRepository.Exists(list);
        }

        public (bool result, string msg) SetStudentAssistBatchModule(string studIds,int uid)
        {
            var tempList = studIds.Split(',', StringSplitOptions.RemoveEmptyEntries);
            var pushKey = "PUSH_STU_UNION_EMP";
            var pushRule = "PUSH_STU_RULETYPE";
            if (tempList.Length > 0)
            {
                var push = dictvalueRepository.GetList(new RB_Dictvalue_Extend() { DictKey = pushKey }).FirstOrDefault();
                var rule = dictvalueRepository.GetList(new RB_Dictvalue_Extend() { DictKey = pushRule }).FirstOrDefault();
                var guwen = push.Content.Split(',', StringSplitOptions.RemoveEmptyEntries);
                var guwenName = push.Mask.Split(',', StringSplitOptions.RemoveEmptyEntries);
                if (guwen.Length > 1)
                {
                    if (rule.Content.Equals("1"))
                    {
                        var mask = string.Empty;
                        tempList.ToList().ForEach(x =>
                        {
                            Random ran = new Random();
                            var cur = ran.Next(0, guwen.Length - 1);
                            var model = new RB_Student_Assist_Extend()
                            {
                                Id = 0,
                                AssistId = int.Parse(guwen[cur]),
                                AssistType = Common.Enum.User.AssistTypeEnum.CourseAdviser,
                                StuId = int.Parse(x),
                                Status = Common.Enum.DateStateEnum.Normal
                            };
                            SetStudentAssistModule(int.Parse(x), model, uid);
                            mask += mask.Contains("," + guwenName[cur]) ? "" : "," + guwenName[cur];
                        });
                        return (true, "学员批量转课程顾问成功，已分别转给顾问：" + mask);
                    }
                    else
                    {
                        var mask = string.Empty;
                        tempList.ToList().ForEach(x =>
                        {
                            var cache = CustomerRedisCache.Get();
                            if (cache >= guwen.Length)
                            {
                                CustomerRedisCache.Set(1);
                                cache = 0;
                            }
                            var model = new RB_Student_Assist_Extend()
                            {
                                Id = 0,
                                AssistId = int.Parse(guwen[cache]),
                                AssistType = Common.Enum.User.AssistTypeEnum.CourseAdviser,
                                StuId = int.Parse(x),
                                Status = Common.Enum.DateStateEnum.Normal
                            };
                            SetStudentAssistModule(int.Parse(x), model, uid);
                            mask += mask.Contains("," + guwenName[cache]) ? "" : "," + guwenName[cache];
                        });
                        return (true, "学员批量转课程顾问成功，已分别转给顾问：" + mask);
                    }
                }
                else
                {
                    tempList.ToList().ForEach(x =>
                    {
                        var model = new RB_Student_Assist_Extend()
                        {
                            Id = 0,
                            AssistId = int.Parse(guwen[0]),
                            AssistType = Common.Enum.User.AssistTypeEnum.CourseAdviser,
                            StuId = int.Parse(x),
                            Status = Common.Enum.DateStateEnum.Normal
                        };
                        SetStudentAssistModule(int.Parse(x), model, uid);
                    });
                    return (true, "学员批量转课程顾问成功，已全部转给顾问：" + push.Mask);
                }
            }
            else 
            {
                return (false, "未获取到学员信息");
            }
        }

        /// <summary>
        /// 获取学员协助人员列表
        /// </summary>
        /// <param name="StuId"></param>
        /// <returns></returns>
        public List<RB_Student_Assist_Extend> GeStudentAssistListModule(int StuId)
        {
            var list = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend()
            {
                StuId = StuId
            });
            string aIds = string.Join(",", list.Select(qitem => qitem.AssistId));
            List<RB_Account_ViewModel> accountList = new List<RB_Account_ViewModel>();
            if (!string.IsNullOrEmpty(aIds))
            {
                accountList = accountRepository.GetAccountListExtRepository(new RB_Account_ViewModel() { QIds = aIds });
            }
            foreach (var item in list)
            {
                item.AssistName = accountList?.FirstOrDefault(qitem => qitem.Id == item.AssistId)?.AccountName ?? "";
            }
            return list;
        }

        #endregion

        #region 客户阶段

        /// <summary>
        /// 获取客户阶段列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Stage> GetStageListModule(RB_Stage query)
        {
            var list = stageRepository.GetStageListRepostory(query);
            return list;
        }

        /// <summary>
        /// 新增修改客户阶段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStageModule(RB_Stage model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Stage.No),model.No },
                    {nameof(RB_Stage.StageName),model.StageName },
                    {nameof(RB_Stage.UpdateBy),model.UpdateBy },
                    {nameof(RB_Stage.UpdateTime),model.UpdateTime },
                };
                flag = stageRepository.Update(fileds, new WhereHelper(nameof(RB_Stage.Id), model.Id));
            }
            else
            {
                var newId = stageRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 删除客户阶段
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemodeStageModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Stage.Status),(int)DateStateEnum.Delete },
            };
            bool flag = stageRepository.Update(fileds, new WhereHelper(nameof(RB_Stage.Id), Id));
            return flag;
        }

        #endregion

        #region 客户类型
        /// <summary>
        /// 获取客户类型列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Type_Extend> GetStudentTypeListModule(RB_Student_Type_Extend query)
        {
            var list = student_TypeRepository.GetStudentTypeListRepository(query);
            return list;
        }

        /// <summary>
        /// 新增修改客户类型
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStudentTypeModule(RB_Student_Type_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_Type_Extend.No),model.No },
                    {nameof(RB_Student_Type_Extend.Name),model.Name },
                    {nameof(RB_Student_Type_Extend.Info),model.Info },
                    {nameof(RB_Student_Type_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Student_Type_Extend.UpdateTime),model.UpdateTime },
                };
                flag = student_TypeRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Type_Extend.Id), model.Id));
            }
            else
            {
                var newId = student_TypeRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 删除客户类型
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemodeStudentTypeModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_Type_Extend.Status),(int)DateStateEnum.Delete },
            };
            bool flag = student_TypeRepository.Update(fileds, new WhereHelper(nameof(RB_Stage.Id), Id));
            return flag;
        }
        #endregion

        #region 学习目的

        /// <summary>
        /// 获取学习目的分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_LearningGoals_Extend> GetLearningGoalsPageModule(int pageIndex, int pageSize, out long rowsCount, RB_LearningGoals_Extend query)
        {
            var list = learningGoalsRepository.GetLearningGoalsPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 获取学习目的列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_LearningGoals_Extend> GetLearningGoalsListModule(RB_LearningGoals_Extend query)
        {
            var list = learningGoalsRepository.GetLearningGoalsListRepository(query);
            return list;
        }

        /// <summary>
        /// 获取学习目的实体类
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_LearningGoals_Extend GetLearningGoalsExtEntityModule(int Id)
        {
            var extModel = learningGoalsRepository.GetLearningGoalsExtEntityRepository(Id);
            return extModel;
        }

        /// <summary>
        /// 新增修改学习目的
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetLearningGoalsModule(RB_LearningGoals_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_LearningGoals_Extend.Name),model.Name },
                    {nameof(RB_LearningGoals_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_LearningGoals_Extend.UpdateTime),model.UpdateTime },
                };
                flag = learningGoalsRepository.Update(fileds, new WhereHelper(nameof(RB_LearningGoals_Extend.Id), model.Id));
            }
            else
            {
                var newId = learningGoalsRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;

        }

        /// <summary>
        /// 删除学习目的
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveLearningGoalsModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_LearningGoals_Extend.Status),(int)DateStateEnum.Delete },
            };
            bool flag = learningGoalsRepository.Update(fileds, new WhereHelper(nameof(RB_LearningGoals_Extend.Id), Id));
            return flag;
        }

        #endregion

        #region 客户渠道
        /// <summary>
        /// 获取渠道分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Channel_Extend> GetChannelPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Channel_Extend query)
        {
            var list = channelRepository.GetChannelPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }


        /// <summary>
        /// 获取渠道列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Channel_Extend> GetChannelListModule(RB_Channel_Extend query)
        {
            var list = channelRepository.GetChannelListRepository(query);
            return list;
        }

        /// <summary>
        /// 获取学习目的实体类
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Channel_Extend GetChannelExtEntityModule(int Id)
        {
            var extModel = channelRepository.GetChannelExtEntityRepository(Id);
            return extModel;
        }

        /// <summary>
        /// 新增修改收客渠道
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetChannelModule(RB_Channel_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Channel_Extend.Name),model.Name },
                    {nameof(RB_Channel_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Channel_Extend.UpdateTime),model.UpdateTime },
                    {nameof(RB_Channel_Extend.StaticType),model.StaticType },
                };
                flag = channelRepository.Update(fileds, new WhereHelper(nameof(RB_Channel_Extend.Id), model.Id));
            }
            else
            {
                var newId = channelRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 删除收客渠道
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveChannelModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Channel_Extend.Status),(int)DateStateEnum.Delete},
            };
            var flag = channelRepository.Update(fileds, new WhereHelper(nameof(RB_Channel_Extend.Id), Id));
            return flag;
        }
        #endregion

        #region 客户需求

        /// <summary>
        /// 获取客户需求分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Needs_Extend> GetNeedsPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Needs_Extend query)
        {
            var list = needsRepository.GetNeedsPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 获取客户需求列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Needs_Extend> GetNeedsListModule(RB_Needs_Extend query)
        {
            var list = needsRepository.GetNeedsListRepository(query);
            return list;
        }

        /// <summary>
        /// 获取客户需求实体类
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Needs_Extend GetNeedsExtEntityModule(int Id)
        {
            var extModel = needsRepository.GetNeedsExtEntityRepository(Id);
            return extModel;
        }

        /// <summary>
        /// 新增修改客户需求
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetNeedsModule(RB_Needs_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Needs_Extend.Name),model.Name },
                    {nameof(RB_Needs_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Needs_Extend.UpdateTime),model.UpdateTime },
                };
                flag = needsRepository.Update(fileds, new WhereHelper(nameof(RB_Needs_Extend.Id), model.Id));
            }
            else
            {
                var newId = needsRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 删除客户需求
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveNeedsModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Needs_Extend.Status),(int)DateStateEnum.Delete},
            };
            var flag = needsRepository.Update(fileds, new WhereHelper(nameof(RB_Needs_Extend.Id), Id));
            return flag;
        }
        #endregion
    }
}
