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

namespace Edu.Module.User
{
    /// <summary>
    /// 学生处理类
    /// </summary>
    public class StudentModule
    {
        /// <summary>
        /// 学生仓储层对象
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();
        /// <summary>
        /// 日志
        /// </summary>
        private readonly RB_Student_LogRepository student_LogRepository = new RB_Student_LogRepository();
        /// <summary>
        /// 地区仓储层对象
        /// </summary>
        private readonly RB_DestinationRepository destinationRepository = new RB_DestinationRepository();

        /// <summary>
        /// 同业
        /// </summary>
        private readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();

        /// <summary>
        /// 账号处理类
        /// </summary>
        private readonly AccountModule accountModule = new AccountModule();

        /// <summary>
        /// 小程序用户仓储层对象  add by:W  2021-09-15
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();

        /// <summary>
        /// 学员订单关联表仓储层
        /// </summary>

        private readonly RB_Student_OrderGuestRepository student_OrderGuestRepository = new RB_Student_OrderGuestRepository();

        /// <summary>
        /// 学员跟进
        /// </summary>
        private readonly RB_Student_FollowRepository followRepository = new RB_Student_FollowRepository();

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

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

        /// <summary>
        /// 学员试听课仓储层对象
        /// </summary>
        private readonly RB_Visitor_ReserveRepository visitor_ReserveRepository = new RB_Visitor_ReserveRepository();

        /// <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();

        /// <summary>
        /// 学员约访仓储层对象
        /// </summary>
        private readonly RB_Student_AppointmentRepository student_AppointmentRepository = new RB_Student_AppointmentRepository();

        /// <summary>
        /// 课程顾问跟进配置仓储层对象
        /// </summary>
        private readonly RB_Student_AdvisorConfigRepository student_AdvisorConfigRepository = new RB_Student_AdvisorConfigRepository();

        /// <summary>
        /// 课程顾问跟进仓储层对象
        /// </summary>
        private readonly RB_Student_AdvisorRepository student_AdvisorRepository = new RB_Student_AdvisorRepository();

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

        /// <summary>
        /// 获取学生分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_ViewModel> GetStudentPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_ViewModel query)
        {
            var list = studentRepository.GetStudentPageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                //客户阶段列表
                var stageList = stageRepository.GetStageListRepostory(new Model.Entity.System.RB_Stage()
                {
                    Group_Id = list[0].Group_Id
                });
                //学员类型列表
                var stuTypeList = student_TypeRepository.GetStudentTypeListRepository(new RB_Student_Type_Extend());
                string stuIds = string.Join(",", list.Select(qitem => qitem.StuId));
                //学员跟进
                var followList = followRepository.GetStudentFollowListRepository(new RB_Student_Follow_Extend()
                {
                    QStuIds = stuIds
                });
                //学员订单
                var stuOrderList = student_OrderGuestRepository.GetStrOrderGuestListStaticRepository(new RB_Student_OrderGuest_ViewModel()
                {
                    QStudentIds = stuIds
                });
                //本周新增
                var stuList = studentRepository.GetCustomerStuWeekListRepository(new RB_Student_ViewModel()
                {
                    CustomerId = query.CustomerId
                });
                //协助人员列表
                var assistList = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend()
                {
                    QStuIds = stuIds
                });
                //内部介绍人
                List<int> empIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Where(qitem => qitem.CreateType == StuCreateTypeEnum.InternalIntroduction).Select(qitem => qitem.StuSourceId)));
                List<int> aIds = Common.ConvertHelper.StringToList(string.Join(",", assistList.Select(qitem => qitem.AssistId)));
                List<RB_Account_ViewModel> accountList = new List<RB_Account_ViewModel>();
                if (aIds != null && aIds.Count > 0)
                {
                    empIdList.AddRange(aIds);
                }
                if (empIdList != null && empIdList.Count > 0)
                {
                    accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel() { QIds = string.Join(",", empIdList) });
                }
                //学员到访统计
                var visitList = student_VisitRepository.GetStudentVisitStaticRepository(new RB_Student_Visit_Extend()
                {
                    QStuIds = stuIds
                });
                //学员试听统计
                var stuReserveList = visitor_ReserveRepository.GetStuReserveStaticsListRepository(new Model.ViewModel.Reserve.RB_Visitor_Reserve_Extend()
                {
                    QVisitor_Ids = stuIds
                });
                var provideList = list.Where(qitem => qitem.ProviceId > 0).Select(qitem => qitem.ProviceId).ToList();
                var cityList = list.Where(qitem => qitem.CityId > 0).Select(qitem => qitem.CityId).ToList();
                var areaList = list.Where(qitem => qitem.AreaId > 0).Select(qitem => qitem.AreaId).ToList();
                List<int> ids = new List<int>();
                if (provideList != null && provideList.Count > 0)
                {
                    ids.AddRange(provideList);
                }
                if (cityList != null && cityList.Count > 0)
                {
                    ids.AddRange(cityList);
                }
                if (areaList != null && areaList.Count > 0)
                {
                    ids.AddRange(areaList);
                }
                string qIds = "";
                if (ids != null && ids.Count > 0)
                {
                    qIds = string.Join(",", ids);
                }
                else
                {
                    qIds = "0";
                }
                var destinationList = destinationRepository.GetDestinationListRepository(new Model.ViewModel.System.RB_Destination_ViewModel() { Ids = qIds });

                //同业录入列表
                List<RB_Customer_Extend> customerList = new List<RB_Customer_Extend>();
                List<int> customerIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Where(qitem => qitem.CreateType == StuCreateTypeEnum.CustomerInput).Select(qitem => qitem.StuSourceId)));
                if (customerIdList != null && customerIdList.Count > 0)
                {
                    customerList = customerRepository.GetCustomerListRepository(new RB_Customer_Extend()
                    {
                        CustomerIds = string.Join(",", customerIdList)
                    });
                }
                List<RB_Student_ViewModel> transStudentList = new List<RB_Student_ViewModel>();
                //转介人列表
                List<int> transIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Where(qitem => qitem.CreateType == StuCreateTypeEnum.TransIntroduction).Select(qitem => qitem.StuSourceId)));
                if (transIdList != null && transIdList.Count > 0)
                {
                    transStudentList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel()
                    {
                        StuIds = string.Join(",", transIdList)
                    });
                }

                //学习目的
                string goalIds = string.Join(",", list.Select(qitem => qitem.StuPurpose));
                var goalList = learningGoalsRepository.GetLearningGoalsListRepository(new Model.ViewModel.System.RB_LearningGoals_Extend()
                {
                    QGoalIds = goalIds
                });

                string channelIds = string.Join(",", list.Select(qitem => qitem.StuChannel));
                var channelList = channelRepository.GetChannelListRepository(new Model.ViewModel.System.RB_Channel_Extend()
                {
                    QChannelIds = channelIds
                });

                var needIds = string.Join(",", list.Select(qitem => qitem.StuNeeds));
                var needList = needsRepository.GetNeedsListRepository(new Model.ViewModel.System.RB_Needs_Extend()
                {
                    QNeedsId = needIds
                });

              
                //课程顾问跟进信息
                List<RB_Student_Advisor_Extend> advisorList = student_AdvisorRepository.GetStudentAdvisorListRepository(new RB_Student_Advisor_Extend() { QStuIds = stuIds });

                foreach (var item in list)
                {
                    var tempOrderList = stuOrderList?.Where(qitem => qitem.Student_Id == item.StuId)?.ToList();
                    var tempFollow = followList?.Where(qitem => qitem.StuId == item.StuId)?.OrderByDescending(qitem => qitem.Id)?.FirstOrDefault();
                    item.followUpTime = Common.ConvertHelper.FormatTime(tempFollow?.CreateTime);
                    item.WeekCount = stuList?.Count() ?? 0;
                    item.TodayCount = stuList?.Where(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(DateTime.Now))?.Count() ?? 0;
                    item.OrderCount = tempOrderList?.Count() ?? 0;
                    item.RenewOrderCount = tempOrderList?.Where(qitem => qitem.RenewState == 2)?.Count() ?? 0;
                    item.StuGuestState = tempOrderList?.OrderByDescending(qitem => qitem.OrderId)?.LastOrDefault()?.StuGuestState ?? 0;
                    item.AreaName = (destinationList?.FirstOrDefault(qitem => qitem.ID == item.ProviceId)?.Name ?? "")
                        + "/" + (destinationList?.FirstOrDefault(qitem => qitem.ID == item.CityId)?.Name ?? "")
                        + "/" + (destinationList?.FirstOrDefault(qitem => qitem.ID == item.AreaId)?.Name ?? "");

                    var tempAssistList = assistList?.Where(qitem => qitem.StuId == item.StuId)?.ToList();
                    foreach (var sItem in tempAssistList)
                    {
                        sItem.AssistName = accountList?.FirstOrDefault(qitem => qitem.Id == sItem.AssistId)?.AccountName ?? "";
                    }
                    item.AssistList = tempAssistList;
                    item.VisitCount = visitList?.FirstOrDefault(qitem => qitem.StuId == item.StuId)?.VisitCount ?? 0;
                    item.TrialLessonCount = stuReserveList?.FirstOrDefault(qitem => qitem.Visitor_Id == item.StuId)?.TrialLessonCount ?? 0;
                    if (item.CreateType == StuCreateTypeEnum.InternalIntroduction)
                    {
                        item.StuSourceIdName = accountList?.FirstOrDefault(qitem => qitem.Id == item.StuSourceId)?.AccountName ?? "";
                    }
                    else if (item.CreateType == StuCreateTypeEnum.CustomerInput)
                    {
                        var tempCustomer = customerList?.FirstOrDefault(qitem => qitem.CustomerId == item.StuSourceId);
                        item.StuSourceIdName = tempCustomer?.CustomerName ?? "";
                        if (tempCustomer != null)
                        {
                            if (tempCustomer.CustomerType == Common.Enum.Customer.CatetoryTypeEnum.Other)
                            {
                                item.EnterpriseName = tempCustomer?.EnterpriseName ?? "";
                            }
                            else
                            {
                                item.EnterpriseName = tempCustomer?.CategoryName ?? "";
                            }
                        }
                        else
                        {
                            item.EnterpriseName = "";
                        }
                    }
                    else if (item.CreateType == StuCreateTypeEnum.TransIntroduction)
                    {
                        item.StuSourceIdName = transStudentList?.FirstOrDefault(qitem => qitem.StuId == item.StuSourceId)?.StuName ?? "";
                    }
                    item.StuStageName = stageList?.FirstOrDefault(qitem => qitem.Id == item.StuStage)?.StageName ?? "";
                    item.StuTypeName = stuTypeList?.FirstOrDefault(qitem => qitem.Id == item.StuType)?.Name ?? "";
                    item.StuChannelName = channelList?.FirstOrDefault(qitem => qitem.Id == item.StuChannel)?.Name ?? "";
                    item.StuPurposeName = goalList?.FirstOrDefault(qitem => qitem.Id == item.StuPurpose)?.Name ?? "";
                    item.StuNeedsName = needList?.FirstOrDefault(qitem => qitem.Id == item.StuNeeds)?.Name ?? "";
                    item.AdvisorList = advisorList?.Where(qitem => qitem.StuId == item.StuId)?.ToList() ?? new List<RB_Student_Advisor_Extend>();
                }
            }
            return list;
        }

        /// <summary>
        /// 检查学员是否存在资料库
        /// </summary>
        /// <param name="model"></param>
        /// <param name="Type">1-电话，2-QQ，3-微信号</param>
        /// <returns></returns>
        public bool CheckStudentModule(RB_Student_ViewModel model, int Type)
        {
            List<WhereHelper> where = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Student_ViewModel.Group_Id),model.Group_Id),
                new WhereHelper(nameof(RB_Student_ViewModel.Status),(int)DateStateEnum.Normal),
            };
            if (Type == 1)
            {
                where.Add(new WhereHelper(nameof(RB_Student_ViewModel.StuRealMobile), model.StuRealMobile));
            }
            if (Type == 2)
            {
                where.Add(new WhereHelper(nameof(RB_Student_ViewModel.QQ), model.QQ));
            }
            if (Type == 3)
            {
                where.Add(new WhereHelper(nameof(RB_Student_ViewModel.WeChatNo), model.WeChatNo));
            }
            if (model.StuId > 0)
            {
                where.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Student_ViewModel.StuId),
                    FiledValue = model.StuId,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            var NewId = studentRepository.Exists("StuId", where);
            return NewId > 0;
        }

        /// <summary>
        /// 跟进电话号码获取学员信息
        /// </summary>
        /// <param name="Tel"></param>
        /// <returns></returns>
        public RB_Student_ViewModel CheckExistsStuModule(RB_Student_ViewModel query)
        {
            var model = studentRepository.GetStuByTelRepository(query);
            return model;
        }

        /// <summary>
        /// 添加修改学生
        /// </summary>
        /// <param name="model"></param>
        /// <param name="fromApp">来至于同业  1是</param>
        /// <returns></returns>
        public bool SetStudentModule(RB_Student_ViewModel model, int fromApp = 0)
        {
            bool IsInsert = false;
            if (model.StuId == 0) { IsInsert = true; }
            bool flag = studentRepository.SetStudentRepository(model);
            if (flag)
            {
                if (IsInsert && model.CustomerId > 0 && fromApp == 1)
                {
                    var queryTargetWorkId = accountModule.GetWorkUserIdModule(model.CreateBy);
                    if (!string.IsNullOrEmpty(queryTargetWorkId))
                    {
                        var cmodel = customerRepository.GetEntity(model.CustomerId);
                        var path = $"/sale/visitorRegistrat?StuId={model.StuId}";
                        path = System.Web.HttpUtility.UrlEncode(path);
                        string markdownContent = $"`同业添加学生通知` \n>**概要信息** \n>同业名称：{cmodel.CustomerName}({cmodel.ContactNumber})\n>学生名称：{model.StuName}\n>学生电话：{model.StuTel}\n>请点击：[查看详情]({Common.Config.ErpUrl}/autologin?loginId={model.CreateBy}&target={path})";
                        Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                        {
                            CategoryId = Common.Enum.System.PushMessageCategoryEnum.B2BCustomerStu,
                            Content = markdownContent,
                            CoverImg = "",
                            CreateByName = "系统",
                            JumpUrl = "",
                            WorkMsgType = "markdown",
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "同业添加学生通知",
                            Platform = 5,
                            ReceiveId = queryTargetWorkId
                        };
                        Common.Message.MessageHelper.SendMessage(modelWork);
                    }
                }

            }

            return flag;
        }

        /// <summary>
        /// 修改客户阶段
        /// </summary>
        /// <param name="StuId"></param>
        /// <param name="StuStage"></param>
        /// <param name="Uid"></param>
        /// <returns></returns>
        public bool SetStudentStageModule(int StuId, int StuStage, int Uid)
        {
            return studentRepository.SetStudentStageRepository(StuId, StuStage, Uid);
        }

        /// <summary>
        /// 获取协助人员列表
        /// </summary>
        /// <param name="StuId"></param>
        /// <returns></returns>
        public List<RB_Student_Assist_Extend> GetStuAssistListModule(int StuId)
        {
            var list = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend()
            {
                StuId = StuId
            });
            return list;
        }


        /// <summary>
        /// 学员转交
        /// </summary>
        /// <param name="StuId">学员编号</param>
        /// <param name="CreateBy">负责人</param>
        /// <param name="OperateId">操作人</param>
        /// <returns></returns>
        public bool ForwardStudentModule(int StuId, int CreateBy, int OperateId)
        {
            return studentRepository.ForwardStudentRepository(StuId, CreateBy, OperateId);
        }

        /// <summary>
        /// 根据学生编号获取学生实体类
        /// </summary>
        /// <param name="StuId"></param>
        /// <returns></returns>
        public RB_Student_ViewModel GetStudentModule(int StuId)
        {
            var extModel = studentRepository.GetEntity<RB_Student_ViewModel>(StuId);
            if (extModel != null && extModel.StuId > 0)
            {
                var assistList = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend()
                {
                    StuId = extModel.StuId
                });
                extModel.AssistList = assistList;
                extModel.StuStageName = stageRepository.GetEntity(extModel.StuStage)?.StageName ?? "";
                extModel.StuTypeName = student_TypeRepository.GetEntity(extModel.StuType)?.Name ?? "";
                extModel.StuPurposeName = learningGoalsRepository.GetLearningGoalsExtEntityRepository(extModel.StuPurpose)?.Name ?? "";
                extModel.StuChannelName = channelRepository.GetChannelExtEntityRepository(extModel.StuChannel)?.Name ?? "";
                extModel.StuNeedsName = needsRepository.GetNeedsExtEntityRepository(extModel.StuNeeds)?.Name ?? "";
                //if (extModel.CustomerId > 0)
                //{
                //    extModel.CustomerName = customerRepository.GetEntity(extModel.CustomerId)?.CustomerName ?? "";
                //}
                if (extModel.StuSourceId > 0)
                {
                    if (extModel.CreateType == StuCreateTypeEnum.CustomerInput)
                    {
                        var customerName = customerRepository.GetEntity(extModel.StuSourceId)?.CustomerName ?? "";
                        extModel.StuSourceIdName = customerName;
                        extModel.CustomerName = customerName;
                    }
                    else if (extModel.CreateType == StuCreateTypeEnum.EmployeeInput)
                    {
                        extModel.StuSourceIdName = accountModule.GetEmployeeInfo(extModel.StuSourceId)?.EmployeeName ?? "";
                    }
                    else if (extModel.CreateType == StuCreateTypeEnum.InternalIntroduction)
                    {
                        extModel.StuSourceIdName = accountModule.GetEmployeeInfo(extModel.StuSourceId)?.EmployeeName ?? "";
                    }
                    else if (extModel.CreateType == StuCreateTypeEnum.TransIntroduction)
                    {
                        extModel.StuSourceIdName = studentRepository.GetEntity(extModel.StuSourceId)?.StuName ?? "";
                    }
                }
            }
            return extModel;
        }

        /// <summary>
        /// 更新学生状态
        /// </summary>
        /// <param name="StuId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveStudentModule(int StuId, int Status)
        {
            bool flag = false;
            var model = GetStudentModule(StuId);
            if (model != null && model.StuId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_ViewModel.Status),  Status},
                };
                flag = studentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_ViewModel.StuId), StuId));
                var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                {
                    AccountId = model.StuId,
                    Account = model.StuTel,
                    AccountType = AccountTypeEnum.Student
                });
                if (accountList != null && accountList.Count > 0)
                {
                    flag = accountModule.SetAccountStatusModule(new RB_Account_ViewModel()
                    {
                        AccountType = AccountTypeEnum.Student,
                        AccountId = model.StuId,
                        UpdateTime = DateTime.Now,
                        Status = (DateStateEnum)Status
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 更新学员【禁用、启用】
        /// </summary>
        /// <param name="StuId"></param>
        /// <param name="IsDisable">0-禁用，1-启用</param>
        /// <returns></returns>
        public bool UpdateStudentIsDisableModule(object StuId, int IsDisable)
        {
            bool flag;
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_ViewModel.IsDisable),  IsDisable},
            };
            flag = studentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_ViewModel.StuId), StuId));
            return flag;
        }

        /// <summary>
        /// 创建学生账号
        /// </summary>
        /// <param name="StuId"></param>
        /// <param name="UserInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool CreateStudentAccountModule(int StuId, UserInfo user)
        {
            bool flag = false;
            var model = GetStudentModule(StuId);
            if (model != null && model.StuId > 0)
            {
                var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                {
                    Account = model.StuTel,
                    AccountType = AccountTypeEnum.Student
                });
                if (accountList == null || (accountList != null && accountList.Count == 0))
                {
                    flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                    {
                        Account = model.StuTel,
                        Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                        AccountType = AccountTypeEnum.Student,
                        AccountId = model.StuId,
                        CreateBy = user.Id,
                        UpdateBy = user.Id,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        Group_Id = model.Group_Id,
                        School_Id = model.School_Id,
                        Status = model.Status
                    });
                }
            }
            return flag;
        }

        #region 学生兴趣爱好

        /// <summary>
        /// 新增学生兴趣
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStudentInterest(RB_Student_ViewModel model)
        {
            if (model.StuId == 0)
            {
                return false;
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_ViewModel.Interest),model.Interest },
                    {nameof(RB_Student_ViewModel.JapanBaseInfo),(int)model.JapanBaseInfo },
                    {nameof(RB_Student_ViewModel.StuIcon),model.StuIcon.Trim() },
                    {nameof(RB_Student_ViewModel.StuSex),model.StuSex },
                    {nameof(RB_Student_ViewModel.UpdateTime),System.DateTime.Now }
                };
                return studentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_ViewModel.StuId), model.StuId));
            }
        }
        #endregion

        /// <summary>
        /// 根据学生id获取同班账户,必须是未开班/学习中的
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<RB_Student_ViewModel> GetListByStudentId(int Student_Id, int Group_Id)
        {
            return studentRepository.GetListByStudentId(Student_Id, Group_Id);
        }

        /// <summary>
        /// 根据学生id获取学生的班级课程学校信息
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<RB_Student_ViewModel> GetStudentInfo(int Student_Id, int Group_Id)
        {
            return studentRepository.GetStudentInfo(Student_Id, Group_Id);
        }

        /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="type">1-手机，2-QQ,3-微信</param>
        public void PushMessageModule(RB_Student_ViewModel model, int type)
        {
            var assistList = GetStuAssistListModule(model.StuId);
            var customerModel = customerRepository.GetEntity(model.CustomerId);

            string searchContent = model.StuTel + "(学员电话)";
            if (type == 2)
            {
                searchContent = model.QQ + "(学员电话)";
            }
            if (type == 3)
            {
                searchContent = model.WeChatNo + "(学员微信)";
            }
            string createByName = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
            {
                Id = model.CreateBy
            })?.FirstOrDefault()?.AccountName ?? "";
            string markdownContent = $"`同业查重通知` \n>**概要信息** \n>同业名称：{customerModel?.CustomerName ?? ""}({customerModel?.ContactNumber ?? ""})\n>查询内容：{searchContent} \n>关联学员：{model.StuName}\n>";
            markdownContent += $"关联同事：{ createByName}\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 (customerModel != null && customerModel.CreateBy > 0)
            {
                var queryTargetWorkId = accountModule.GetWorkUserIdModule(customerModel.CreateBy);
                modelWork.ReceiveId = queryTargetWorkId;
                Common.Message.MessageHelper.SendMessage(modelWork);
            }
            //if (assistList != null && assistList.Count > 0)
            //{
            //    foreach (var item in assistList)
            //    {
            //        var queryTargetWorkId = accountModule.GetWorkUserIdModule(item.AssistId);
            //        modelWork.ReceiveId = queryTargetWorkId;
            //        Common.Message.MessageHelper.SendMessage(modelWork);
            //    }
            //}
        }

        #region 小程序用户
        /// <summary>
        /// 根据条件获取用户实体
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_Member_User_Extend GetMemberUserEntityModule(RB_Member_User_Extend query)
        {
            return member_UserRepository.GetMemberUserEntityRepository(query);
        }
        #endregion

        /// <summary>
        /// 今日新名单
        /// </summary>
        /// <returns></returns>
        public object GetStudentTodayStaticModule(int createBy)
        {
            DateTime startTime = DateTime.Now.AddMonths(-1);
            string startDate = Common.ConvertHelper.FormatDate(startTime);
            var today = Common.ConvertHelper.FormatDate(DateTime.Now);

            //今日新增名单
            var addList = studentRepository.GetStudentStaticRepository(createBy.ToString(), startDate, today);
            int days = (DateTime.Now - startTime).Days;
            List<object> dayList = new List<object>();

            //今日新增名单
            int todayAdd = addList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == today)?.ClueCount ?? 0;

            //到访名单
            var visitList = student_VisitRepository.GetStudentVisitStaticRepository(new RB_Student_Visit_Extend()
            {
                CreateBy = createBy,
                StartDate = startDate,
                EndDate = today
            });
            //今日到访
            int todayVisit = visitList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == today)?.VisitCount ?? 0;

            //预约列表
            var appointmentList = student_AppointmentRepository.GetStudentVisitStaticRepository(new RB_Student_Appointment_Extend()
            {
                CreateBy = createBy,
                StartDate = startDate,
                EndDate = today,
            });
            //今日预约
            int appointmentCount = appointmentList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == today)?.AppointmentCount ?? 0;

            //新增同行列表
            var customerList = customerRepository.GetCustomerStaticRepository(new RB_Customer_Extend()
            {
                CreateBy = createBy,
                StartDate = startDate,
                EndDate = today
            });
            //今日新增同行
            var customerCount = customerList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == today)?.CustomerCount ?? 0;

            //试听列表
            var trialLessonList = visitor_ReserveRepository.GetVisitorReserveStaticRepository(new Model.ViewModel.Reserve.RB_Visitor_Reserve_Extend()
            {
                CreateBy = createBy,
                StartClassDate = startDate,
                EndClassDate = today
            });
            //今日试听
            var trialLessonCount = trialLessonList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == today)?.TrialLessonCount ?? 0;
            //未沟通人数
            var notCommunicateCount = studentRepository.GetStudentListRepository(new RB_Student_ViewModel()
            {
                CreateBy = createBy,
                StuStage = 1
            })?.Count();

            for (int i = 1; i <= days; i++)
            {
                var newDate = startTime.AddDays(i);
                dayList.Add(new
                {
                    x = Common.ConvertHelper.FormatMonthDay(newDate),
                    y = addList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(newDate))?.ClueCount ?? 0,
                    AddCount = addList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(newDate))?.ClueCount ?? 0,
                    VisitCount = visitList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(newDate))?.VisitCount ?? 0,
                    appointmentCount = appointmentList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(newDate))?.AppointmentCount ?? 0,
                    customerCount = customerList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(newDate))?.CustomerCount ?? 0,
                    trialLessonCount = trialLessonList?.FirstOrDefault(qitem => Common.ConvertHelper.FormatDate(qitem.CreateTime) == Common.ConvertHelper.FormatDate(newDate))?.TrialLessonCount ?? 0,
                });
            }

            object obj = new
            {
                dayList,
                todayAdd,
                todayVisit,
                appointmentCount,
                customerCount,
                trialLessonCount,
                notCommunicateCount
            };
            return obj;
        }

        #region 小程序个人中心

        /// <summary>
        /// 获取学生订单/留学/合同数量
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_Student_OrderGuest_ViewModel GetStuendOrderNum(int accountId, int group_Id)
        {
            return student_OrderGuestRepository.GetStuendOrderNum(accountId, group_Id);
        }

        /// <summary>
        /// 获取学生正在学习的课程 信息
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_Student_OrderGuest_ViewModel GetLearningCourseInfo(int accountId, int group_Id)
        {
            //获取正在学习的课程
            var model = student_OrderGuestRepository.GetLearningCourseInfo(accountId, group_Id, 1);
            if (model == null)
            {
                model = student_OrderGuestRepository.GetLearningCourseInfo(accountId, group_Id, 2);
            }
            return model;
        }

        #endregion

        public void UpdateTel()
        {
            var list = studentRepository.GetStudentListRepository(new RB_Student_ViewModel());
            foreach (var item in list)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_ViewModel.StuTel),Common.Plugin.StringHelper.ReplaceMobile(item.StuTel) }
                };
                studentRepository.Update(fileds, new WhereHelper(nameof(RB_Student_ViewModel.StuId), item.StuId));
            }
        }

        /// <summary>
        /// 更新学员咨询信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetStudentConsultResults(RB_Student_ViewModel demodel, UserInfo userInfo)
        {
            var oldModel = studentRepository.GetEntity(demodel.StuId);
            if (oldModel == null) { return "不存在"; }
            string logContent = "";
            if (oldModel.PlanPrice != demodel.PlanPrice)
            {
                logContent += $"规划课程及报价由【{oldModel.PlanPrice}】修改为【{demodel.PlanPrice}】;";
            }
            if (oldModel.BaseCondition != demodel.BaseCondition)
            {
                logContent += $"基本情况由【{oldModel.BaseCondition}】修改为【{demodel.BaseCondition}】;";
            }
            if (oldModel.DemandPoint != demodel.DemandPoint)
            {
                logContent += $"需求点由【{oldModel.DemandPoint}】修改为【{demodel.DemandPoint}】;";
            }
            if (oldModel.ResistPoint != demodel.ResistPoint)
            {
                logContent += $"抗拒点由【{oldModel.ResistPoint}】修改为【{demodel.ResistPoint}】;";
            }
            if (oldModel.ConsultingResults != demodel.ConsultingResults)
            {
                logContent += $"咨询结果由【{oldModel.ConsultingResults}】修改为【{demodel.ConsultingResults}】;";
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_Student_ViewModel.ConsultDate), demodel.ConsultDate},
                { nameof(RB_Student_ViewModel.PlanPrice), demodel.PlanPrice},
                { nameof(RB_Student_ViewModel.BaseCondition), demodel.BaseCondition},
                { nameof(RB_Student_ViewModel.DemandPoint), demodel.DemandPoint},
                { nameof(RB_Student_ViewModel.ResistPoint), demodel.ResistPoint},
                { nameof(RB_Student_ViewModel.ConsultingResults), demodel.ConsultingResults},
                { nameof(RB_Student_ViewModel.UpdateBy), userInfo.Id},
                { nameof(RB_Student_ViewModel.UpdateTime), DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper()
                {
                     FiledName = nameof(RB_Student_ViewModel.StuId),
                     FiledValue = demodel.StuId,
                     OperatorEnum =OperatorEnum.Equal
                }
            };
            bool flag = studentRepository.Update(keyValues, wheres);
            if (flag)
            {
                student_LogRepository.Insert(new Model.Entity.Customer.RB_Student_Log()
                {
                    LogId = 0,
                    LogType = Common.Enum.Log.StudentLogTypeEnum.BasicInfo,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    CreateType = 1,
                    Group_Id = userInfo.Group_Id,
                    LogContent = logContent,
                    LogTitle = "客户情况分析",
                    StuId = demodel.StuId
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        #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_AdvisorConfig_Extend> GetStudentAdvisorConfigPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_AdvisorConfig_Extend query)
        {
            var list = student_AdvisorConfigRepository.GetStudentAdvisorConfigPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 获取课程顾问跟进配置列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_AdvisorConfig_Extend> GetStudentAdvisorConfigListModule(RB_Student_AdvisorConfig_Extend query)
        {
            var list = student_AdvisorConfigRepository.GetStudentAdvisorConfigListRepository(query);
            return list;
        }

        /// <summary>
        /// 新增修改课程顾问配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        public bool SetStudentAdvisorConfigModule(RB_Student_AdvisorConfig_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_AdvisorConfig_Extend.Name),model.Name },
                    {nameof(RB_Student_AdvisorConfig_Extend.Num),model.Num },
                    {nameof(RB_Student_AdvisorConfig_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Student_AdvisorConfig_Extend.UpdateTime),model.UpdateTime },
                    {nameof(RB_Student_AdvisorConfig_Extend.Rate),model.Rate },
                };
                flag = student_AdvisorConfigRepository.Update(fileds, new WhereHelper(nameof(RB_Student_AdvisorConfig_Extend.Id), model.Id));
            }
            else
            {
                var newId = student_AdvisorConfigRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取课程顾问配置信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Student_AdvisorConfig_Extend GetStudentAdvisorConfigModule(object Id)
        {
            var model = student_AdvisorConfigRepository.GetEntity<RB_Student_AdvisorConfig_Extend>(Id);
            return model;
        }

        /// <summary>
        /// 根据编号删除课程顾问配置信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveStudentAdvisorConfigModule(object Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Student_AdvisorConfig_Extend.Status), (int)DateStateEnum.Delete },
            };
            bool flag = student_AdvisorConfigRepository.Update(fileds, new WhereHelper(nameof(RB_Student_AdvisorConfig_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_Student_Advisor_Extend> GetStudentAdvisorPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_Advisor_Extend query)
        {
            var list = student_AdvisorRepository.GetStudentAdvisorPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 获取课程顾问跟进列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_Advisor_Extend> GetStudentAdvisorListModule(RB_Student_Advisor_Extend query)
        {
            var list = student_AdvisorRepository.GetStudentAdvisorListRepository(query);
            return list;
        }

        /// <summary>
        /// 新增修改课程顾问跟进记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStudentAdvisorModule(RB_Student_Advisor_Extend model)
        {
            bool flag = false;
            var oldStudent = studentRepository.GetEntity<RB_Student_ViewModel>(model.StuId);
            if (oldStudent != null)
            {
                Dictionary<string, object> stuFileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_ViewModel.AdvisorStatus),model.AdvisorStatus },
                    {nameof(RB_Student_ViewModel.AdvisorWinRate),model.AdvisorRate },
                };
                if (string.IsNullOrEmpty(oldStudent.AdvisorExpectDate))
                {
                    stuFileds.Add(nameof(RB_Student_ViewModel.AdvisorExpectDate), model.AdvisorExpectDate);
                }
                flag = studentRepository.Update(stuFileds, new WhereHelper(nameof(RB_Student_ViewModel.StuId), model.StuId));
            }
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Student_Advisor_Extend.StuId),model.StuId },
                    {nameof(RB_Student_Advisor_Extend.AdvisorStatus),model.AdvisorStatus },
                    {nameof(RB_Student_Advisor_Extend.AdvisorDate),model.AdvisorDate },
                    {nameof(RB_Student_Advisor_Extend.AdvisorRemark),model.AdvisorRemark },
                };
                flag = student_AdvisorRepository.Update(fileds, new WhereHelper(nameof(RB_Student_Advisor_Extend.Id), model.Id));
            }
            else
            {
                var newId = student_AdvisorRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }


        /// <summary>
        /// 根据编号获取课程顾问跟进记录
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Student_Advisor_Extend GetStudentAdvisorModule(object Id)
        {
            var extModel = student_AdvisorRepository.GetEntity<RB_Student_Advisor_Extend>(Id);
            return extModel;
        }
        #endregion
    }
}
