using Edu.AOP.CustomerAttribute;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.Enum;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.Sale;
using Edu.Common.Enum.System;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Contract;
using Edu.Model.Entity.Sell;
using Edu.Model.ViewModel.Contract;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.EduTask;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Log;
using Edu.Model.ViewModel.Mall;
using Edu.Model.ViewModel.Reserve;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.StudyAbroad;
using Edu.Model.ViewModel.User;
using Edu.Repository.Contract;
using Edu.Repository.Course;
using Edu.Repository.Customer;
using Edu.Repository.Finance;
using Edu.Repository.Grade;
using Edu.Repository.Log;
using Edu.Repository.Reserve;
using Edu.Repository.Sell;
using Edu.Repository.StudyAbroad;
using Edu.Repository.System;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 订单处理类
    /// </summary>
    public partial class OrderModule
    {
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();

        /// <summary>
        /// 订单备注
        /// </summary>
        private readonly RB_Order_RemarkRepository order_RemarkRepository = new RB_Order_RemarkRepository();

        /// <summary>
        /// 客人
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

        /// <summary>
        /// 用户日志
        /// </summary>
        private readonly RB_User_ChangeLogRepository changeLogRepository = new RB_User_ChangeLogRepository();

        /// <summary>
        /// 班级
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 阶梯价格
        /// </summary>
        private readonly RB_Class_StepPriceRepository class_StepPriceRepository = new RB_Class_StepPriceRepository();

        /// <summary>
        /// 订单阶梯价格
        /// </summary>
        private readonly RB_Order_StepPriceRepository order_StepPriceRepository = new RB_Order_StepPriceRepository();

        /// <summary>
        /// 课程计划
        /// </summary>
        private readonly RB_Class_PlanRepository class_PlanRepository = new RB_Class_PlanRepository();

        /// <summary>
        /// 班级上课时间仓储层对象
        /// </summary>
        private readonly RB_Class_TimeRepository class_TimeRepository = new RB_Class_TimeRepository();
            
        /// <summary>
        /// 课程仓储层对象
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();

        /// <summary>
        /// 课程优惠仓储层对象
        /// </summary>
        private readonly RB_Course_PreferentialRepository course_PreferentialRepository = new RB_Course_PreferentialRepository();

        /// <summary>
        /// 教师
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

        /// <summary>
        /// 助教
        /// </summary>
        private readonly RB_AssistRepository assistRepository = new RB_AssistRepository();
        /// <summary>
        /// 学员协助人员仓储层对象
        /// </summary>
        private readonly RB_Student_AssistRepository student_AssistRepository = new RB_Student_AssistRepository();
        /// <summary>
        /// 学生
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();
        /// <summary>
        /// 学员续费介绍
        /// </summary>
        private readonly RB_Student_RenewOrderRepository student_RenewOrderRepository = new RB_Student_RenewOrderRepository();

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

        /// <summary>
        /// 学生关联
        /// </summary>
        private readonly RB_Student_OrderGuestRepository student_OrderGuestRepository = new RB_Student_OrderGuestRepository();

        /// <summary>
        /// 账号
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 合同
        /// </summary>
        private readonly RB_Education_ContractRepository education_ContractRepository = new RB_Education_ContractRepository();
        /// <summary>
        /// 合同协调金额
        /// </summary>
        private readonly RB_Education_ContractAdjustRepository education_ContractAdjustRepository = new RB_Education_ContractAdjustRepository();

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

        /// <summary>
        /// 报价单仓储层对象
        /// </summary>
        private readonly RB_Course_OfferRepository course_OfferRepository = new RB_Course_OfferRepository();

        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();
        /// <summary>
        /// 财务单据详情
        /// </summary>
        private readonly RB_FinanceDetailRepository financeDetailRepository = new RB_FinanceDetailRepository();
        /// <summary>
        /// 交易方式
        /// </summary>
        private readonly RB_TradeWayRepository tradeWayRepository = new RB_TradeWayRepository();
        /// <summary>
        /// 币种
        /// </summary>
        private readonly RB_CurrencyRepository currencyRepository = new RB_CurrencyRepository();
        /// <summary>
        /// 银行账户
        /// </summary>
        private readonly RB_BackAccountRepository backAccountRepository = new RB_BackAccountRepository();
        /// <summary>
        /// 现金账户
        /// </summary>
        private readonly RB_CashPoolAccountRepository cashPoolAccountRepository = new RB_CashPoolAccountRepository();
        /// <summary>
        /// 平台账户
        /// </summary>
        private readonly RB_PlatformAccountRepository platformAccountRepository = new RB_PlatformAccountRepository();

        /// <summary>
        /// 班级关联课程仓储层对象
        /// </summary>
        private readonly RB_Class_CourseRepository class_CourseRepository = new RB_Class_CourseRepository();

        /// <summary>
        /// 访客预约仓储层对象
        /// </summary>
        private readonly RB_Visitor_ReserveRepository visitor_ReserveRepository = new RB_Visitor_ReserveRepository();

        /// <summary>
        /// 订单拆分仓储层对象
        /// </summary>
        private readonly RB_Order_SplitDetailsRepository splitDetailsRepository = new RB_Order_SplitDetailsRepository();

        /// <summary>
        /// 商品规格值
        /// </summary>
        private readonly Repository.Mall.RB_Goods_SpecificationValueRepository goods_SpecificationValueRepository = new Repository.Mall.RB_Goods_SpecificationValueRepository();
        /// <summary>
        /// 商品规格价格
        /// </summary>
        private readonly Repository.Mall.RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new Repository.Mall.RB_Goods_SpecificationPriceRepository();
        /// <summary>
        /// 财务配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();

        /// <summary>
        /// 学习目的仓储层对象
        /// </summary>
        private readonly RB_LearningGoalsRepository learningGoalsRepository = new RB_LearningGoalsRepository();
        /// <summary>
        /// 业绩提成
        /// </summary>
        private readonly RB_Sell_Achievements_EmpRepository sell_Achievements_EmpRepository = new RB_Sell_Achievements_EmpRepository();

        private readonly RB_Order_ReturnComissionRepository returnComissionRepository = new RB_Order_ReturnComissionRepository();

        private readonly RB_User_ReturnComissionRepository userReturnComissionRepository = new RB_User_ReturnComissionRepository();

        private readonly RB_ReturnMoney_BatchRepository returnMoney_BatchRepository = new RB_ReturnMoney_BatchRepository();

        #region 日语培训

        /// <summary>
        /// 获取日语培训
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassPruductListModule(int pageIndex, int pageSize, out long count, RB_Class_ViewModel dmodel)
        {
            var list = classRepository.GetClassProductPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                string classIds = string.Join(",", list.Select(x => x.ClassId));
                string courseIds = string.Join(",", list.Select(qitem => qitem.CouseId));
                //查询阶梯价格
                var stepList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { QClassIds = classIds });
                var otherCourseList = class_CourseRepository.GetClassCourseListRepository(new RB_Class_Course_Extend() { QClassIds = classIds });
                List<RB_Class_Plan_ViewModel> PlanFixed = new List<RB_Class_Plan_ViewModel>();
                string k2classIds = string.Join(",", list.Where(x => x.ClassStyle == Common.Enum.Course.ClassStyleEnum.FixedDate).Select(x => x.ClassId));
                if (!string.IsNullOrEmpty(k2classIds))
                {
                    PlanFixed = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel() { QClassIds = k2classIds });
                }
                foreach (var item in list)
                {
                    item.ClassStepPriceList = stepList.Where(x => x.ClassId == item.ClassId).OrderBy(x => x.PersionNum).ToList();
                    item.OtherCourseList = otherCourseList?.Where(qitem => qitem.ClassId == item.ClassId)?.ToList() ?? new List<RB_Class_Course_Extend>();
                    item.DefaultTimeList = new List<ClassTimeItem>();
                    if (item.ClassStyle != Common.Enum.Course.ClassStyleEnum.OnLine)
                    {
                        if (!string.IsNullOrEmpty(item.DefaultTimeJson))
                        {
                            item.DefaultTimeList = JsonHelper.DeserializeObject<List<ClassTimeItem>>(item.DefaultTimeJson);
                        }
                    }
                    item.ClassPlanList = new List<RB_Class_Plan_ViewModel>();
                    if (item.ClassStyle == Common.Enum.Course.ClassStyleEnum.Week || item.ClassStyle == Common.Enum.Course.ClassStyleEnum.Month)
                    {
                        if (!string.IsNullOrEmpty(item.DateJson))
                        {
                            List<int> DayList = JsonHelper.DeserializeObject<List<int>>(item.DateJson);
                            foreach (var qitem in DayList)
                            {
                                item.ClassPlanList.Add(new RB_Class_Plan_ViewModel()
                                {
                                    WeekDay = qitem
                                });
                            }
                        }
                    }
                    else if (item.ClassStyle == Common.Enum.Course.ClassStyleEnum.FixedDate)
                    {
                        item.ClassPlanList = PlanFixed.Where(x => x.ClassId == item.ClassId).ToList();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取班级课程信息
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <param name="Group_Id">集团编号</param>
        /// <returns></returns>
        public Dictionary<string, object> GetClassCourseListModule(int classId)
        {
            List<object> newCourseList = new List<object>();
            Dictionary<string, object> fileds = new Dictionary<string, object>();
            var planList = class_PlanRepository.GetClassPlanListExtRepository(new RB_Class_Plan_ViewModel() { ClassId = classId, EndTime = Common.ConvertHelper.FormatDate(DateTime.Now) });
            var totalMinutes = planList?.Sum(qitem => qitem.ClassMinutes) ?? 0;
            //查询基础课时时长
            var BasicMinutes = class_ConfigRepository.GetClassMinutesRepository(classId);
            var finishHours = totalMinutes / BasicMinutes;
            fileds.Add("finishHours", finishHours);
            var classModel = classRepository.GetEntity(classId);
            var courseModel = courseRepository.GetEntity(classModel.CouseId);
            if (courseModel != null && courseModel.CourseId > 0)
            {
                var CoursePriceList = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend() { CourseId = courseModel.CourseId });
                newCourseList.Add(new
                {
                    courseModel.CourseId,
                    courseModel.CourseName,
                    courseModel.ClassHours,
                    courseModel.SellPrice,
                    CoursePriceList
                });
            }
            var courseList = class_CourseRepository.GetClassCourseListRepository(new RB_Class_Course_Extend() { ClassId = classId });
            if (courseList != null)
            {
                string courseIds = string.Join(",", courseList.Select(qitem => qitem.CourseId));
                var coursePriceList = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
                {
                    QCourseIds = courseIds
                });
                foreach (var item in courseList)
                {
                    newCourseList.Add(new
                    {
                        item.CourseId,
                        item.CourseName,
                        item.ClassHours,
                        item.SellPrice,
                        item.CoursePriceList
                    });
                }
            }
            fileds.Add("otherCourse", newCourseList);
            return fileds;
        }

        /// <summary>
        /// 获取班级名称
        /// </summary>
        /// <param name="classIds"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassNameList(string classIds)
        {
            return classRepository.GetClassListRepository(new RB_Class_ViewModel() { Q_ClassIds = classIds });
        }

        /// <summary>
        /// 获取留学就业产品名称
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public List<RB_StudyAbroad_ViewModel> GetStudyAbroadListModule(string ids)
        {
            return studyAbroadRepository.GetStudyAbroadListRepository(new RB_StudyAbroad_ViewModel()
            {
                QIds = ids
            });
        }

        /// <summary>
        /// 日语培训下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetClassOrderModule(RB_Order_ViewModel demodel, UserInfo userInfo, bool isEditOrder, out string message)
        {
            return SetClassOrderCommonModule(demodel, userInfo, isEditOrder, out message);
        }

        /// <summary>
        /// 记录返佣信息
        /// </summary>
        /// <param name="model"></param>
        public void SetReturnOrderCommission(RB_Order_ViewModel model)
        {
            //排除原有的批量报入，和B2B未付款的订单
            if (model.OrderIdentify == 2 && model.OrderState != OrderStateEnum.WaitPay)
            {
                var stuList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = model.Group_Id, StuIds = model.StuIds, School_Id = -1 });
                if (stuList.Any())
                {
                    stuList.ForEach(x =>
                    {
                        //检查学员是否存在有效订单
                        int orderCount = studentRepository.GetStudentOrderCount(x.StuId);

                        var commissionModel = new RB_Order_ReturnComission_ViewModel()
                        {
                            Id = 0,
                            OrderId = model.OrderId,
                            OrderSourceType = x.CreateType,
                            OrderSourceId = x.CreateType == StuCreateTypeEnum.EmployeeInput ? x.CreateBy : (x.CreateType == StuCreateTypeEnum.CustomerInput ? x.CustomerId : x.StuSourceId),
                            Status = -1, //下单默认为不可返佣，等待付款完成后更新为待返佣
                            UnionCashOutId = 0,
                            StuId = x.StuId,
                            CommissionType = orderCount == 0 ? 1 : 2,
                            SchoolId = model.School_Id,
                            GroupId = model.Group_Id,
                            Remark = ""
                        };
                        FormatOrderCommissionByCourse(ref commissionModel, model.CourseId);
                        returnComissionRepository.Insert(commissionModel);
                    });
                }
            }
        }

        /// <summary>
        /// 生成指定类型的佣金
        /// </summary>
        /// <param name="type"></param>
        /// <param name="uid"></param>
        /// <param name="gid"></param>
        /// <returns></returns>
        public (bool result,string message) SetUserReturnMoneyModule(int type,int uid,int gid)
        {
            //检查本月是否存在操作记录
            string month = DateTime.Now.ToString("yyyy-MM");
            var isHave = returnMoney_BatchRepository.ExsitModelByMonth(gid, month, type);
            if (!isHave)
            {
                var model = new RB_ReturnMoney_Batch()
                {
                    Id = 0,
                    BatchName = DateTime.Now.ToString("yyyyMM") + "返佣",
                    TotalMoney = 0,
                    CreateBy = uid,
                    CreateDate = DateTime.Now,
                    GroupId = gid,
                    CommissionType = type
                };
                //查询符合返佣条件的学员（非订单）
                var list = returnComissionRepository.GetListBySetBatch(gid, type);

                if (list.Any())
                {
                    //开始生成用户待提现的金额
                    var userResult = list.GroupBy(x => new { x.OrderSourceType, x.OrderSourceId }).Select(g => (new RB_Order_ReturnComission_ViewModel
                    {
                        OrderSourceType = g.Key.OrderSourceType,
                        OrderSourceId = g.Key.OrderSourceId,
                        CommissionMoeny = g.Sum(item => item.CommissionMoeny),
                        CommissionType = type
                    }));

                    if (userResult.Any()) 
                    {
                        //更新用户主表信息
                        userResult.ToList().ForEach(x =>
                        {

                            var userModel = userReturnComissionRepository.GetModelBySourceId((int)x.OrderSourceType, x.OrderSourceId, x.CommissionType);
                            if (userModel != null && userModel.UserId > 0)
                            {
                                userModel.CanCashOutMoney += x.CommissionMoeny;
                                userModel.UnSettlementMoney -= x.CommissionMoeny;
                                userModel.SttlementMoney += x.CommissionMoeny;

                                Dictionary<string, object> userKeyValues = new Dictionary<string, object>()
                                {
                                    { nameof(RB_User_ReturnComission_ViewModel.SttlementMoney),userModel.SttlementMoney},
                                    { nameof(RB_User_ReturnComission_ViewModel.CanCashOutMoney),userModel.CanCashOutMoney},
                                    { nameof(RB_User_ReturnComission_ViewModel.UnSettlementMoney),userModel.UnSettlementMoney}
                                };
                                List<WhereHelper> userWheres = new List<WhereHelper>()
                                {
                                    new WhereHelper()
                                    {
                                        FiledName=nameof(RB_User_ReturnComission_ViewModel.UserType),
                                        FiledValue=userModel.UserType,
                                        OperatorEnum= OperatorEnum.Equal
                                    },
                                    new WhereHelper()
                                    {
                                        FiledName=nameof(RB_User_ReturnComission_ViewModel.UserId),
                                        FiledValue=userModel.UserId,
                                        OperatorEnum= OperatorEnum.Equal
                                    },
                                    new WhereHelper()
                                    {
                                        FiledName=nameof(RB_User_ReturnComission_ViewModel.CommissionType),
                                        FiledValue=userModel.CommissionType,
                                        OperatorEnum= OperatorEnum.Equal
                                    }
                                };
                                userReturnComissionRepository.Update(userKeyValues, userWheres);
                            }
                            else 
                            {
                                userModel = new RB_User_ReturnComission_ViewModel()
                                {
                                    UserId = x.OrderSourceId,
                                    UserType = x.OrderSourceType,
                                    CommissionType = x.CommissionType,
                                    CanCashOutMoney = x.CommissionMoeny,
                                    CashOutMoney = 0,
                                    GroupId = gid,
                                    SttlementMoney = x.CommissionMoeny,
                                    UnSettlementMoney = 0
                                };
                                userReturnComissionRepository.Insert(userModel);
                            }
                            
                        });
                    }

                    model.TotalMoney = list.Sum(x => x.CommissionMoeny);
                    //添加主表返佣信息
                    model.Id = returnMoney_BatchRepository.Insert(model);

                    //更新子表数据
                    var ids = list.Select(x => x.Id);
                    returnComissionRepository.UpdateModelByBatch(model.Id, string.Join(',', ids));

                    return (true, $"执行成功，本期返佣标号为：{model.BatchName}");
                }
                else
                {
                    return (false, $"执行失败，本期无返佣金额");
                }
            }
            else 
            {
                return (false, "当月份已执行返佣操作，请下月再试");
            }

        }

        /// <summary>
        /// 查询指定分页的提成数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="type"></param>
        /// <param name="month"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_ReturnMoney_Batch_ViewModel> GetBatchListModule(int pageIndex, int pageSize, out long count, int type, string month,int groupId)
        {
            var list = returnMoney_BatchRepository.GetPageList(pageIndex, pageSize, out count, type, month, groupId);
            if (list.Any()) 
            {
                list.ForEach(x => {
                    x.CreateByName = UserReidsCache.GetUserLoginInfo(x.CreateBy)?.AccountName ?? "";
                });
            }
            return list;
        }

        public void FormatOrderCommissionByCourse(ref RB_Order_ReturnComission_ViewModel m, int courseId)
        {
            var courseModel = courseRepository.GetEntity(courseId);
            if (courseModel != null)
            {
                var sellPrice = courseModel.SellPrice * ((100-(m.CommissionType == 1 ? courseModel.B2CRatio : courseModel.B2CReNewRatio)) / 100);
                if ((int)m.OrderSourceType == 1) 
                {
                    if (courseModel.CommissionReType == 1)
                    {
                        m.CommissionMoeny = Math.Round(sellPrice * ((m.CommissionType == 1 ? courseModel.B2CRbRatio : courseModel.B2CRNRatio) / 100), 2, MidpointRounding.AwayFromZero);
                    }
                    else {
                        m.CommissionMoeny = m.CommissionType == 1 ? courseModel.B2CRbRatio : courseModel.B2CRNRatio;
                    }
                    m.CommissionReType = m.CommissionType == 1 ? courseModel.B2CRbRatioType.ToInt() : courseModel.B2CRNRatioType.ToInt();
                    m.CommissionReValue = m.CommissionType == 1 ? courseModel.B2CRbRatioValue : courseModel.B2CRNRatioValue;
                    m.Remark = $"学员来源为：直客，学员为{(m.CommissionType == 1 ? "首次报名" : "续费报名")},本次报名金额为：{sellPrice}，本次返佣金额为：{m.CommissionMoeny:0.00}";
                }
                else if ((int)m.OrderSourceType == 2)
                {
                    var customerModel = customerRepository.GetEntity(m.OrderSourceId);
                    if (customerModel.CustomerType ==  Common.Enum.Customer.CatetoryTypeEnum.Company)
                    {
                        if (courseModel.CommissionReType == 1)
                        {
                            m.CommissionMoeny = Math.Round(sellPrice * ((m.CommissionType == 1 ? courseModel.B2BRebateRatio : courseModel.B2BReNewRatio) / 100), 2, MidpointRounding.AwayFromZero);
                        }
                        else {
                            m.CommissionMoeny = m.CommissionType == 1 ? courseModel.B2BRebateRatio : courseModel.B2BReNewRatio;
                        }
                        m.CommissionReType = m.CommissionType == 1 ? courseModel.B2BRebateRatioType.ToInt() : courseModel.B2BReNewRatioType.ToInt();
                        m.CommissionReValue = m.CommissionType == 1 ? courseModel.B2BRebateRatioValue : courseModel.B2BReNewRatioValue;
                        m.Remark = $"学员来源为：同业，学员为{(m.CommissionType == 1 ? "首次报名" : "续费报名")},本次报名金额为：{sellPrice}，本次返佣金额为：{m.CommissionMoeny:0.00}";
                    }
                    else 
                    {
                        if (courseModel.CommissionReType == 1)
                        {
                            m.CommissionMoeny = Math.Round(sellPrice * ((m.CommissionType == 1 ? courseModel.SchoolRebateRatio : courseModel.SchoolReNewRatio) / 100), 2, MidpointRounding.AwayFromZero);
                        }
                        else {
                            m.CommissionMoeny = m.CommissionType == 1 ? courseModel.SchoolRebateRatio : courseModel.SchoolReNewRatio;
                        }
                        m.CommissionReType = m.CommissionType == 1 ? courseModel.SchoolRebateRatioType.ToInt() : courseModel.SchoolReNewRatioType.ToInt();
                        m.CommissionReValue = m.CommissionType == 1 ? courseModel.SchoolRebateRatioValue : courseModel.SchoolReNewRatioValue;
                        m.Remark = $"学员来源为：校代，学员为{(m.CommissionType == 1 ? "首次报名" : "续费报名")},本次报名金额为：{sellPrice}，本次返佣金额为：{m.CommissionMoeny:0.00}";
                    }
                }
                else if ((int)m.OrderSourceType == 3)
                {
                    if (courseModel.CommissionReType == 1)
                    {
                        m.CommissionMoeny = Math.Round(sellPrice * ((m.CommissionType == 1 ? courseModel.InnerRecommendRatio : courseModel.InnerRecommendReNewRatio) / 100), 2, MidpointRounding.AwayFromZero);
                    }
                    else {
                        m.CommissionMoeny = m.CommissionType == 1 ? courseModel.InnerRecommendRatio : courseModel.InnerRecommendReNewRatio;
                    }
                    m.CommissionReType = m.CommissionType == 1 ? courseModel.InnerRecommendRatioType.ToInt() : courseModel.InnerRecommendReNewRatioType.ToInt();
                    m.CommissionReValue = m.CommissionType == 1 ? courseModel.InnerRecommendRatioValue : courseModel.InnerRecommendReNewRatioValue.Value;
                    m.Remark = $"学员来源为：内部介绍，学员为{(m.CommissionType == 1 ? "首次报名" : "续费报名")},本次报名金额为：{sellPrice}，本次返佣金额为：{m.CommissionMoeny:0.00}";
                }
                else if ((int)m.OrderSourceType == 4)
                {
                    if (courseModel.CommissionReType == 1)
                    {
                        m.CommissionMoeny = Math.Round(sellPrice * ((m.CommissionType == 1 ? (courseModel.TransIntroductceRatio) : courseModel.TransIntroductceReNewRatio) / 100), 2, MidpointRounding.AwayFromZero);
                    }
                    else {
                        m.CommissionMoeny = m.CommissionType == 1 ? (courseModel.TransIntroductceRatio) : courseModel.TransIntroductceReNewRatio;
                    }
                    m.CommissionReType = m.CommissionType == 1 ? courseModel.TransIntroductceRatioType.ToInt() : courseModel.TransIntroductceReNewRatioType.ToInt();
                    m.CommissionReValue = m.CommissionType == 1 ? courseModel.TransIntroductceRatioValue : courseModel.TransIntroductceReNewRatioValue;
                    m.Remark = $"学员来源为：学员转介绍，学员为{(m.CommissionType == 1 ? "首次报名" : "续费报名")},本次报名金额为：{sellPrice}，本次返佣金额为：{m.CommissionMoeny:0.00}";
                }
            }
            else 
            {
                //未匹配到课程，以防万一
                m.CommissionMoeny = 0;
                m.CommissionReType = 3;
                m.CommissionReValue = 0;
                m.Remark = "系统未匹配到对应的返佣信息，本订单返佣为0";
            }
        }


        /// <summary>
        /// 修改老订单
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="TargetOrderId"></param>
        /// <param name="targetJoinType"></param>
        /// <returns></returns>
        public bool UpdateOrderJoinTypeModule(int OrderId, int TargetOrderId, OrderJoinTypeEnum targetJoinType)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Order_ViewModel.TargetOrderId),TargetOrderId },
                {nameof(RB_Order_ViewModel.TargetJoinType),(int)targetJoinType }
            };
            return orderRepository.Update(fileds, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), OrderId));
        }

        /// <summary>
        /// 日语培训下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>

        public bool SetClassOrderCommonModule(RB_Order_ViewModel demodel, UserInfo userInfo, bool isEditOrder, out string message)
        {
            bool flag = false;
            message = "";
            var orderModel = new RB_Order();
            if (demodel.OrderId > 0)
            {
                orderModel = orderRepository.GetEntity(demodel.OrderId);
                demodel.OrderIdentify = orderModel.OrderIdentify;
            }
            //查询班级信息
            var classModel = classRepository.GetEntity(demodel.ClassId);
            if (classModel == null)
            {
                flag = false;
                message = "班级不存在";
                return flag;
            }
            if (demodel.JoinType == OrderJoinTypeEnum.Normal || demodel.JoinType == OrderJoinTypeEnum.RenewOrder)
            {
                demodel.CourseId = classModel.CouseId;
            }
            //课程信息
            var courseModel = courseRepository.GetEntity(demodel.CourseId);
            decimal coursePrice = courseModel.SellPrice;//课程最低单价
            demodel.CommissionReType = courseModel.CommissionReType;

            #region 课程比例赋值
            if (demodel.OrderId <= 0)
            {
                demodel.B2CRatio = courseModel.B2CRatio;
                demodel.B2CReNewRatio = courseModel.B2CReNewRatio;
                demodel.B2BRebateRatio = courseModel.B2BRebateRatio;
                demodel.B2BReNewRatio = courseModel.B2BReNewRatio;
                demodel.SchoolRebateRatio = courseModel.SchoolRebateRatio;
                demodel.SchoolReNewRatio = courseModel.SchoolReNewRatio;
                demodel.TransIntroductceRatio = courseModel.TransIntroductceRatio;
                demodel.TransIntroductceReNewRatio = courseModel.TransIntroductceReNewRatio;
                demodel.InnerRecommendRatio = courseModel.InnerRecommendRatio;
                demodel.InnerRecommendReNewRatio = courseModel.InnerRecommendReNewRatio;
                demodel.CommissionReType = courseModel.CommissionReType;
            }
            else {
                //使用订单的比例
                courseModel.B2CRatio = orderModel.B2CRatio;
                courseModel.B2CReNewRatio = orderModel.B2CReNewRatio;
                courseModel.B2BRebateRatio = orderModel.B2BRebateRatio;
                courseModel.B2BReNewRatio = orderModel.B2BReNewRatio;
                courseModel.SchoolRebateRatio = orderModel.SchoolRebateRatio;
                courseModel.SchoolReNewRatio = orderModel.SchoolReNewRatio;
                courseModel.TransIntroductceRatio = orderModel.TransIntroductceRatio;
                courseModel.TransIntroductceReNewRatio = orderModel.TransIntroductceReNewRatio;
                courseModel.InnerRecommendRatio = orderModel.InnerRecommendRatio;
                courseModel.InnerRecommendReNewRatio = orderModel.InnerRecommendReNewRatio;
                courseModel.CommissionReType = orderModel.CommissionReType;
            }
            #endregion
            #region 计算订单优惠信息     
            List<RB_Student_ViewModel> StuList = new List<RB_Student_ViewModel>();
            //计算续费订单优惠
            if (demodel.JoinType == OrderJoinTypeEnum.RenewOrder && demodel.OrderId == 0)
            {
                demodel.DiscountMoney = coursePrice * (courseModel.B2CReNewRatio / 100);
                demodel.SaleRemark = "续费报名优惠" + courseModel.B2CReNewRatio + "%";
            }
            else if ((demodel.JoinType == OrderJoinTypeEnum.Normal || demodel.JoinType == OrderJoinTypeEnum.InsertClass) && demodel.OrderIdentify != 2)
            {
                //默认都是首次报名优惠
                //HK 2022 - 02 - 08修改
                decimal DiscountMoney = coursePrice * (courseModel.B2CRatio / 100);
                //if (demodel.DiscountMoney > DiscountMoney)
                //{
                //    message = string.Format("优惠金额不正确，不能超过{0}元",DiscountMoney);
                //    return false;
                //}
            }
            else if (demodel.OrderIdentify == 2 && demodel.OrderId == 0)
            {
                //查询学生列表
                StuList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = demodel.Group_Id, StuIds = demodel.StuIds, School_Id = -1 });
                //根据客人手机号码  验证是否是续费
                if (StuList.Select(x => x.CustomerId).Distinct().Count() > 1)
                {
                    message = "只能选择同一同行的客户报名";
                    return false;
                }
                if (StuList.Count() != demodel.GuestNum)
                {
                    message = "学生信息有误";
                    return false;
                }
                if (StuList.FirstOrDefault().CustomerId != demodel.CustomerId)
                {
                    message = "同业信息有误";
                    return false;
                }
                var glist = student_OrderGuestRepository.GetStuOrderList(demodel.StuIds, demodel.Group_Id);
                if (glist.Any())
                {
                    foreach (var item in StuList)
                    {
                        if (glist.Where(x => x.Student_Id == item.StuId).Any())
                        {
                            item.IsRenewGuest = 1;//是续费的
                        }
                    }
                }
                int RenewNum = glist.Select(x => x.Student_Id).Distinct().Count();//续费订单数量
                int NormalNum = demodel.GuestNum - RenewNum;//首次报名数量
                decimal dmoney = coursePrice * (courseModel.B2CRatio / 100) * NormalNum + coursePrice * (courseModel.B2CReNewRatio / 100) * RenewNum;
                if (demodel.DiscountMoney != dmoney)
                {
                    message = "优惠金额不正确";
                    return false;
                }
            }
            else if (demodel.OrderIdentify == 2 && demodel.OrderId > 0) {
                //直接验证优惠金额
                decimal DiscountMoney = coursePrice * (courseModel.B2CRatio / 100);
                //HK 2022-02-08修改
                //if (demodel.DiscountMoney > DiscountMoney)
                //{
                //    message = string.Format("优惠金额有误,不能超过 {0} 元.", DiscountMoney);
                //    return false;
                //}
            }

            //获取课程优惠
            var coursePreferentialList = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
            {
                CourseId = demodel.CourseId
            });
            if (coursePreferentialList != null && coursePreferentialList.Count > 0)
            {
                #region 记录提成信息
                var coursePreferentialModel = coursePreferentialList.FirstOrDefault();
                demodel.CommissionType = coursePreferentialModel?.SaleCommissionType ?? 0;
                demodel.CommissionRate = coursePreferentialModel?.SaleCommissionMoney ?? 0;
                demodel.CommissionTypeTH = coursePreferentialModel?.B2BCommissionType ?? 0;
                demodel.CommissionRateTH = coursePreferentialModel?.B2BCommissionMoney ?? 0;
                if (coursePreferentialModel != null)
                {
                    demodel.CommissionRemark = "使用优惠Id:" + coursePreferentialModel.Id + " 返佣类型:" + demodel.CommissionType + " 返佣比例/金额:" + demodel.CommissionRate + " 同行返佣类型:" + demodel.CommissionTypeTH + " 同行返佣比例/金额:" + demodel.CommissionRateTH;
                }
                #endregion
            }
            #endregion
            if (demodel.OrderSource == OrderSourceEnum.EduClient || demodel.OrderSource == OrderSourceEnum.Client)
            {
                if (demodel.OrderSource == OrderSourceEnum.EduClient)
                {
                    demodel.GeneralOccupation = "";
                }
                else if (demodel.OrderSource == OrderSourceEnum.Client)
                {
                    demodel.EduOccupation = "";
                }
            }
            else
            {
                demodel.EduOccupation = "";
                demodel.GeneralOccupation = "";
            }
            if (demodel.OrderId > 0)
            {
                int BNum = orderRepository.GetClassOrderPeopleNumRepository(demodel.ClassId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
                if (BNum + demodel.GuestNum - orderModel.GuestNum > classModel.ClassPersion)
                {
                    flag = false;
                    message = "人数报超" + (classModel.ClassPersion - (BNum + demodel.GuestNum - orderModel.GuestNum));
                    return flag;
                }
            }
            else
            {
                int BNum = orderRepository.GetClassOrderPeopleNumRepository(demodel.ClassId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
                if (BNum + demodel.GuestNum > classModel.ClassPersion)
                {
                    flag = false;
                    message = "人数报超" + (classModel.ClassPersion - (BNum + demodel.GuestNum));
                    return flag;
                }
            }
            //没有总经理修改订单权限
            if (!isEditOrder)
            {
                //if (demodel.Unit_Price < coursePrice)
                //{
                //    flag = false;
                //    message = "成交单价不能小于最低价格";
                //    return flag;
                //}
                if (demodel.JoinType == OrderJoinTypeEnum.InsertClass)
                {
                    var newPreferPrice = Math.Round(coursePrice / courseModel.ClassHours * (courseModel.ClassHours - demodel.StartClassHours) * demodel.GuestNum, 2);
                    if (demodel.PreferPrice != newPreferPrice)
                    {
                        flag = false;
                        message = "应收总额不正确";
                        return flag;
                    }
                }
                else if (demodel.JoinType == OrderJoinTypeEnum.TransOrder || demodel.JoinType == OrderJoinTypeEnum.SplitOrder)
                {
                    //不验证应收
                }
                else
                {
                    if (demodel.PreferPrice != (coursePrice * demodel.GuestNum))
                    {
                        flag = false;
                        message = "应收总额不正确";
                        return flag;
                    }
                }
            }
            //日志信息
            string LogContent = "";
            //销售备注
            string SaleRemark = "";
            if (demodel.OrderId > 0)
            {
                if (demodel.JoinType == OrderJoinTypeEnum.InsertClass)
                {
                    if (orderModel.EffectStatus != 2)
                    {
                        if (Convert.ToDateTime(Common.ConvertHelper.FormatTime(demodel.EffectTime)) < Convert.ToDateTime(Common.ConvertHelper.FormatTime(DateTime.Now)))
                        {
                            demodel.EffectStatus = 1;
                        }
                        else
                        {
                            demodel.EffectStatus = 0;
                        }
                    }
                    else
                    {
                        demodel.EffectStatus = orderModel.EffectStatus;
                    }
                }
                else
                {
                    demodel.EffectStatus = 2;
                    demodel.EffectTime = DateTime.Now;
                }

                if (orderModel == null)
                {
                    flag = false;
                    message = "订单不存在";
                    return flag;
                }
                if (orderModel.OrderState == Common.Enum.Course.OrderStateEnum.Cancel)
                {
                    flag = false;
                    message = "取消订单无法修改";
                    return flag;
                }

                #region 验证学生名单数量
                var glist = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { Group_Id = demodel.Group_Id, OrderId = demodel.OrderId, GuestState = GuestStateEnum.Normal });
                if (glist.Any() && orderModel.CustomerId != demodel.CustomerId) {
                    message = "订单已创建学生名单，无法修改其同行";
                    return false;
                }
                if (glist.Count() > demodel.GuestNum)
                {
                    flag = false;
                    message = "请先取消学生名单再修改订单人员数量";
                    return flag;
                }
                #endregion

                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_ViewModel.GuestNum),demodel.GuestNum},
                    { nameof(RB_Order_ViewModel.Unit_Price),demodel.Unit_Price},
                    { nameof(RB_Order_ViewModel.DiscountMoney),demodel.DiscountMoney},
                    { nameof(RB_Order_ViewModel.PerDiscountMoney),demodel.PerDiscountMoney},
                    { nameof(RB_Order_ViewModel.PreferPrice),demodel.PreferPrice},
                    { nameof(RB_Order_ViewModel.OrderSource),demodel.OrderSource},
                    { nameof(RB_Order_ViewModel.SaleRemark),demodel.SaleRemark},
                    { nameof(RB_Order_ViewModel.HelpEnterId),demodel.HelpEnterId},
                    { nameof(RB_Order_ViewModel.GeneralOccupation),demodel.GeneralOccupation},
                    { nameof(RB_Order_ViewModel.EduOccupation),demodel.EduOccupation},
                    { nameof(RB_Order_ViewModel.IsLessPrice),demodel.IsLessPrice},
                    { nameof(RB_Order_ViewModel.LessPrice),demodel.LessPrice},
                    { nameof(RB_Order_ViewModel.PerLessMoney),demodel.PerLessMoney},
                    { nameof(RB_Order_ViewModel.StartClassHours),demodel.StartClassHours},
                    { nameof(RB_Order_ViewModel.CourseId),demodel.CourseId},
                    { nameof(RB_Order_ViewModel.EffectStatus),demodel.EffectStatus},
                    { nameof(RB_Order_ViewModel.EffectTime),demodel.EffectTime},
                    { nameof(RB_Order_ViewModel.UpOrderId),demodel.UpOrderId},
                    { nameof(RB_Order_ViewModel.CustomerId),demodel.CustomerId},
                    { nameof(RB_Order_ViewModel.CourseConsultantId),demodel.CourseConsultantId},
                };
                flag = orderRepository.Update(keyValues, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), demodel.OrderId));
                #region 记录日志信息
                LogContent = $"修改日语培训订单【{demodel.OrderId}】";
                if (orderModel.GuestNum != demodel.GuestNum)
                {
                    LogContent += $"，人数由【{orderModel.GuestNum}】修改为【{demodel.GuestNum}】";
                }
                if (orderModel.Unit_Price != demodel.Unit_Price)
                {
                    LogContent += $"，成交单价由【{orderModel.Unit_Price}】修改为【{demodel.Unit_Price}】";
                }
                if (orderModel.DiscountMoney != demodel.DiscountMoney)
                {
                    LogContent += $"，优惠金额由【{(orderModel.DiscountMoney)}】修改为【{(demodel.DiscountMoney)}】";
                }
                if (orderModel.PerDiscountMoney != demodel.PerDiscountMoney)
                {
                    LogContent += $"，每人优惠金额由【{(orderModel.PerDiscountMoney)}】修改为【{(demodel.PerDiscountMoney)}】";
                }
                if (orderModel.PreferPrice != demodel.PreferPrice)
                {
                    LogContent += $"，应收金额由【{orderModel.PreferPrice}】修改为【{demodel.PreferPrice}】";
                }
                if (orderModel.OrderSource != demodel.OrderSource)
                {
                    LogContent += $"，客人来源由【{orderModel.OrderSource.ToName()}】修改为【{demodel.OrderSource.ToName()}】";
                }
                if (orderModel.HelpEnterId != demodel.HelpEnterId)
                {
                    var empList = accountRepository.GetAccountListRepository(new RB_Account_ViewModel() { QIds = orderModel.HelpEnterId + "," + demodel.HelpEnterId });
                    LogContent += $"，协助人员由【{empList?.Where(qitem => qitem.Id == orderModel.HelpEnterId)?.FirstOrDefault()?.AccountName}】修改为【{empList?.Where(qitem => qitem.Id == demodel.HelpEnterId)?.FirstOrDefault()?.AccountName}】";
                }
                if (orderModel.CourseConsultantId != demodel.CourseConsultantId)
                {
                    var empList = accountRepository.GetAccountListRepository(new RB_Account_ViewModel() { QIds = orderModel.CourseConsultantId + "," + demodel.CourseConsultantId });
                    LogContent += $"，课程顾问由【{empList?.Where(qitem => qitem.Id == orderModel.CourseConsultantId)?.FirstOrDefault()?.AccountName}】修改为【{empList?.Where(qitem => qitem.Id == demodel.CourseConsultantId)?.FirstOrDefault()?.AccountName}】";
                }
                if (orderModel.CustomerId != demodel.CustomerId)
                {
                    LogContent += $"，关联同行联系人由【{customerRepository.GetEntity(orderModel.CustomerId)?.CustomerName ?? ""}】修改为【{customerRepository.GetEntity(demodel.CustomerId)?.CustomerName ?? ""}】";
                }
                if (orderModel.GeneralOccupation != demodel.GeneralOccupation)
                {
                    LogContent += $"，一般同行由【{orderModel.GeneralOccupation}】修改为【{demodel.GeneralOccupation}】";
                }
                if (orderModel.EduOccupation != demodel.EduOccupation)
                {
                    LogContent += $"，教育同行由【{orderModel.EduOccupation}】修改为【{demodel.EduOccupation}】";
                }
                if (orderModel.IsLessPrice != demodel.IsLessPrice)
                {
                    LogContent += $"，少价由【{(orderModel.IsLessPrice > 0 ? "少价" : "不少价")}】修改为【{(demodel.IsLessPrice > 0 ? "少价" : "不少价")}】";
                }
                if (orderModel.LessPrice != demodel.LessPrice)
                {
                    LogContent += $"，少价金额由【{(orderModel.LessPrice)}】修改为【{(demodel.LessPrice)}】";
                }
                if (orderModel.PerLessMoney != demodel.PerLessMoney)
                {
                    LogContent += $"，每人少价金额由【{(orderModel.PerLessMoney)}】修改为【{(demodel.PerLessMoney)}】";
                }
                //记录订单备注
                if (orderModel.SaleRemark != demodel.SaleRemark)
                {
                    LogContent += $"，销售备注由【{orderModel.SaleRemark}】修改为【{demodel.SaleRemark}】";
                    SaleRemark = demodel.SaleRemark;
                }
                #endregion
            }
            else
            {
                if (demodel.JoinType == OrderJoinTypeEnum.InsertClass)
                {
                    if (Convert.ToDateTime(Common.ConvertHelper.FormatTime(demodel.EffectTime)) < Convert.ToDateTime(Common.ConvertHelper.FormatTime(DateTime.Now)))
                    {
                        demodel.EffectStatus = 1;
                    }
                    else
                    {
                        demodel.EffectStatus = 0;
                    }
                }
                else
                {
                    demodel.EffectStatus = 1;
                    demodel.EffectTime = DateTime.Now;
                }
                if (classModel.ClassStatus == Common.Enum.Course.ClassStatusEnum.EndClass)
                {
                    flag = false;
                    message = "班级状态不正确";
                    return flag;
                }
                demodel.Class_Price = courseModel.SellPrice;
                if (demodel.EnterID <= 0 && demodel.CreateBy > 0)
                {
                    if (userInfo.AccountType == AccountTypeEnum.Teacher)
                    {
                        demodel.HelpEnterId = demodel.CreateBy;
                    }
                    else
                    {
                        demodel.EnterID = demodel.CreateBy;
                    }
                }
                if (demodel.OrderIdentify == 2 && StuList.Where(x => x.IsRenewGuest == 1).Any())
                {
                    demodel.JoinType = OrderJoinTypeEnum.RenewOrder;
                }
                int OrderId = orderRepository.Insert(demodel);
                demodel.OrderId = OrderId;
                flag = OrderId > 0;
                LogContent = "新增日语培训订单";
                //记录订单备注
                if (!string.IsNullOrEmpty(demodel.SaleRemark))
                {
                    SaleRemark = demodel.SaleRemark;
                }

                #region 预约单转订单
                //预约单转订单
                if (flag && demodel.VisitorReserveId > 0)
                {
                    string remark = userInfo.AccountName + "转订单";
                    Dictionary<string, object> visitorFileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Visitor_Reserve_Extend.ReserveStatus),1 },
                        {nameof(RB_Visitor_Reserve_Extend.Remark),remark },
                        {nameof(RB_Visitor_Reserve_Extend.OrderId),demodel.OrderId },
                    };
                    flag = visitor_ReserveRepository.Update(visitorFileds, new WhereHelper(nameof(RB_Visitor_Reserve_Extend.Id), demodel.VisitorReserveId));
                    var visitorModel = visitor_ReserveRepository.GetVisitorRepository(new RB_Visitor_Reserve_Extend() { Id = demodel.VisitorReserveId })?.FirstOrDefault();
                    var guestModel = new RB_Order_Guest_ViewModel()
                    {
                        Id = 0,
                        OrderId = demodel.OrderId,
                        ClassId = demodel.ClassId,
                        GuestName = visitorModel?.Name ?? "",
                        GuestState = GuestStateEnum.Normal,
                        Profession = "",
                        Sex = 1,
                        Age = 18,
                        Mobile = visitorModel?.Tel ?? "",
                        Basics = visitorModel?.LevelType,
                        Education = GuestEducationEnum.N2,
                        GuestSource = demodel.OrderSource,
                        LearningGoals =0,
                        Contact = "",
                        ContactMobile = "",
                        Status = 0,
                        Group_Id = demodel.Group_Id,
                        School_Id = demodel.School_Id,
                        CreateBy = demodel.CreateBy,
                        CreateTime = demodel.CreateTime,
                        UpdateBy = demodel.UpdateBy,
                        UpdateTime = demodel.UpdateTime,
                        DropOutRemark = "",
                        IDCard = "",
                        Domicile = "",
                        ContactAddress = "",
                        SourceId = 0,
                        GraduatedSchool = "",
                        GraduatedMajor = "",
                        VolunteerMajor = "",
                        Price = 0,
                        StudyRemark = "",
                        TotalHours = Convert.ToInt32(courseModel.ClassHours),
                        CompleteHours = 0,
                        MakeUpHours = 0,
                        StuIcon = "",
                        RenewState = 1
                    };
                    SetOrderGuestInfo(guestModel, out string Nmessage);
                }
                #endregion

                #region 续课订单和转班订单和分拆订单 添加学员名单
                if (flag && demodel.OldGuestId > 0)
                {
                    var oldGuestModel = order_GuestRepository.GetEntity(demodel.OldGuestId);
                    var guestModel = new RB_Order_Guest_ViewModel()
                    {
                        Id = 0,
                        OrderId = demodel.OrderId,
                        ClassId = demodel.ClassId,
                        GuestName = oldGuestModel?.GuestName ?? "",
                        GuestState = GuestStateEnum.Normal,
                        Profession = oldGuestModel?.Profession ?? "",
                        Sex = oldGuestModel?.Sex ?? 1,
                        Age = oldGuestModel?.Age ?? 18,
                        Mobile = oldGuestModel?.Mobile ?? "",
                        Basics = oldGuestModel?.Basics,
                        Education = oldGuestModel?.Education ?? GuestEducationEnum.N2,
                        GuestSource = demodel.OrderSource,
                        LearningGoals = oldGuestModel?.LearningGoals ?? 0,
                        Contact = oldGuestModel?.Contact ?? "",
                        ContactMobile = oldGuestModel?.ContactMobile ?? "",
                        Status = 0,
                        Group_Id = demodel.Group_Id,
                        School_Id = demodel.School_Id,
                        CreateBy = demodel.CreateBy,
                        CreateTime = demodel.CreateTime,
                        UpdateBy = demodel.UpdateBy,
                        UpdateTime = demodel.UpdateTime,
                        DropOutRemark = "",
                        IDCard = oldGuestModel?.IDCard ?? "",
                        Domicile = oldGuestModel?.Domicile ?? "",
                        ContactAddress = oldGuestModel?.ContactAddress ?? "",
                        SourceId = 0,
                        GraduatedSchool = oldGuestModel?.GraduatedSchool ?? "",
                        GraduatedMajor = oldGuestModel?.GraduatedMajor ?? "",
                        VolunteerMajor = oldGuestModel?.VolunteerMajor ?? "",
                        Price = 0,
                        StudyRemark = "",
                        CompleteHours = 0,
                        MakeUpHours = 0,
                        StuIcon = "",
                        RenewState = 1
                    };
                    if (demodel.RenewOrderId > 0)
                    {
                        guestModel.TotalHours = Convert.ToInt32(courseModel.ClassHours);
                        guestModel.RenewState = 2;
                    }
                    else if (demodel.JoinType == OrderJoinTypeEnum.TransOrder)
                    {
                        //原订单学员的剩余课时
                        guestModel.TotalHours = oldGuestModel.TotalHours - oldGuestModel.CompleteHours;
                    }
                    else if (demodel.JoinType == OrderJoinTypeEnum.SplitOrder)
                    {
                        //新订单新课程的【根据时间计算的有效课时】
                        guestModel.TotalHours = demodel.NewGuestTotalClassHours;
                    }
                    SetOrderGuestInfo(guestModel, out string Nmessage);
                    demodel.NewGuestId = guestModel.Id;
                    #region 续费  学员介绍
                    RB_Student_ViewModel stuModel = null;
                    var sogModel = student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel() { GuestId = demodel.OldGuestId }).FirstOrDefault();
                    if (sogModel != null) {
                        stuModel = studentRepository.GetEntity<RB_Student_ViewModel>(sogModel.Student_Id);
                    }
                    if (stuModel != null && (demodel.RenewOrderId > 0 || (stuModel.CreateType == StuCreateTypeEnum.TransIntroduction && stuModel.StuSourceId > 0))) {
                        
                        int month = 1;
                        if (stuModel.FirstEnrollDate.HasValue)
                        {
                            month = ((demodel.CreateTime.Year - stuModel.FirstEnrollDate.Value.Year) * 12) + demodel.CreateTime.Month - stuModel.FirstEnrollDate.Value.Month + 1;
                        }
                        //续费
                        if (demodel.RenewOrderId > 0)
                        {
                            student_RenewOrderRepository.Insert(new Model.Entity.Customer.RB_Student_RenewOrder()
                            {
                                Id = 0,
                                CreateBy = demodel.CreateBy,
                                CreateTime = demodel.CreateTime,
                                Group_Id = demodel.Group_Id,
                                Month = month,
                                OrderId = OrderId,
                                Status = 0,
                                StuId = stuModel.StuId,
                                Type = 1
                            });
                        }
                        //学员介绍
                        if (stuModel.CreateType == StuCreateTypeEnum.TransIntroduction && stuModel.StuSourceId > 0)
                        {
                            student_RenewOrderRepository.Insert(new Model.Entity.Customer.RB_Student_RenewOrder()
                            {
                                Id = 0,
                                CreateBy = demodel.CreateBy,
                                CreateTime = demodel.CreateTime,
                                Group_Id = demodel.Group_Id,
                                Month = month,
                                OrderId = OrderId,
                                Status = 0,
                                StuId = stuModel.StuId,
                                Type = 2
                            });
                        }
                    }
                    #endregion
                }
                #endregion

                #region 插入学生名单(客户选择转订单)
                if (flag && demodel.OrderIdentify == 2) {
                    foreach (var item in StuList) {
                        var guestModel = new RB_Order_Guest_ViewModel()
                        {
                            Id = 0,
                            OrderId = demodel.OrderId,
                            ClassId = demodel.ClassId,
                            GuestName = item.StuName,
                            GuestState = GuestStateEnum.Normal,
                            Profession = item?.StuProfession ?? "",
                            Sex = (item?.StuSex ?? 1) + 1,
                            Age = item.StuBirth.HasValue ? DateTime.Now.Year - item.StuBirth.Value.Year : 18,
                            Mobile = item?.StuTel ?? "",
                            Basics = "",
                            Education = item?.StuEducation ?? GuestEducationEnum.N2,
                            GuestSource = demodel.OrderSource,
                            LearningGoals = item?.StuPurpose ?? 0,
                            Contact = item?.StuContract ?? "",
                            ContactMobile = item?.StuContractMobile ?? "",
                            Status = 0,
                            Group_Id = demodel.Group_Id,
                            School_Id = demodel.School_Id,
                            CreateBy = demodel.CreateBy,
                            CreateTime = demodel.CreateTime,
                            UpdateBy = demodel.UpdateBy,
                            UpdateTime = demodel.UpdateTime,
                            DropOutRemark = "",
                            IDCard = item?.StuIDCard ?? "",
                            Domicile = item?.StuIDCardAddress ?? "",
                            ContactAddress = item?.StuAddress ?? "",
                            SourceId = 0,
                            GraduatedSchool = "",
                            GraduatedMajor = "",
                            VolunteerMajor = "",
                            Price = 0,
                            StudyRemark = "",
                            CompleteHours = 0,
                            MakeUpHours = 0,
                            StuIcon = item.StuIcon,
                            TotalHours = Convert.ToInt32(courseModel.ClassHours),
                            RenewState = item.IsRenewGuest == 1 ? 2 : 1,
                            QQ=item.QQ,
                            WeChatNo=item.WeChatNo,
                        };
                        SetOrderGuestInfo(guestModel, out string Nmessage);

                        #region 更新客人阶段

                        //if (item.IsRenewGuest == 1 && item.StuStage == Common.Enum.User.StuStageEnum.Clinch)
                        //{
                        //    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        //        { nameof(RB_Student_ViewModel.StuStage), Common.Enum.User.StuStageEnum.MultipleClinch}
                        //    };
                        //    List<WhereHelper> wheres = new List<WhereHelper>() {
                        //         new WhereHelper(){
                        //            FiledName = nameof (RB_Student_ViewModel.StuId),
                        //             FiledValue = item.StuId,
                        //              OperatorEnum =OperatorEnum.Equal
                        //         }
                        //    };
                        //    studentRepository.Update(keyValues, wheres);
                        //    student_LogRepository.Insert(new Model.Entity.Customer.RB_Student_Log()
                        //    {
                        //        LogId = 0,
                        //        CreateBy = userInfo.Id,
                        //        CreateTime = DateTime.Now,
                        //        CreateType = 1,
                        //        Group_Id = userInfo.Group_Id,
                        //        LogContent = "首次续课，客户阶段由'" + (Common.Enum.User.StuStageEnum.Clinch.ToName()) + "'自动转换为'" + (Common.Enum.User.StuStageEnum.MultipleClinch.ToName()) +"'",
                        //        LogTitle = "客户阶段变更",
                        //        LogType = Common.Enum.Log.StudentLogTypeEnum.BasicInfo,
                        //        StuId = item.StuId
                        //    });
                        //}
                        //else if (item.StuStage < Common.Enum.User.StuStageEnum.Clinch)
                        //{
                        //    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        //        { nameof(RB_Student_ViewModel.StuStage), Common.Enum.User.StuStageEnum.Clinch}
                        //    };
                        //    List<WhereHelper> wheres = new List<WhereHelper>() {
                        //         new WhereHelper(){
                        //            FiledName = nameof (RB_Student_ViewModel.StuId),
                        //             FiledValue = item.StuId,
                        //              OperatorEnum =OperatorEnum.Equal
                        //         }
                        //    };
                        //    studentRepository.Update(keyValues, wheres);
                        //    student_LogRepository.Insert(new Model.Entity.Customer.RB_Student_Log()
                        //    {
                        //        LogId = 0,
                        //        CreateBy = userInfo.Id,
                        //        CreateTime = DateTime.Now,
                        //        CreateType = 1,
                        //        Group_Id = userInfo.Group_Id,
                        //        LogContent = "首次生成订单，客户阶段由'" + (item.StuStage.ToName()) + "'自动转换为'" + (Common.Enum.User.StuStageEnum.Clinch.ToName()) + "'",
                        //        LogTitle = "客户阶段变更",
                        //        LogType = Common.Enum.Log.StudentLogTypeEnum.BasicInfo,
                        //        StuId = item.StuId
                        //    });
                        //}
                        #endregion

                        #region 更新首次报名时间
                        if (item.IsRenewGuest != 1) {
                            //非续费 更新首次报名
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Student_ViewModel.FirstEnrollDate), DateTime.Now}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_Student_ViewModel.StuId),
                                      FiledValue = item.StuId,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            studentRepository.Update(keyValues, wheres);
                        }
                        #endregion

                        #region 续费  学员介绍
                        if (item.IsRenewGuest == 1 || (item.CreateType == StuCreateTypeEnum.TransIntroduction && item.StuSourceId > 0))
                        {
                            int month = 1;
                            if (item.FirstEnrollDate.HasValue)
                            {
                                month = ((demodel.CreateTime.Year - item.FirstEnrollDate.Value.Year) * 12) + demodel.CreateTime.Month - item.FirstEnrollDate.Value.Month + 1;
                            }
                            //续费
                            if (item.IsRenewGuest == 1)
                            {
                                student_RenewOrderRepository.Insert(new Model.Entity.Customer.RB_Student_RenewOrder()
                                {
                                    Id = 0,
                                    CreateBy = demodel.CreateBy,
                                    CreateTime = demodel.CreateTime,
                                    Group_Id = demodel.Group_Id,
                                    Month = month,
                                    OrderId = OrderId,
                                    Status = 0,
                                    StuId = item.StuId,
                                    Type = 1
                                });
                            }
                            //学员介绍
                            if (item.CreateType == StuCreateTypeEnum.TransIntroduction && item.StuSourceId > 0)
                            {
                                student_RenewOrderRepository.Insert(new Model.Entity.Customer.RB_Student_RenewOrder()
                                {
                                    Id = 0,
                                    CreateBy = demodel.CreateBy,
                                    CreateTime = demodel.CreateTime,
                                    Group_Id = demodel.Group_Id,
                                    Month = month,
                                    OrderId = OrderId,
                                    Status = 0,
                                    StuId = item.StuId,
                                    Type = 2
                                });
                            }
                        }
                        #endregion
                    }
                }
                #endregion

                #region 更新甲鹤小程序规格对应的库存
                if (flag && demodel.JoinType != OrderJoinTypeEnum.RenewOrder)//续费订单不去更新规格库存
                {
                    System.Threading.Tasks.Task.Run(() => UpdateClassInventoryNum(demodel));
                }
                #endregion

                #region 更新客人协助人员
                if (demodel.OrderIdentify == 2 && (demodel.HelpEnterId > 0 || demodel.CourseConsultantId > 0)) {
                    //客户转订单这种适配
                    int StuId = StuList.FirstOrDefault().StuId;
                    //更新协助人员
                    var list = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend()
                    {
                        StuId = StuId
                    });
                    if (demodel.HelpEnterId > 0) {
                        var assModel = list.Where(x => x.AssistType == Common.Enum.User.AssistTypeEnum.Teacher).FirstOrDefault();
                        if (assModel == null) {
                            student_AssistRepository.Insert(new Model.Entity.Customer.RB_Student_Assist()
                            {
                                Id = 0,
                                AssistId = demodel.HelpEnterId,
                                AssistType = Common.Enum.User.AssistTypeEnum.Teacher,
                                CreateBy = userInfo.Id,
                                CreateTime = DateTime.Now,
                                Status = DateStateEnum.Normal,
                                StuId = StuId
                            });
                        }
                    }
                    //更新课程顾问
                    if (demodel.CourseConsultantId > 0) {
                        var assModel = list.Where(x => x.AssistType == Common.Enum.User.AssistTypeEnum.CourseAdviser).FirstOrDefault();
                        if (assModel == null)
                        {
                            student_AssistRepository.Insert(new Model.Entity.Customer.RB_Student_Assist()
                            {
                                Id = 0,
                                AssistId = demodel.CourseConsultantId,
                                AssistType = Common.Enum.User.AssistTypeEnum.CourseAdviser,
                                CreateBy = userInfo.Id,
                                CreateTime = DateTime.Now,
                                Status = DateStateEnum.Normal,
                                StuId = StuId
                            });
                        }
                    }
                }
                #endregion

                #region 推送订单报入日志
                var queryNotifyManager = accountRepository.GetWorkUserIdByDictRepository("Push_NewOrder");
                var param = new RB_Class_ViewModel()
                {
                    ClassId = demodel.ClassId,
                    ClassScrollType = 0
                };
                var classDetailModel = classRepository.GetClassAndCourseListRepository(param).FirstOrDefault();
                if (queryNotifyManager != null && queryNotifyManager.Count > 0)
                {
                    queryNotifyManager.ForEach(x =>
                    {
                        var path = $"/sale/orderStatistics?OrderId={OrderId}";
                        path = HttpUtility.UrlEncode(path);

                        string markdownContent = $"<font color='info'>新订单通知</font> 新报入订单推送通知\n>**概要信息** \n>订单编号：{OrderId}\n>关联销售：{userInfo.AccountName}\n>报入班级：{classDetailModel.ClassName}\n>带班老师：{classDetailModel.TeacherName}\n>学习课程：{classDetailModel.CourseName}\n>开班时间：{classDetailModel.OpenTime}\n>订单金额：<font color='warning'>￥{demodel.PreferPrice}({demodel.GuestNum}人)</font>\n>销售备注：<font color='comment'>{demodel.SaleRemark}</font>\n>请点击：[查看详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={path})";
                        Common.Message.PushMessageModel modelWork = new Common.Message.PushMessageModel()
                        {
                            CategoryId = PushMessageCategoryEnum.SalePeople,
                            Content = markdownContent,
                            CoverImg = "",
                            CreateByName = "系统",
                            JumpUrl = "",
                            WorkMsgType = "markdown",
                            SendTime = DateTime.Now,
                            SendType = 0,
                            Title = "新订单通知",
                            Platform = 5,
                            ReceiveId = x.WorkUserId
                        };
                        Common.Message.MessageHelper.SendMessage(modelWork);
                    });
                }

                #endregion

                // 处理返佣信息
                System.Threading.Tasks.Task.Run(() => SetReturnOrderCommission(demodel));
            }

            #region 写日志
            if (flag)
            {
                //销售备注
                if (!string.IsNullOrEmpty(SaleRemark))
                {
                    order_RemarkRepository.Insert(new RB_Order_Remark()
                    {
                        Id = 0,
                        Content = SaleRemark,
                        CreateBy = demodel.CreateBy,
                        CreateTime = DateTime.Now,
                        OrderId = demodel.OrderId,
                        Type = 1
                    });
                }

                //订单日志
                if (!string.IsNullOrEmpty(LogContent))
                {
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = LogContent,
                        School_Id = userInfo.School_Id,
                        SourceId = demodel.OrderId
                    });
                }                
            }
            #endregion
            return flag;
        }


        /// <summary>
        /// 更新订单提成比例
        /// </summary>
        /// <returns></returns>
        public bool UpdateClassOrderCommissionRate()
        {
            var orderList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel() { Group_Id = 100000, OrderType = OrderTypeEnum.CourseOrder, Q_OrderState = 1 });
            foreach (var item in orderList)
            {
                //根据班级查询课程
                var classModel = classRepository.GetEntity(item.ClassId);

                #region 计算订单优惠信息
                //获取课程优惠
                var coursePreferentialList = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
                {
                    CourseId = classModel.CouseId
                });
                //课程优惠信息
                RB_Course_Preferential_Extend coursePreferentialModel = null;
                if (coursePreferentialList != null && coursePreferentialList.Count > 0)
                {
                    if (item.RenewOrderId > 0 && coursePreferentialList.Where(x => x.PriceDiscountType == CoursePriceDiscountEnum.Renewal).Any())
                    {
                        coursePreferentialModel = coursePreferentialList?.Where(qitem => qitem.PriceDiscountType == CoursePriceDiscountEnum.Renewal)?.FirstOrDefault();
                    }
                    if (coursePreferentialModel == null)
                    {
                        if (item.GuestNum == 1)
                        {
                            coursePreferentialModel = coursePreferentialList?.Where(qitem => qitem.PriceDiscountType == CoursePriceDiscountEnum.SingleJoin)?.FirstOrDefault();
                        }
                        if (item.GuestNum >= 2)
                        {
                            coursePreferentialModel = coursePreferentialList?.Where(qitem => qitem.PriceDiscountType == CoursePriceDiscountEnum.DoubleJoin)?.FirstOrDefault();
                        }
                    }
                    if (coursePreferentialModel == null)
                    {
                        //随便取一个了
                        coursePreferentialModel = coursePreferentialList.FirstOrDefault();
                    }

                    #region 记录提成信息
                    item.CommissionType = coursePreferentialModel?.SaleCommissionType ?? 0;
                    item.CommissionRate = coursePreferentialModel?.SaleCommissionMoney ?? 0;
                    item.CommissionTypeTH = coursePreferentialModel?.B2BCommissionType ?? 0;
                    item.CommissionRateTH = coursePreferentialModel?.B2BCommissionMoney ?? 0;
                    if (coursePreferentialModel != null)
                    {
                        item.CommissionRemark = "初始化使用优惠Id:" + coursePreferentialModel.Id + " 返佣类型:" + item.CommissionType + " 返佣比例/金额:" + item.CommissionRate + " 同行返佣类型:" + item.CommissionTypeTH + " 同行返佣比例/金额:" + item.CommissionRateTH;
                    }
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Order_ViewModel.CommissionType),item.CommissionType},
                        { nameof(RB_Order_ViewModel.CommissionRate),item.CommissionRate},
                        { nameof(RB_Order_ViewModel.CommissionTypeTH),item.CommissionTypeTH},
                        { nameof(RB_Order_ViewModel.CommissionRateTH),item.CommissionRateTH},
                        { nameof(RB_Order_ViewModel.CommissionRemark),item.CommissionRemark},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Order_ViewModel.OrderId),
                              FiledValue=item.OrderId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    orderRepository.Update(keyValues, wheres);
                    #endregion
                }
                #endregion
            }
            return true;
        }

        /// <summary>
        /// 留学就业下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetStudyOrderModule(RB_Order_ViewModel demodel, UserInfo userInfo, out string message)
        {
            bool flag = false;
            message = "";
            var studyModel = studyAbroadRepository.GetEntity(demodel.SourceId);
            if (studyModel == null)
            {
                flag = false;
                message = "留学就业产品不存在";
                return flag;
            }
            demodel.OldPreferPrice = studyModel.SellPrice * demodel.GuestNum;

            demodel.Class_Price = studyModel.SellPrice;
            decimal MinPrice = studyModel.SellPrice;
            if (demodel.Unit_Price < MinPrice)
            {
                flag = false;
                message = "成交单价不能小于最低价格";
                return flag;
            }
            if (demodel.OrderNature == OrderNatureEnum.ThroughTrain && demodel.PreferPrice != demodel.Unit_Price * demodel.GuestNum)
            {
                flag = false;
                message = "应收总额不正确";
                return flag;
            }
            if (demodel.OrderId > 0)
            {
                var orderModel = orderRepository.GetEntity(demodel.OrderId);
                if (orderModel == null)
                {
                    flag = false;
                    message = "订单不存在";
                    return flag;
                }
                if (orderModel.OrderState == Common.Enum.Course.OrderStateEnum.Cancel)
                {
                    flag = false;
                    message = "取消订单无法修改";
                    return flag;
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_ViewModel.GuestNum),demodel.GuestNum},
                    { nameof(RB_Order_ViewModel.Unit_Price),demodel.Unit_Price},
                    { nameof(RB_Order_ViewModel.PreferPrice),demodel.PreferPrice},
                    { nameof(RB_Order_ViewModel.OrderSource),demodel.OrderSource},
                    { nameof(RB_Order_ViewModel.SaleRemark),demodel.SaleRemark},
                    { nameof(RB_Order_ViewModel.OrderNature),demodel.OrderNature},
                    { nameof(RB_Order_ViewModel.OldPreferPrice),demodel.OldPreferPrice},
                };
                flag = orderRepository.Update(keyValues, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), demodel.OrderId));
                if (flag)
                {
                    //记录日志信息
                    string LogContent = $"修改留学就业订单【{demodel.OrderId}】";
                    if (orderModel.GuestNum != demodel.GuestNum)
                    {
                        LogContent += $"，人数由【{orderModel.GuestNum}】修改为【{demodel.GuestNum}】";
                    }
                    if (orderModel.Unit_Price != demodel.Unit_Price)
                    {
                        LogContent += $"，成交单价由【{orderModel.Unit_Price}】修改为【{demodel.Unit_Price}】";
                    }
                    if (orderModel.PreferPrice != demodel.PreferPrice)
                    {
                        LogContent += $"，应收金额由【{orderModel.PreferPrice}】修改为【{demodel.PreferPrice}】";
                    }
                    if (orderModel.OrderSource != demodel.OrderSource)
                    {
                        LogContent += $"，客人来源由【{orderModel.OrderSource.ToName()}】修改为【{demodel.OrderSource.ToName()}】";
                    }
                    if (orderModel.OrderNature != demodel.OrderNature)
                    {
                        LogContent += $"，订单性质由【{orderModel.OrderSource.ToName()}】修改为【{demodel.OrderSource.ToName()}】";
                    }
                    //记录订单备注
                    if (orderModel.SaleRemark != demodel.SaleRemark)
                    {
                        LogContent += $"，销售备注由【{orderModel.SaleRemark}】修改为【{demodel.SaleRemark}】";
                        order_RemarkRepository.Insert(new RB_Order_Remark()
                        {
                            Id = 0,
                            Content = demodel.SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = demodel.OrderId,
                            Type = 1
                        });
                    }
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = LogContent,
                        School_Id = userInfo.School_Id,
                        SourceId = demodel.OrderId
                    });
                }
            }
            else
            {
                if (studyModel.SaleState != Common.Enum.Sale.SaleStateEnum.Sell)
                {
                    flag = false;
                    message = "留学就业产品不正确";
                    return flag;
                }
                int OrderId = orderRepository.Insert(demodel);
                flag = OrderId > 0;
                if (flag)
                {
                    //记录订单备注
                    if (!string.IsNullOrEmpty(demodel.SaleRemark))
                    {
                        order_RemarkRepository.Insert(new RB_Order_Remark()
                        {
                            Id = 0,
                            Content = demodel.SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = OrderId,
                            Type = 1
                        });
                    }
                    //记录日志信息
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "新增留学就业订单",
                        School_Id = userInfo.School_Id,
                        SourceId = OrderId
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetClassOrderInfoModule(int orderId)
        {
            var model = orderRepository.GetEntity<RB_Order_ViewModel>(orderId);
            if (model != null)
            {
                if (model.OrderType == Common.Enum.Sale.OrderTypeEnum.CourseOrder)
                {
                    var classModel = classRepository.GetEntity(model.ClassId);
                    if (classModel != null)
                    {
                        model.ClassName = classModel?.ClassName ?? "";
                        model.OpenTime = classModel.OpenTime;
                    }
                }
                else if (model.OrderType == Common.Enum.Sale.OrderTypeEnum.StudyabroadOrder)
                {
                    model.ClassName = studyAbroadRepository.GetEntity(model.SourceId)?.Name ?? "";
                }
            }
            return model;
        }


        /// <summary>
        /// 获取订单阶梯价格
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<RB_Order_StepPrice_ViewModel> GetClassOrderSetpPrice(int orderId)
        {
            return order_StepPriceRepository.GetList(new RB_Order_StepPrice_ViewModel() { OrderId = orderId });
        }

        /// <summary>
        /// 获取日志列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_User_ChangeLog_ViewModel> GetClassOrderLogList(int pageIndex, int pageSize, out long count, RB_User_ChangeLog_ViewModel dmodel)
        {
            return changeLogRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
        }

        /// <summary>
        /// 转交订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="careOfPeople"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetClassOrderCareOf(int orderId, int careOfPeople, UserInfo userInfo)
        {
            var ordermodel = orderRepository.GetEntity(orderId);
            if (ordermodel == null) { return false; }
            if (ordermodel.EnterID != userInfo.Id)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() 
            {
                { nameof(RB_Order_ViewModel.EnterID),careOfPeople}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() 
            {
                new WhereHelper()
                {
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                     FiledValue=orderId,
                     OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志信息
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"修改【{orderId}】订单业务员，由【{UserReidsCache.GetUserLoginInfo(ordermodel.EnterID).AccountName}({ordermodel.EnterID})】修改为【{UserReidsCache.GetUserLoginInfo(careOfPeople).AccountName}({careOfPeople})】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool CancelClassOrder(int orderId, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_Order_ViewModel.OrderState),OrderStateEnum.Cancel}
            };
            if (orderModel.OfferId > 0)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.OfferId), 0);
            }
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper()
                {
                    FiledName=nameof(RB_Order_ViewModel.OrderId),
                    FiledValue=orderId,
                    OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                if (orderModel.OfferId > 0)
                {
                    Dictionary<string, object> offerFileds = new Dictionary<string, object>()
                    {
                        { nameof(RB_Course_Offer_ViewModel.CustomerStatus),(int)CustomerStatusEnum.Cancel},
                        { nameof(RB_Course_Offer_ViewModel.OrderId),0},
                    };
                    flag = course_OfferRepository.Update(offerFileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), orderModel.OfferId));
                }
                //记录日志信息
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"取消日语培训订单【{orderId}】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });

                #region 更新甲鹤小程序规格对应的库存
                if (flag && orderModel.JoinType != OrderJoinTypeEnum.RenewOrder)//续费订单不去更新规格库存
                {
                    List<int> classId = new List<int>
                    {
                        orderModel.ClassId
                    };
                    System.Threading.Tasks.Task.Run(() => UpdateGoodsSpecification(classId));
                }
                #endregion
            }
            return flag;
        }

        #endregion

        #region 班级或留学产品订单

        /// <summary>
        /// 班级或留学产品订单
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <param name="groupId"></param>
        /// <param name="SourceId">留学就业产品编号</param>
        /// <param name="ClassInfo"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetClassOrderList(int classId, int groupId, int SourceId, out object ClassInfo)
        {
            ClassInfo = new { };
            //获取订单列表
            var orderList = new List<RB_Order_ViewModel>();
            int courseId = 0;
            if (classId > 0)
            {
                var cModel = classRepository.GetEntity(classId);
                if (cModel == null)
                {
                    return new List<RB_Order_ViewModel>();
                }
                courseId = cModel.CouseId;
                //获取班级教师
                var tModel = teacherRepository.GetEntity(cModel.Teacher_Id);
                var zModel = assistRepository.GetEntity(cModel.Assist_Id);
                ClassInfo = new
                {
                    cModel.ClassName,
                    cModel.ClassNo,
                    tModel?.TeacherName,
                    tModel?.TeacherIcon,
                    zModel?.AssistName,
                    zModel?.AssistIcon
                };
            }
            else if (SourceId > 0)
            {
                var studyModel = studyAbroadRepository.GetEntity(SourceId);
                if (studyModel != null && studyModel.Id > 0)
                {
                    ClassInfo = new
                    {
                        StudyName = studyModel.Name,
                    };
                }
            }
            //获取订单列表
            var query = new RB_Order_ViewModel() { Group_Id = groupId, ClassId = classId, SourceId = SourceId };
            orderList = OrderPageModule(1, 100000, out _, query);
            return orderList;
        }

        /// <summary>
        /// 获取班级订单列表
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetClassOrderListExtModule(RB_Order_ViewModel query)
        {
            //获取订单列表
            var orderList = orderRepository.GetOrderListRepository(query);
            var guestList = new List<RB_Order_Guest_ViewModel>();
            if (orderList != null && orderList.Count > 0)
            {
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                //获取名单列表
                guestList = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { OrderIds = orderIds });
            }
            foreach (var item in orderList)
            {
                item.GuestList = guestList.Where(x => x.OrderId == item.OrderId).ToList();
            }
            return orderList;
        }

        /// <summary>
        /// 设置订单使用最新的班级价格
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool SetClassOrderUseNewClassPrice(int orderId)
        {
            var demodel = orderRepository.GetEntity(orderId);
            //查询班级信息
            var classModel = classRepository.GetEntity(demodel.ClassId);
            if (classModel == null)
            {
                return false;
            }
            List<RB_Class_StepPrice_ViewModel> spList = new List<RB_Class_StepPrice_ViewModel>();
            if (classModel.IsStepPrice == 1)
            {
                spList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { ClassId = demodel.ClassId });
            }
            return true;
        }

        /// <summary>
        /// 更新订单销售
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="enterID"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string UpdateOrderSale(int orderId, int enterID, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return "订单不存在，请核实后再试"; }
            if (orderModel.EnterID == enterID)
            {
                return "不能转交给同一人";
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() 
            {
                { nameof(RB_Order_ViewModel.EnterID),enterID}
            };
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper()
                {
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                     FiledValue=orderId,
                     OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = "修改销售，由" + (UserReidsCache.GetUserLoginInfo(orderModel.EnterID)?.AccountName ?? "") + "(" + orderModel.EnterID + ") 修改为" + (UserReidsCache.GetUserLoginInfo(enterID)?.AccountName ?? "") + "(" + enterID + ")",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag ? "" : "操作失败，请联系管理员";
        }

        /// <summary>
        /// 获取订单备注列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_Remark_ViewModel> GetClassOrderRemarkPageModule(int pageIndex, int pageSize, out long count, RB_Order_Remark_ViewModel dmodel)
        {
            return order_RemarkRepository.GetOrderRemarkPageRepository(pageIndex, pageSize, out count, dmodel);
        }

        /// <summary>
        /// 修改备注
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool UpdateOrderRemark(int orderId, int type, string remark, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            string LogContent;
            if (type == 2)
            {
                if (orderModel.TeacherRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.TeacherRemark), remark);
                LogContent = "修改教务备注：由【" + orderModel.TeacherRemark + "】修改为【" + remark + "】";
            }
            else if (type == 3)
            {
                if (orderModel.RectorRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.RectorRemark), remark);
                LogContent = "修改校长备注：由【" + orderModel.RectorRemark + "】修改为【" + remark + "】";
            }
            else if (type == 4)
            {
                if (orderModel.DirectorRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.DirectorRemark), remark);
                LogContent = "修改经理备注：由【" + orderModel.DirectorRemark + "】修改为【" + remark + "】";
            }
            else if (type == 1)
            {
                if (orderModel.SaleRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.SaleRemark), remark);
                LogContent = "修改销售备注：由【" + orderModel.SaleRemark + "】修改为【" + remark + "】";
            }
            else { return false; }
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper()
                {
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                     FiledValue=orderId,
                     OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                if (type == 1)
                {
                    order_RemarkRepository.Insert(new RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 1
                    });
                }
                else if (type == 2)
                {
                    order_RemarkRepository.Insert(new RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 2
                    });
                }
                else if (type == 3)
                {
                    order_RemarkRepository.Insert(new RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 3
                    });
                }
                else if (type == 4)
                {
                    order_RemarkRepository.Insert(new RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 4
                    });
                }
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = LogContent,
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        /// <summary>
        /// 修改提成
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="commissionMoney"></param>
        /// <param name="extraRewardMoney"></param>
        /// <param name="extraDeductMoney"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool UpdateOrderCommission(int orderId, int type, decimal commissionMoney, decimal extraRewardMoney, decimal extraDeductMoney, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            if (type == 1)
            {
                if (orderModel.IsCommissionGive != 1)
                {
                    return false;
                }
                if (orderModel.CommissionMoney == commissionMoney) { return true; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                {
                    { nameof(RB_Order_ViewModel.CommissionMoney),commissionMoney}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() 
                {
                     new WhereHelper()
                     {
                         FiledName=nameof(RB_Order_ViewModel.OrderId),
                         FiledValue=orderId,
                         OperatorEnum=OperatorEnum.Equal
                     }
                };
                var flag = orderRepository.Update(keyValues, wheres);
                if (flag)
                {
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "修改提成，由【" + orderModel.CommissionMoney + "】修改为【" + commissionMoney + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = orderId
                    });
                }
                return flag;
            }
            else
            {
                if (orderModel.ExtraRewardMoney != extraRewardMoney || orderModel.ExtraDeductMoney != extraDeductMoney)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                    {
                        { nameof(RB_Order_ViewModel.ExtraRewardMoney),extraRewardMoney},
                        { nameof(RB_Order_ViewModel.ExtraDeductMoney),extraDeductMoney}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>()
                    {
                         new WhereHelper()
                         {
                             FiledName=nameof(RB_Order_ViewModel.OrderId),
                             FiledValue=orderId,
                             OperatorEnum=OperatorEnum.Equal
                         }
                    };
                    var flag = orderRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        string LogContent = "修改额外金额";
                        if (orderModel.ExtraRewardMoney != extraRewardMoney)
                        {
                            LogContent += "，额外奖励由【" + orderModel.ExtraRewardMoney + "】修改为【" + extraRewardMoney + "】";
                        }
                        if (orderModel.ExtraDeductMoney != extraDeductMoney)
                        {
                            LogContent += "，额外扣除由【" + orderModel.ExtraDeductMoney + "】修改为【" + extraDeductMoney + "】";
                        }
                        changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                        {
                            Id = 0,
                            Type = 2,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            Group_Id = userInfo.Group_Id,
                            LogContent = LogContent,
                            School_Id = userInfo.School_Id,
                            SourceId = orderId
                        });
                    }
                    return flag;
                }
                else
                {
                    return true;
                }
            }
        }

        /// <summary>
        /// 订单转班
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="classId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetClassOrderCareOfClass(int orderId, int classId, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return "订单不存在"; }
            if (orderModel.OrderState == OrderStateEnum.Cancel) { return "订单状态不正确"; }
            if (orderModel.ClassId == classId) { return "转入班级不正确"; }
            var classModel = classRepository.GetEntity(classId);
            if (classModel == null) { return "班级不存在"; }
            //获取该班级下订单人数
            int BNum = orderRepository.GetClassOrderPeopleNumRepository(classId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
            if (BNum + orderModel.GuestNum > classModel.ClassPersion)
            {
                return "转入班级剩余招收人数不足，请核实后再试";
            }

            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_Order_ViewModel.ClassId),classId}
            };
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper()
                {
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                     FiledValue=orderId,
                     OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //查询所有的学生名单
                var glist = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { OrderId = orderId });
                foreach (var item in glist)
                {
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>()
                    {
                        { nameof(RB_Order_Guest_ViewModel.ClassId),classId}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>()
                    {
                        new WhereHelper()
                        {
                             FiledName=nameof(RB_Order_Guest_ViewModel.Id),
                             FiledValue=item.Id,
                             OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    order_GuestRepository.Update(keyValues1, wheres1);
                }
                //记录日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"订单转班，由【{orderModel.ClassId}】转移至【{classId}】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
                return "";
            }
            else
            {
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 设置订单应收金额
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="preferPrice"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetOrderPreferPrice(int orderId, decimal preferPrice, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() 
            {
                { nameof(RB_Order_ViewModel.PreferPrice),preferPrice}
            };
            if (orderModel.PreferPrice != preferPrice)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.IsCommissionGiveOK), 0);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() 
            {
                new WhereHelper()
                {
                    FiledName=nameof(RB_Order_ViewModel.OrderId),
                    FiledValue=orderId,
                    OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = "修改订单应收总额，由【" + orderModel.PreferPrice + "】修改为【" + preferPrice + "】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        /// <summary>
        /// 获取班级订单列表
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetClassOrderList_V2(int classId, int groupId, int SourceId)
        {
            //获取订单列表
            var orderList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel() { Group_Id = groupId, ClassId = classId, SourceId = SourceId });
            return orderList;
        }

        #endregion

        #region 学生名单
        /// <summary>
        /// 获取学生名单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_Guest_ViewModel> GetOrderGuestPageModule(int pageIndex, int pageSize, out long count, RB_Order_Guest_ViewModel dmodel)
        {
            var list = order_GuestRepository.GetOrderGuestPageRepository(pageIndex, pageSize, out count, dmodel);
            if (list != null && list.Count > 0)
            {
                string guestIds = string.Join(",", list.Select(qitem => qitem.Id));
                string goalIds = string.Join(",", list.Select(qitem => qitem.LearningGoals));

                var goalList= learningGoalsRepository.GetLearningGoalsListRepository(new Model.ViewModel.System.RB_LearningGoals_Extend()
                {
                    QGoalIds=goalIds
                });
                //查询学员[停课，退课，转班，分拆，临课]业务单据
                var guestEduReceiptList = education_ReceiptRepository.GetEducationReceiptListExtRepository(new EducationReceiptQuery()
                {
                    QGuestIds = guestIds,
                    QReceiptTypes = "2,3,4,5,6",
                });
                List<RB_Order_ViewModel> sourceTargetList = new List<RB_Order_ViewModel>();
                List<int> idList = new List<int>();
                var sourceOrderIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Select(x => x.SourceOrderId)));
                if (sourceOrderIdList != null && sourceOrderIdList.Count > 0)
                {
                    idList.AddRange(sourceOrderIdList);
                }
                var targetOrderIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Select(x => x.TargetOrderId)));
                if (targetOrderIdList != null && targetOrderIdList.Count > 0)
                {
                    idList.AddRange(targetOrderIdList);
                }
                if (idList != null && idList.Count > 0)
                {
                    string ids = string.Join(",", idList);
                    sourceTargetList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel { QOrderIds = ids });
                }
                foreach (var item in list)
                {
                    item.GuestEduReceiptList = guestEduReceiptList?
                        .Where(qitem => qitem.BackClassGuestId == item.Id
                      || qitem.StopClassGuestId == item.Id
                      || qitem.OrderChangeGuestId == item.Id
                      || qitem.TempinvitationGuestIds.Contains(item.Id.ToString())
                    )?.ToList() ?? new List<RB_Education_Receipt_ViewModel>();
                    if (item.SourceOrderId > 0)
                    {
                        item.SourceClassName = sourceTargetList?.Where(qitem => qitem.OrderId == item.SourceOrderId)?.FirstOrDefault()?.ClassName;
                    }
                    if (item.TargetOrderId > 0)
                    {
                        item.TargetClassName = sourceTargetList?.Where(qitem => qitem.OrderId == item.TargetOrderId)?.FirstOrDefault()?.ClassName;
                    }
                    item.LearningGoalsName = goalList?.FirstOrDefault(qitem => qitem.Id == item.LearningGoals)?.Name ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改 学生
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public  bool SetOrderGuestInfo(RB_Order_Guest_ViewModel dmodel, out string message)
        {
            bool flag = false;
            if (dmodel.BirthDate != null)
            {
                dmodel.Age = Common.ConvertHelper.GetAgeByBirthdate(dmodel.BirthDate);
            }
            message = "";
            //订单实体
            var ordermodel = orderRepository.GetEntity(dmodel.OrderId);
            if (ordermodel == null)
            {
                message = "订单不存在";
                return flag;
            }
            //班级实体
            var classmodel = classRepository.GetEntity(ordermodel.ClassId);
            string LogContent = "";
            //修改学员信息
            if (dmodel.Id > 0)
            {
                var gModel = order_GuestRepository.GetEntity(dmodel.Id);
                LogContent = "修改学生名单【" + dmodel.Id + "】";
                if (gModel.Age != dmodel.Age)
                {
                    LogContent += "，年龄由【" + gModel.Age + "】修改为【" + dmodel.Age + "】";
                }
                gModel.Age = dmodel.Age;

                if (gModel.Basics != dmodel.Basics)
                {
                    LogContent += "，日语基础由【" + gModel.Basics + "】修改为【" + dmodel.Basics + "】";
                }
                gModel.Basics = dmodel.Basics;

                if (gModel.Contact != dmodel.Contact)
                {
                    LogContent += "，紧急联系人由【" + gModel.Contact + "】修改为【" + dmodel.Contact + "】";
                }
                gModel.Contact = dmodel.Contact;

                if (gModel.ContactMobile != dmodel.ContactMobile)
                {
                    LogContent += "，紧急联系电话由【" + gModel.ContactMobile + "】修改为【" + dmodel.ContactMobile + "】";
                }
                gModel.ContactMobile = dmodel.ContactMobile;

                if (gModel.Education != dmodel.Education)
                {
                    LogContent += "，学历由【" + gModel.Education.ToName() + "】修改为【" + dmodel.Education.ToName() + "】";
                }
                gModel.Education = dmodel.Education;

                if (gModel.GuestName != dmodel.GuestName)
                {
                    LogContent += "，客人名称由【" + gModel.GuestName + "】修改为【" + dmodel.GuestName + "】";
                }
                gModel.GuestName = dmodel.GuestName;

                if (gModel.GuestSource != dmodel.GuestSource)
                {
                    LogContent += "，客人来源由【" + gModel.GuestSource.ToName() + "】修改为【" + dmodel.GuestSource.ToName() + "】";
                }
                gModel.GuestSource = dmodel.GuestSource;

                if (gModel.LearningGoals != dmodel.LearningGoals)
                {
                    string oldName = learningGoalsRepository.GetLearningGoalsExtEntityRepository(gModel.LearningGoals)?.Name ?? "";
                    string newName= learningGoalsRepository.GetLearningGoalsExtEntityRepository(dmodel.LearningGoals)?.Name ?? "";
                    LogContent += "，学习目的由【" + oldName + "】修改为【" + newName + "】";
                }
                gModel.LearningGoals = dmodel.LearningGoals;

                if (gModel.Mobile != dmodel.Mobile)
                {
                    LogContent += "，手机号码由【" + gModel.Mobile + "】修改为【" + dmodel.Mobile + "】";
                }
                gModel.Mobile = dmodel.Mobile;

                if (gModel.Profession != dmodel.Profession)
                {
                    LogContent += "，职业由【" + gModel.Profession + "】修改为【" + dmodel.Profession + "】";
                }
                gModel.Profession = dmodel.Profession;

                if (gModel.Sex != dmodel.Sex)
                {
                    LogContent += "，性别由【" + gModel.Sex + "】修改为【" + dmodel.Sex + "】";
                }
                gModel.Sex = dmodel.Sex;

                if (gModel.IDCard != dmodel.IDCard)
                {
                    LogContent += "，身份证由【" + gModel.IDCard + "】修改为【" + dmodel.IDCard + "】";
                }
                gModel.IDCard = dmodel.IDCard;

                if (gModel.Domicile != dmodel.Domicile)
                {
                    LogContent += "，身份证居住地由【" + gModel.Domicile + "】修改为【" + dmodel.Domicile + "】";
                }
                gModel.Domicile = dmodel.Domicile;

                if (gModel.ContactAddress != dmodel.ContactAddress)
                {
                    LogContent += "，联系地址由【" + gModel.ContactAddress + "】修改为【" + dmodel.ContactAddress + "】";
                }
                gModel.ContactAddress = dmodel.ContactAddress;

                if (gModel.GraduatedSchool != dmodel.GraduatedSchool)
                {
                    LogContent += "，毕业院校由【" + gModel.GraduatedSchool + "】修改为【" + dmodel.GraduatedSchool + "】";
                }
                gModel.GraduatedSchool = dmodel.GraduatedSchool;

                if (gModel.GraduatedMajor != dmodel.GraduatedMajor)
                {
                    LogContent += "，毕业专业由【" + gModel.GraduatedMajor + "】修改为【" + dmodel.GraduatedMajor + "】";
                }
                gModel.GraduatedMajor = dmodel.GraduatedMajor;

                if (gModel.VolunteerMajor != dmodel.VolunteerMajor)
                {
                    LogContent += "，志愿专业由【" + gModel.VolunteerMajor + "】修改为【" + dmodel.VolunteerMajor + "】";
                }
                gModel.VolunteerMajor = dmodel.VolunteerMajor;

                if (gModel.Price != dmodel.Price)
                {
                    LogContent += "，价格由【" + gModel.Price + "】修改为【" + dmodel.Price + "】";
                }
                gModel.Price = dmodel.Price;

                if (gModel.StudyRemark != dmodel.StudyRemark)
                {
                    LogContent += "，备注由【" + gModel.StudyRemark + "】修改为【" + dmodel.StudyRemark + "】";
                }
                gModel.StudyRemark = dmodel.StudyRemark;

                if (gModel.BirthDate != dmodel.BirthDate)
                {
                    LogContent += "，出身日期由【" + gModel.BirthDate + "】修改为【" + dmodel.BirthDate + "】";
                }
                gModel.BirthDate = dmodel.BirthDate;
                if (gModel.TotalHours != dmodel.TotalHours)
                {
                    LogContent += "，总课时由【" + gModel.TotalHours + "】修改为【" + dmodel.TotalHours + "】";
                }

                if (gModel.StuIcon != dmodel.StuIcon)
                {
                    LogContent += "，学生头像由【" + gModel.StuIcon + "】修改为【" + dmodel.StuIcon + "】";
                }
                gModel.StuIcon = dmodel.StuIcon;
                gModel.TotalHours = dmodel.TotalHours;
                gModel.GuestContractNo = dmodel.GuestContractNo;
                gModel.ContractType = dmodel.ContractType;
                gModel.ContractUrl = dmodel.ContractUrl;
                gModel.UpdateTime = dmodel.UpdateTime;
                flag = order_GuestRepository.Update(gModel);

            }
            //新增学员信息
            else
            {
                #region 验证电话是否已是他人客户
                if (!string.IsNullOrEmpty(dmodel.Mobile)) {
                    var slist = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = dmodel.Group_Id, StuTel = dmodel.Mobile, School_Id = -1 });
                    if (slist.Where(x => x.CustomerId != ordermodel.CustomerId).Any()) {
                        message = "学员'" + dmodel.GuestName + "'已被他人注册";
                        return false;
                    }
                }
                #endregion
                dmodel.ClassId = ordermodel.ClassId;
                dmodel.SourceId = ordermodel.SourceId;
                int GuestNum = order_GuestRepository.GetOrderGuestNumRepository(new RB_Order_Guest_ViewModel() { OrderId = dmodel.OrderId, GuestState = GuestStateEnum.Normal });
                if (GuestNum >= ordermodel.GuestNum)
                {
                    message = "学生名单已录入完毕";
                    return flag;
                }
                int Id = order_GuestRepository.Insert(dmodel);
                dmodel.Id = Id;
                flag = Id > 0;
            }

            #region  新增修改学员账号
            if (flag )
            {
                RB_Student_ViewModel stuModel = null;
                if ((dmodel?.StudentId ?? 0) > 0)
                {
                    //学员表
                    stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                    {
                         StuId= dmodel?.StudentId??0
                    });
                }
                else
                {
                    if (!string.IsNullOrEmpty(dmodel.Mobile))
                    {
                        //学员表
                        stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                        {
                            Group_Id = dmodel.Group_Id,
                            StuTel = dmodel.Mobile
                        });
                    }
                    if (stuModel == null && !string.IsNullOrEmpty(dmodel.QQ))
                    {
                        //学员表
                        stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                        {
                            Group_Id = dmodel.Group_Id,
                            QQ = dmodel.QQ
                        });
                    }
                    if (stuModel == null && !string.IsNullOrEmpty(dmodel.WeChatNo))
                    {
                        //学员表
                        stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                        {
                            Group_Id = dmodel.Group_Id,
                            WeChatNo = dmodel.WeChatNo
                        });
                    }
                }
          
                //不存在存在学员基本信息
                if (stuModel == null)
                {
                    //创建学生表信息
                    stuModel = new RB_Student_ViewModel()
                    {
                        StuId = 0,
                        AreaId = 0,
                        CityId = 0,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = dmodel.Group_Id,
                        IsDisable = 1,
                        ProviceId = 0,
                        School_Id = (classmodel?.School_Id??0),
                        Status = DateStateEnum.Normal,
                        StuBirth = dmodel.BirthDate,
                        StuIcon = dmodel.StuIcon,
                        StuName = dmodel.GuestName,
                        StuSex = dmodel.Sex - 1,
                        StuTel = dmodel.Mobile,
                        QQ = dmodel?.QQ ?? "",
                        WeChatNo = dmodel?.WeChatNo ?? "",
                        UpdateBy = dmodel.CreateBy,
                        UpdateTime = DateTime.Now,
                        CustomerId = ordermodel.CustomerId,
                        StuStage = 1,
                        CreateType = Common.Enum.User.StuCreateTypeEnum.EmployeeInput
                    };
                    studentRepository.SetStudentRepository(stuModel);
                }

                //检查【学员表(rb_order_guest)和学生表(rb_student)】关联信息
                var stuOrderGuestModel = student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel
                {
                    ClassId = ordermodel.ClassId,
                    OrderId = ordermodel.OrderId,
                    GuestId = dmodel.Id
                }).FirstOrDefault();
                //不存在学员表、学生表、账号表】关联信息
                if (stuOrderGuestModel == null)
                {
                    //创建【学员表、学生表、账号表】关联信息
                    student_OrderGuestRepository.Insert(new Model.Entity.User.RB_Student_OrderGuest()
                    {
                        Id = 0,
                        Account_Id = stuModel.Account_Id,
                        ClassId = ordermodel.ClassId,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        GuestId = dmodel.Id,
                        OrderId = dmodel.OrderId,
                        Status = DateStateEnum.Normal,
                        Student_Id = stuModel.StuId
                    });
                    LogContent += ",自动创建学生账号【" + stuModel.Account_Id + "】";
                }
            }
            #endregion

            #region 添加日志

            if (flag && !string.IsNullOrEmpty(LogContent))
            {
                //记录日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = dmodel.CreateBy,
                    CreateTime = DateTime.Now,
                    Group_Id = dmodel.Group_Id,
                    LogContent = LogContent,
                    School_Id = dmodel.School_Id,
                    SourceId = dmodel.OrderId
                });
            }
            #endregion

            return flag;
        }


        /// <summary>
        /// 新增修改 学生
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetOrderGuestInfo_V2(RB_Order_Guest_ViewModel dmodel, out string message)
        {
            bool flag = false;
            bool isAdd = dmodel.Id <= 0;
            if (dmodel.BirthDate != null)
            {
                dmodel.Age = Common.ConvertHelper.GetAgeByBirthdate(dmodel.BirthDate);
            }
            message = "";
            //订单实体
            var ordermodel = orderRepository.GetEntity(dmodel.OrderId);
            if (ordermodel == null)
            {
                message = "订单不存在";
                return flag;
            }
            //班级实体
            var classmodel = classRepository.GetEntity(ordermodel.ClassId);
            string LogContent = "";
            //修改学员信息
            if (dmodel.Id > 0)
            {
                var gModel = order_GuestRepository.GetEntity(dmodel.Id);
                LogContent = "修改学生名单【" + dmodel.Id + "】";
                if (gModel.Age != dmodel.Age)
                {
                    LogContent += "，年龄由【" + gModel.Age + "】修改为【" + dmodel.Age + "】";
                }
                gModel.Age = dmodel.Age;

                if (gModel.Basics != dmodel.Basics)
                {
                    LogContent += "，日语基础由【" + gModel.Basics + "】修改为【" + dmodel.Basics + "】";
                }
                gModel.Basics = dmodel.Basics;

                if (gModel.Contact != dmodel.Contact)
                {
                    LogContent += "，紧急联系人由【" + gModel.Contact + "】修改为【" + dmodel.Contact + "】";
                }
                gModel.Contact = dmodel.Contact;

                if (gModel.ContactMobile != dmodel.ContactMobile)
                {
                    LogContent += "，紧急联系电话由【" + gModel.ContactMobile + "】修改为【" + dmodel.ContactMobile + "】";
                }
                gModel.ContactMobile = dmodel.ContactMobile;

                if (gModel.Education != dmodel.Education)
                {
                    LogContent += "，学历由【" + gModel.Education.ToName() + "】修改为【" + dmodel.Education.ToName() + "】";
                }
                gModel.Education = dmodel.Education;

                if (gModel.GuestName != dmodel.GuestName)
                {
                    LogContent += "，客人名称由【" + gModel.GuestName + "】修改为【" + dmodel.GuestName + "】";
                }
                gModel.GuestName = dmodel.GuestName;

                if (gModel.GuestSource != dmodel.GuestSource)
                {
                    LogContent += "，客人来源由【" + gModel.GuestSource.ToName() + "】修改为【" + dmodel.GuestSource.ToName() + "】";
                }
                gModel.GuestSource = dmodel.GuestSource;

                if (gModel.LearningGoals != dmodel.LearningGoals)
                {
                    string oldName = learningGoalsRepository.GetLearningGoalsExtEntityRepository(gModel.LearningGoals)?.Name ?? "";
                    string newName = learningGoalsRepository.GetLearningGoalsExtEntityRepository(dmodel.LearningGoals)?.Name ?? "";
                    LogContent += "，学习目的由【" + oldName + "】修改为【" + newName + "】";
                }
                gModel.LearningGoals = dmodel.LearningGoals;

                if (gModel.Mobile != dmodel.Mobile)
                {
                    LogContent += "，手机号码由【" + gModel.Mobile + "】修改为【" + dmodel.Mobile + "】";
                }
                gModel.Mobile = dmodel.Mobile;

                if (gModel.Profession != dmodel.Profession)
                {
                    LogContent += "，职业由【" + gModel.Profession + "】修改为【" + dmodel.Profession + "】";
                }
                gModel.Profession = dmodel.Profession;

                if (gModel.Sex != dmodel.Sex)
                {
                    LogContent += "，性别由【" + gModel.Sex + "】修改为【" + dmodel.Sex + "】";
                }
                gModel.Sex = dmodel.Sex;

                if (gModel.IDCard != dmodel.IDCard)
                {
                    LogContent += "，身份证由【" + gModel.IDCard + "】修改为【" + dmodel.IDCard + "】";
                }
                gModel.IDCard = dmodel.IDCard;

                if (gModel.Domicile != dmodel.Domicile)
                {
                    LogContent += "，身份证居住地由【" + gModel.Domicile + "】修改为【" + dmodel.Domicile + "】";
                }
                gModel.Domicile = dmodel.Domicile;

                if (gModel.ContactAddress != dmodel.ContactAddress)
                {
                    LogContent += "，联系地址由【" + gModel.ContactAddress + "】修改为【" + dmodel.ContactAddress + "】";
                }
                gModel.ContactAddress = dmodel.ContactAddress;

                if (gModel.GraduatedSchool != dmodel.GraduatedSchool)
                {
                    LogContent += "，毕业院校由【" + gModel.GraduatedSchool + "】修改为【" + dmodel.GraduatedSchool + "】";
                }
                gModel.GraduatedSchool = dmodel.GraduatedSchool;

                if (gModel.GraduatedMajor != dmodel.GraduatedMajor)
                {
                    LogContent += "，毕业专业由【" + gModel.GraduatedMajor + "】修改为【" + dmodel.GraduatedMajor + "】";
                }
                gModel.GraduatedMajor = dmodel.GraduatedMajor;

                if (gModel.VolunteerMajor != dmodel.VolunteerMajor)
                {
                    LogContent += "，志愿专业由【" + gModel.VolunteerMajor + "】修改为【" + dmodel.VolunteerMajor + "】";
                }
                gModel.VolunteerMajor = dmodel.VolunteerMajor;

                if (gModel.Price != dmodel.Price)
                {
                    LogContent += "，价格由【" + gModel.Price + "】修改为【" + dmodel.Price + "】";
                }
                gModel.Price = dmodel.Price;

                if (gModel.StudyRemark != dmodel.StudyRemark)
                {
                    LogContent += "，备注由【" + gModel.StudyRemark + "】修改为【" + dmodel.StudyRemark + "】";
                }
                gModel.StudyRemark = dmodel.StudyRemark;

                if (gModel.BirthDate != dmodel.BirthDate)
                {
                    LogContent += "，出身日期由【" + gModel.BirthDate + "】修改为【" + dmodel.BirthDate + "】";
                }
                gModel.BirthDate = dmodel.BirthDate;
                if (gModel.TotalHours != dmodel.TotalHours)
                {
                    LogContent += "，总课时由【" + gModel.TotalHours + "】修改为【" + dmodel.TotalHours + "】";
                }

                if (gModel.StuIcon != dmodel.StuIcon)
                {
                    LogContent += "，学生头像由【" + gModel.StuIcon + "】修改为【" + dmodel.StuIcon + "】";
                }
                gModel.StuIcon = dmodel.StuIcon;
                gModel.TotalHours = dmodel.TotalHours;
                gModel.GuestContractNo = dmodel.GuestContractNo;
                gModel.ContractType = dmodel.ContractType;
                gModel.ContractUrl = dmodel.ContractUrl;
                gModel.UpdateTime = dmodel.UpdateTime;
                flag = order_GuestRepository.Update(gModel);

            }
            //新增学员信息
            else
            {
                #region 验证电话是否已是他人客户
                if (!string.IsNullOrEmpty(dmodel.Mobile))
                {
                    var slist = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = dmodel.Group_Id, StuTel = dmodel.Mobile, School_Id = -1 });
                    if (slist.Where(x => x.CustomerId != ordermodel.CustomerId).Any())
                    {
                        message = "学员'" + dmodel.GuestName + "'已被他人注册";
                        return false;
                    }
                }
                #endregion
                dmodel.ClassId = ordermodel.ClassId;
                dmodel.SourceId = ordermodel.SourceId;
                int GuestNum = order_GuestRepository.GetOrderGuestNumRepository(new RB_Order_Guest_ViewModel() { OrderId = dmodel.OrderId, GuestState = GuestStateEnum.Normal });
                if (GuestNum >= ordermodel.GuestNum)
                {
                    message = "学生名单已录入完毕";
                    return flag;
                }
                int Id = order_GuestRepository.Insert(dmodel);
                dmodel.Id = Id;
                flag = Id > 0;
            }

            #region  新增修改学员账号
            if (flag&& isAdd)
            {
                RB_Student_ViewModel stuModel = null;
                if (!string.IsNullOrEmpty(dmodel.Mobile))
                {
                    //学员表
                    stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                    {
                        Group_Id = dmodel.Group_Id,
                        StuTel = dmodel.Mobile
                    });
                }
                if (stuModel == null && !string.IsNullOrEmpty(dmodel.QQ))
                {
                    //学员表
                    stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                    {
                        Group_Id = dmodel.Group_Id,
                        QQ = dmodel.QQ
                    });
                }
                if (stuModel == null && !string.IsNullOrEmpty(dmodel.WeChatNo))
                {
                    //学员表
                    stuModel = studentRepository.GetStuByTelRepository(new RB_Student_ViewModel()
                    {
                        Group_Id = dmodel.Group_Id,
                        WeChatNo = dmodel.WeChatNo
                    });
                }

                //不存在存在学员基本信息
                if (stuModel == null)
                {
                    //创建学生表信息
                    stuModel = new RB_Student_ViewModel()
                    {
                        StuId = 0,
                        AreaId = 0,
                        CityId = 0,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = dmodel.Group_Id,
                        IsDisable = 1,
                        ProviceId = 0,
                        School_Id = (classmodel?.School_Id ?? 0),
                        Status = DateStateEnum.Normal,
                        StuBirth = dmodel.BirthDate,
                        StuIcon = dmodel.StuIcon,
                        StuName = dmodel.GuestName,
                        StuSex = dmodel.Sex - 1,
                        StuTel = dmodel.Mobile,
                        QQ = dmodel?.QQ ?? "",
                        WeChatNo = dmodel?.WeChatNo ?? "",
                        UpdateBy = dmodel.CreateBy,
                        UpdateTime = DateTime.Now,
                        CustomerId = ordermodel.CustomerId,
                        StuStage = 1,
                        CreateType = Common.Enum.User.StuCreateTypeEnum.EmployeeInput
                    };
                    studentRepository.SetStudentRepository(stuModel);
                }

                //检查【学员表(rb_order_guest)和学生表(rb_student)】关联信息
                var stuOrderGuestModel = student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel
                {
                    ClassId = ordermodel.ClassId,
                    OrderId = ordermodel.OrderId,
                    GuestId = dmodel.Id
                }).FirstOrDefault();
                //不存在学员表、学生表、账号表】关联信息
                if (stuOrderGuestModel == null)
                {
                    //创建【学员表、学生表、账号表】关联信息
                    student_OrderGuestRepository.Insert(new Model.Entity.User.RB_Student_OrderGuest()
                    {
                        Id = 0,
                        Account_Id = stuModel.Account_Id,
                        ClassId = ordermodel.ClassId,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        GuestId = dmodel.Id,
                        OrderId = dmodel.OrderId,
                        Status = DateStateEnum.Normal,
                        Student_Id = stuModel.StuId
                    });
                    LogContent += ",自动创建学生账号【" + stuModel.Account_Id + "】";
                }
            }
            #endregion

            #region 添加日志

            if (flag && !string.IsNullOrEmpty(LogContent))
            {
                //记录日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = dmodel.CreateBy,
                    CreateTime = DateTime.Now,
                    Group_Id = dmodel.Group_Id,
                    LogContent = LogContent,
                    School_Id = dmodel.School_Id,
                    SourceId = dmodel.OrderId
                });
            }
            #endregion

            return flag;
        }

        /// <summary>
        /// 删除学生名单
        /// </summary>
        /// <param name="guestId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool DelOrderGuestInfo(int guestId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order_Guest_ViewModel.Status),1}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_Guest_ViewModel.Id),
                      FiledValue=guestId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = order_GuestRepository.Update(keyValues, wheres);
            if (flag)
            {
                var gmodel = order_GuestRepository.GetEntity(guestId);
                //查询学生账号
                //var sModel = student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel() { OrderId = gmodel?.OrderId ?? 0, GuestId = guestId }).FirstOrDefault();
                //if (sModel != null) {
                //    //更新账号表 
                //    Dictionary<string, object> valuePairs = new Dictionary<string, object>() {
                //        { nameof(RB_Account_ViewModel.Status),DateStateEnum.Delete}
                //    };
                //    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                //        new WhereHelper(){
                //             FiledName=nameof(RB_Account_ViewModel.Id),
                //              FiledValue=sModel.Account_Id,
                //               OperatorEnum=OperatorEnum.Equal
                //        }
                //    };
                //    accountRepository.Update(valuePairs, wheres1);
                //}
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = "删除学生名单【" + guestId + "】",
                    School_Id = userInfo.Id,
                    SourceId = gmodel?.OrderId ?? 0
                });
            }
            return flag;
        }

        #endregion

        #region 销售中心

        /// <summary>
        /// 获取班级上课时间列表
        /// </summary>
        /// <param name="classIds"></param>
        public List<RB_Class_Time_ViewModel> GetClassOpenTimeListModule(string classIds)
        {
            var classTimeList = class_TimeRepository.GetClassTimeListRepository(classIds);
            return classTimeList;
        }

        /// <summary>
        /// 获取我的订单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetMyOrderPageList(int pageIndex, int pageSize, out long count, RB_Order_ViewModel demodel)
        {
            return OrderPageModule(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取订单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        private List<RB_Order_ViewModel> OrderPageModule(int pageIndex, int pageSize, out long count, RB_Order_ViewModel demodel)
        {
            //获取订单列表
            var orderList = orderRepository.GetOrderPageRepository(pageIndex, pageSize, out count, demodel);
            if (orderList.Any())
            {
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                //学员信息
                List<RB_Student_ViewModel> stuList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { QOrderIds = orderIds },isQueryCreateType:true);
               
                List<int> idList = new List<int>();
                List<RB_Order_ViewModel> sourceTargetList = new List<RB_Order_ViewModel>();
                var sourceOrderIdList = Common.ConvertHelper.StringToList(string.Join(",", orderList.Select(x => x.SourceOrderId)));
                if (sourceOrderIdList != null && sourceOrderIdList.Count > 0)
                {
                    idList.AddRange(sourceOrderIdList);
                }
                var targetOrderIdList = Common.ConvertHelper.StringToList(string.Join(",", orderList.Select(x => x.TargetOrderId)));
                if (targetOrderIdList != null && targetOrderIdList.Count > 0)
                {
                    idList.AddRange(targetOrderIdList);
                }
                List<RB_Order_SplitDetails_ViewModel> splitList = new List<RB_Order_SplitDetails_ViewModel>();
                var firstOrderList = Common.ConvertHelper.StringToList(string.Join(",", orderList.Where(qitem => qitem.FirstOrderId > 0).Select(x => x.FirstOrderId)));
                if (firstOrderList != null && firstOrderList.Count > 0)
                {
                    splitList = splitDetailsRepository.GetOrderSplitDetailsListRepository(new RB_Order_SplitDetails_ViewModel()
                    {
                        Q_OldOrderIds = string.Join(",", firstOrderList)
                    });
                }

                if (idList != null && idList.Count > 0)
                {
                    string ids = string.Join(",", idList);
                    sourceTargetList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel { QOrderIds = ids });
                }

                //获取备注列表
                var remarkList = order_RemarkRepository.GetOrderRemarkListRepository(new RB_Order_Remark_ViewModel() { QOrderIds = orderIds });
                //获取名单列表
                var guestList = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { OrderIds = orderIds });

                //获取合同列表
                var clist = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel() { Group_Id = demodel.Group_Id, OrderIds = orderIds, Status = -1 }).Where(x => x.Status != 4).ToList();
                //获取新的业绩提成
                var achList = sell_Achievements_EmpRepository.GetList(new RB_Sell_Achievements_Emp_ViewModel() { Group_Id = demodel.Group_Id, OrderIds = orderIds });

                foreach (var item in orderList)
                {
                    if (item.SourceOrderId > 0)
                    {
                        item.SourceClassName = sourceTargetList?.Where(qitem => qitem.OrderId == item.SourceOrderId)?.FirstOrDefault()?.ClassName;
                    }
                    if (item.TargetOrderId > 0)
                    {
                        item.TargetClassName = sourceTargetList?.Where(qitem => qitem.OrderId == item.TargetOrderId)?.FirstOrDefault()?.ClassName;
                    }
                    item.SplitDetailsList = splitList.Where(qitem => qitem.OldOrderId == item.OrderId || qitem.OldOrderId == item.FirstOrderId)?.ToList() ?? new List<RB_Order_SplitDetails_ViewModel>();
                    item.SaleRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 1).ToList();
                    item.TeacherRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 2).ToList();
                    item.RectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 3).ToList();
                    item.DirectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 4).ToList();
                    item.GuestList = guestList.Where(x => x.OrderId == item.OrderId).ToList();
                    item.ContractList = clist.Where(x => x.OrderId == item.OrderId).ToList();
                    if (item.GuestList != null && item.GuestList.Count > 0)
                    {
                        foreach (var subItem in item.GuestList)
                        {
                            var contractModel = clist.Where(x => x.OrderId == item.OrderId && x.GuestId == subItem.Id)?.FirstOrDefault();
                            subItem.ContractId = contractModel?.Id ?? 0;
                            subItem.ContractNo = contractModel?.ContractNo ?? "";
                            subItem.ContractStatus = contractModel?.Status ?? -1;
                            string ContractStatusStr = "";
                            if (subItem.ContractStatus == 0)
                            {
                                ContractStatusStr = "草稿";
                            }
                            else if (subItem.ContractStatus == 1)
                            {
                                ContractStatusStr = "提交审核";
                            }
                            else if (subItem.ContractStatus == 2)
                            {
                                ContractStatusStr = "审核通过";
                            }
                            else if (subItem.ContractStatus == 3)
                            {
                                ContractStatusStr = "驳回";
                            }
                            else if (subItem.ContractStatus == 4)
                            {
                                ContractStatusStr = "取消";
                            }
                            subItem.ContractStatusStr = ContractStatusStr;
                        }
                    }

                    var achievementList = achList.Where(x => x.OrderId == item.OrderId).ToList();
                    if (achievementList.Any())
                    {
                        item.CommissionMoney = achievementList.Sum(x => x.GiveOutMoney);
                        item.YFCommission = achievementList.Sum(x => x.PushMoney);
                    }
                    var tempStu = stuList?.FirstOrDefault(qitem => qitem.OrderId == item.OrderId);
                    item.CreateType = tempStu?.CreateType ?? StuCreateTypeEnum.EmployeeInput;
                    item.StuSourceIdName = tempStu?.StuSourceIdName ?? "";
                }
            }
            return orderList;
        }

        /// <summary>
        /// 获取留学就业订单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetStudyOrderPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Order_ViewModel demodel)
        {
            //获取订单列表
            var orderList = orderRepository.GetStudyOrderPageListRepository(pageIndex, pageSize, out rowsCount, demodel);
            if (orderList.Any())
            {
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                //获取备注列表
                var remarkList = order_RemarkRepository.GetOrderRemarkListRepository(new RB_Order_Remark_ViewModel() { QOrderIds = orderIds });
                //获取名单列表
                var guestList = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { OrderIds = orderIds });
                //获取合同列表
                var clist = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel() { Group_Id = demodel.Group_Id, OrderIds = orderIds, Status = -1 }).Where(x => x.Status != 4).ToList();
                foreach (var item in orderList)
                {
                    item.SaleRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 1).ToList();
                    item.TeacherRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 2).ToList();
                    item.RectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 3).ToList();
                    item.DirectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 4).ToList();
                    item.GuestList = guestList.Where(x => x.OrderId == item.OrderId).ToList();
                    item.ContractList = clist.Where(x => x.OrderId == item.OrderId).ToList();
                    var ZList = item.GuestList.Where(x => !item.ContractList.Select(z => z.GuestId).Contains(x.Id)).ToList();
                    if (ZList.Any() && item.ContractList.Any())
                    {
                        foreach (var qitem in ZList)
                        {
                            item.ContractList.Add(new RB_Education_Contract_ViewModel()
                            {
                                Id = 0,
                                StudentName = qitem.GuestName,
                                ContractNo = "",
                                GuestId = qitem.Id,
                                Status = 0
                            });
                        }
                    }
                }
            }
            return orderList;
        }

        /// <summary>
        /// 获取我的留学就业订单统计
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetStudyOrderStatisticsModule(RB_Order_ViewModel demodel)
        {
            return orderRepository.GetStudyOrderStatisticsRepository(demodel);
        }

        /// <summary>
        /// 获取我的订单统计
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetMyOrderStatisticsModule(RB_Order_ViewModel demodel)
        {
            return orderRepository.GetMyOrderStatisticsRepository(demodel);
        }

        /// <summary>
        /// 修改订单关联人员
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="helpEnterId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetOrderHelpEnterId(int orderId, int helpEnterId, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return "订单不存在"; }
            if (orderModel.OrderState == OrderStateEnum.Cancel) { return "订单已取消，无法修改"; }
            if (orderModel.HelpEnterId == helpEnterId) { return ""; }
            string OldName = "无", NewName = "无";
            if (orderModel.HelpEnterId > 0)
            {
                OldName = accountRepository.GetEmployeeInfo(orderModel.HelpEnterId)?.EmployeeName ?? "";
            }
            if (helpEnterId > 0)
            {
                var teacherModel = accountRepository.GetEmployeeInfo(helpEnterId);
                if (teacherModel.AccountType != Common.Enum.User.AccountTypeEnum.Teacher) { return "所选账号不是教师端，无法关联"; }
                NewName = teacherModel?.EmployeeName ?? "";
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order.HelpEnterId),helpEnterId}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //写入日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"修改订单关联教师 由【{OldName}】修改为【{NewName}】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }
        #endregion

        #region 订单操作
        /// <summary>
        /// 财务 更新订单实收，退款
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="income"></param>
        /// <param name="platformTax"></param>
        /// <param name="refund"></param>
        /// <param name="empModel"></param>
        /// <returns></returns>
        public bool UpdateEduOrderIncome(int orderId, decimal income, decimal platformTax, decimal refund, Employee_ViewModel empModel)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            if (orderModel.Income == income && orderModel.Refund == refund) { return true; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            string LogContent;
            if (income >= 0)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.Income), income);
                keyValues.Add(nameof(RB_Order_ViewModel.PlatformTax), platformTax);
                LogContent = $"，更新订单实收【{income}】平台税金【{platformTax}】";
            }
            else if (refund >= 0)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.Refund), refund);
                LogContent = $"，更新退款【{refund}】";
            }
            else { return false; }
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper()
                {
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                     FiledValue=orderId,
                     OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //写入日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = empModel.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = empModel.Group_Id,
                    LogContent = $"【{empModel.EmployeeName}({empModel.Id})】单据审核通过{LogContent}",
                    School_Id = empModel.School_Id,
                    SourceId = orderId
                });
                //if (orderModel.CommissionReType == 2 && orderModel.CustomerId > 0) {
                //    //订单帐平之后 返佣
                //    var newOrderModel = orderRepository.GetEntity(orderId);
                //    if (newOrderModel.PreferPrice == (newOrderModel.Income - newOrderModel.Refund + newOrderModel.PlatformTax + newOrderModel.DiscountMoney)) {
                //        //帐平了
                //        var customerModel = customerRepository.GetEntity(orderModel.CustomerId);
                //        //获取订单的返佣列表
                //        var list = customer_BalanceDetailRepository.GetCustomerBalanceDetailListRepository(new RB_Customer_BalanceDetail_ViewModel() { Group_Id = newOrderModel.Group_Id, OrderId = newOrderModel.OrderId, BalanceType = 1, BalanceState = 2 });
                //        if (list.Any())
                //        {
                //            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() { };
                //            foreach (var item in list)
                //            {
                //                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                //                    { nameof(RB_Customer_BalanceDetail_ViewModel.GiveOutMoney), item.Money},
                //                    { nameof(RB_Customer_BalanceDetail_ViewModel.BalanceState), 1}
                //                };
                //                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                //                    new WhereHelper(){
                //                         FiledName = nameof(RB_Customer_BalanceDetail_ViewModel.Id),
                //                          FiledValue = item.Id,
                //                           OperatorEnum =OperatorEnum.Equal
                //                    }
                //                };
                //                bool f = customer_BalanceDetailRepository.Update(keyValues1, wheres1);
                //                if (f)
                //                {
                //                    if (item.RebateType == 1)
                //                    {
                //                        keyValues2.Add(nameof(RB_Customer_Extend.TotalCommission), customerModel.TotalCommission + item.Money);
                //                        keyValues2.Add(nameof(RB_Customer_Extend.CommissionWithdrawal), customerModel.CommissionWithdrawal + item.Money);
                //                    }
                //                    else if (item.RebateType == 2)
                //                    {
                //                        keyValues2.Add(nameof(RB_Customer_Extend.Client_Balance), customerModel.Client_Balance + item.Money);
                //                    }
                //                }
                //            }
                //            //更新同行的可提现金额
                //            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                //                new WhereHelper(){
                //                        FiledName = nameof(RB_Customer_Extend.CustomerId),
                //                        FiledValue = customerModel.CustomerId,
                //                        OperatorEnum =OperatorEnum.Equal
                //                }
                //            };
                //            customerRepository.Update(keyValues2, wheres2);
                //        }
                //    }
                //}
            }
            return flag;
        }
        #endregion

        #region 财务统计

        /// <summary>
        /// 获取订单完成情况一览分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_Contract_ViewModel> GetOrderStudentClassHoursPageList(int pageIndex, int pageSize, out long count, RB_Education_Contract_ViewModel dmodel)
        {
            string datebaseStr = Config.ReadConfigKey("FinanceDateBase");//财务数据库
            var list = education_ContractRepository.GetContractPageListForFinance(pageIndex, pageSize, out count, dmodel, datebaseStr);
            if (list.Any())
            {
                string orderIds = string.Join(",", list.Select(x => x.OrderId).Distinct());
                string guestIds = string.Join(",", list.Select(x => x.GuestId).Distinct());
                //查询所有的财务单据
                var flist = financeRepository.GetListSingle(new Model.ViewModel.Finance.RB_Finance_Extend() { RB_Group_Id = dmodel.Group_Id, FinanceType = 2, IsSelectNormal = 1, OrderIdStr = orderIds, GuestIdStr = guestIds });
                if (flist.Any())
                {
                    string frIds = string.Join(",", flist.Select(x => x.FrID));
                    //查询单据明细
                    var fdlist = financeDetailRepository.GetList(new Model.ViewModel.Finance.RB_FinanceDetail_Extend() { GroupId = dmodel.Group_Id, FrIds = frIds });
                    //查询单据交易账户
                    var TradeList = tradeWayRepository.GetList(new Model.ViewModel.Finance.RB_TradeWay_Extend() { FrIdStr = frIds });
                    //获取币种列表
                    var CurrencyList = currencyRepository.GetList(new Model.Entity.Finance.RB_Currency() { RB_Group_Id = dmodel.Group_Id });
                    //查询四大账户
                    var BankList = new List<Model.ViewModel.Finance.RB_BackAccount_Extend>();
                    if (TradeList.Where(x => x.Type == Common.Enum.Finance.BranchAccountEnum.Bank).Any())
                    {
                        BankList = backAccountRepository.GetList(new Model.ViewModel.Finance.RB_BackAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == Common.Enum.Finance.BranchAccountEnum.Bank).Select(x => x.AccountId ?? 0).Distinct()) });
                    }
                    var CashPoolList = new List<Model.ViewModel.Finance.RB_CashPoolAccount_Extend>();
                    if (TradeList.Where(x => x.Type == Common.Enum.Finance.BranchAccountEnum.CashPool).Any())
                    {
                        CashPoolList = cashPoolAccountRepository.GetList(new Model.ViewModel.Finance.RB_CashPoolAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == Common.Enum.Finance.BranchAccountEnum.CashPool).Select(x => x.AccountId ?? 0).Distinct()) });
                    }
                    var PlatformList = new List<Model.ViewModel.Finance.RB_PlatformAccount_Extend>();
                    if (TradeList.Where(x => x.Type == Common.Enum.Finance.BranchAccountEnum.Platform).Any())
                    {
                        PlatformList = platformAccountRepository.GetList(new Model.ViewModel.Finance.RB_PlatformAccount_Extend() { AccountIdStr = string.Join(",", TradeList.Where(x => x.Type == Common.Enum.Finance.BranchAccountEnum.Platform).Select(x => x.AccountId ?? 0).Distinct()) });
                    }
                    List<Model.ViewModel.Finance.RB_TradeWay_Extend> tlist = new List<Model.ViewModel.Finance.RB_TradeWay_Extend>();
                    foreach (var TradeModel in TradeList)
                    {
                        Model.ViewModel.Finance.RB_TradeWay_Extend accountInFo = TradeModel.RefMapperTo<Model.ViewModel.Finance.RB_TradeWay_Extend>();
                        accountInFo.CurrencyName = CurrencyList.Where(x => x.ID == TradeModel.CurrencyId).FirstOrDefault()?.Name ?? "";
                        if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.Bank)
                        {
                            var bank = BankList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                            if (bank != null)
                            {
                                accountInFo.Alias = bank.Alias;
                                accountInFo.BankNo = bank.BackNo;
                                accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.Bank;
                                accountInFo.AccountTypeId = bank.TypeId;
                            }
                        }
                        else if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.CashPool)
                        {
                            var pool = CashPoolList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                            if (pool != null)
                            {
                                accountInFo.Alias = pool.Alias;
                                accountInFo.BankNo = "";
                                accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.CashPool;
                                accountInFo.AccountTypeId = pool.TypeId;
                            }
                        }
                        else if (TradeModel.Type == Common.Enum.Finance.BranchAccountEnum.Platform)
                        {
                            var platform = PlatformList.Where(x => x.ID == TradeModel.AccountId).FirstOrDefault();
                            if (platform != null)
                            {
                                accountInFo.Alias = platform.Alias;
                                accountInFo.BankNo = platform.PlatformNo;
                                accountInFo.Type = Common.Enum.Finance.BranchAccountEnum.Platform;
                                accountInFo.AccountTypeId = platform.TypeId;
                            }
                        }
                        tlist.Add(accountInFo);
                    }
                    foreach (var item in flist)
                    {
                        item.detailList = fdlist.Where(x => x.FinanceId == item.FrID).ToList();
                        item.BankList = tlist.Where(x => x.FinanceId == item.FrID).ToList();
                    }
                }
                //查询所有学生的已上课时间
                var stuTimeList = class_CheckRepository.GetClassGuestStudentTimeList(dmodel.Group_Id, guestIds, dmodel.XFStartTime, dmodel.XFEndTime);
                //查询基础课时时长
                //var configModel = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = dmodel.Group_Id });
                //用户信息
                var userIds = string.Join(",", list.Select(x => x.CreateBy).Distinct());
                var alist = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel() { QIds = userIds });

                List<RB_Order_ViewModel> sourceTargetList = new List<RB_Order_ViewModel>();
                List<int> idList = new List<int>();
                var sourceOrderIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Select(x => x.SourceOrderId)));
                if (sourceOrderIdList != null && sourceOrderIdList.Count > 0)
                {
                    idList.AddRange(sourceOrderIdList);
                }
                var targetOrderIdList = Common.ConvertHelper.StringToList(string.Join(",", list.Select(x => x.TargetOrderId)));
                if (targetOrderIdList != null && targetOrderIdList.Count > 0)
                {
                    idList.AddRange(targetOrderIdList);
                }
                if (idList != null && idList.Count > 0)
                {
                    string ids = string.Join(",", idList);
                    sourceTargetList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel { QOrderIds = ids });
                }

                foreach (var item in list)
                {
                    if (item.SourceOrderId > 0)
                    {
                        item.SourceClassName = sourceTargetList?.Where(qitem => qitem.OrderId == item.SourceOrderId)?.FirstOrDefault()?.ClassName;
                    }
                    if (item.TargetOrderId > 0)
                    {
                        item.TargetClassName = sourceTargetList?.Where(qitem => qitem.OrderId == item.TargetOrderId)?.FirstOrDefault()?.ClassName;
                    }

                    #region 财务单据
                    item.FinanceList = flist.Where(x => x.GuestId == item.GuestId).ToList();
                    item.Income = item.FinanceList.Where(x => x.Type == Common.Enum.Finance.WFTempLateClassEnum.IN && x.Is_Cashier == 1).Sum(x => (x.Money ?? 0) + (x.Fee ?? 0));//出纳审核算有效金额
                    item.Expend = item.FinanceList.Where(x => x.Type == Common.Enum.Finance.WFTempLateClassEnum.OUT).Sum(x => (x.Money ?? 0) + (x.Fee ?? 0));//制单就算
                    #endregion
                    var stuModel = stuTimeList.Where(x => x.OrderGuestId == item.GuestId).FirstOrDefault();
                    //if (configModel == null || configModel.BasicMinutes <= 0)
                    //{
                    //    item.UseClassHours = 0;
                    //}
                    //else
                    //{
                    //    item.UseClassHours = (int)Math.Ceiling(Convert.ToDecimal(stuModel?.MinutesNum ?? 0) / configModel.BasicMinutes);// 已上课时   （暂时向上取整）
                    //}
                    item.UseClassHours = (stuModel?.CurrentDeductionHours ?? 0);
                    item.Unit_Price = 0;
                    item.UseCourseFee = 0;
                    if (item.TotalClassHours > 0)
                    {
                        if (item.TotalDiscountMoney > 0)
                        {
                            item.Unit_Price = Math.Round((item.TotalCourseFee - (item.TotalDiscountMoney / item.TotalSub) * item.TotalCourseFee) / item.TotalClassHours, 6, MidpointRounding.AwayFromZero);//根据合同计算(包含优惠， 需减去课件费等)
                            item.UseCourseFee = Math.Round((Convert.ToDecimal(item.UseClassHours) / item.TotalClassHours) * (item.TotalCourseFee - (item.TotalDiscountMoney / item.TotalSub) * item.TotalCourseFee), 6, MidpointRounding.AwayFromZero);
                        }
                        else
                        {
                            item.Unit_Price = Math.Round(item.TotalCourseFee / item.TotalClassHours, 6, MidpointRounding.AwayFromZero);//根据合同计算(包含优惠， 需减去课件费等)
                            item.UseCourseFee = Math.Round((Convert.ToDecimal(item.UseClassHours) / item.TotalClassHours) * item.TotalCourseFee, 6, MidpointRounding.AwayFromZero);
                        }
                    }
                    item.UseBookFee = item.TotalBookFee;
                    item.UseCoursewareFee = item.TotalClassFee;
                    if (item.TotalDiscountMoney > 0)
                    {
                        item.UseBookFee = Math.Round(item.TotalBookFee - (item.TotalDiscountMoney / item.TotalSub) * item.TotalBookFee, 6, MidpointRounding.AwayFromZero);//(优惠比例)
                        item.UseCoursewareFee = Math.Round(item.TotalClassFee - (item.TotalDiscountMoney / item.TotalSub) * item.TotalClassFee, 6, MidpointRounding.AwayFromZero);//(优惠比例)
                    }
                    //用户信息
                    var amodel = alist.Where(x => x.Id == item.CreateBy).FirstOrDefault();
                    item.CreateByName = amodel?.AccountName ?? "";
                    item.CreateByPhoto = amodel?.UserIcon ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改合同协调
        /// </summary>
        /// <param name="dmodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetContractAdjustPrice(RB_Education_ContractAdjust_ViewModel dmodel, UserInfo userInfo)
        {
            var list = education_ContractAdjustRepository.GetList(new RB_Education_ContractAdjust_ViewModel() { Group_Id = userInfo.Group_Id, ContractId = dmodel.ContractId });
            if (list.Any())
            {
                var model = list.FirstOrDefault();
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Education_ContractAdjust_ViewModel.AdjustPrice),dmodel.AdjustPrice},
                    { nameof(RB_Education_ContractAdjust_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_Education_ContractAdjust_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                         FiledName=nameof(RB_Education_ContractAdjust_ViewModel.Id),
                         FiledValue= model.Id,
                         OperatorEnum=OperatorEnum.Equal
                    }
                };
                return education_ContractAdjustRepository.Update(keyValues, wheres);
            }
            else
            {
                return education_ContractAdjustRepository.Insert(new RB_Education_ContractAdjust()
                {
                    Id = 0,
                    ContractId = dmodel.ContractId,
                    AdjustPrice = dmodel.AdjustPrice,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    UpdateBy = userInfo.Id,
                    UpdateTime = DateTime.Now
                }) > 0;
            }
        }

        /// <summary>
        /// 更新学生的有效课时
        /// </summary>
        /// <param name="guestId"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public bool UpdateStudentValidClassHours(int guestId, decimal money)
        {
            var gmodel = order_GuestRepository.GetEntity(guestId);
            if (gmodel == null) { return false; }
            var cmodel = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel() { Group_Id = gmodel.Group_Id, GuestId = gmodel.Id, Status = -1 }).Where(x => x.Status != 4).FirstOrDefault();
            if (cmodel != null)
            {
                //有合同
                cmodel.Income = money >= 0 ? money : 0;
                cmodel.Unit_Price = 0;
                if (cmodel.TotalClassHours > 0)
                {
                    if (cmodel.TotalDiscountMoney > 0)
                    {
                        cmodel.Unit_Price = Math.Round((cmodel.TotalCourseFee - (cmodel.TotalDiscountMoney / cmodel.TotalSub) * cmodel.TotalCourseFee) / cmodel.TotalClassHours, 6, MidpointRounding.AwayFromZero);//根据合同计算
                    }
                    else
                    {
                        cmodel.Unit_Price = Math.Round(cmodel.TotalCourseFee / cmodel.TotalClassHours, 6, MidpointRounding.AwayFromZero);//根据合同计算
                    }
                }
                decimal validClassHours = cmodel.Unit_Price > 0 ? Math.Round(cmodel.Income / cmodel.Unit_Price, 2, MidpointRounding.AwayFromZero) : 0;

                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_Guest.ValidClassHours),validClassHours}
                };
                //HK2021-07-19新增【有效课时大于完成课时修改学员状态为正常】
                string LogContent = "";
                if (gmodel.CompleteHours <= validClassHours)
                {
                    keyValues.Add(nameof(RB_Order_Guest.GuestState), (int)GuestStateEnum.Normal);
                    keyValues.Add(nameof(RB_Order_Guest.DropOutRemark), "有效课时大于完成课时,恢复学员状态!");
                    LogContent = gmodel.GuestName + "有效课时大于完成课时,系统恢复学员状态!";
                }
                if (!string.IsNullOrEmpty(LogContent))
                {
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 3,
                        CreateBy = gmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = gmodel.Group_Id,
                        LogContent = LogContent,
                        School_Id = gmodel.School_Id,
                        SourceId = gmodel.Id
                    });
                }
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Order_Guest.Id),
                        FiledValue=guestId,
                        OperatorEnum= OperatorEnum.Equal
                    }
                };
                order_GuestRepository.Update(keyValues, wheres);
                //如果有效课时与总课时相等代表款已收完，更新佣金为可发放状态
                if (gmodel.TotalHours <= validClassHours)
                {
                    var studentMapping = student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel() {
                        GuestId = guestId
                    });
                    if (studentMapping.Any()) {
                        UpdateReturnMoneyStatus(studentMapping.First().Student_Id, gmodel.OrderId);
                    }
                    
                }
            }
            return true;
        }

        /// <summary>
        /// 更新返佣状态不可返佣-->待结算
        /// </summary>
        /// <param name="stuId"></param>
        /// <param name="orderId"></param>
        private void UpdateReturnMoneyStatus(int stuId,int orderId)
        {
            var model = returnComissionRepository.GetModelByOrderIdStuId(orderId, stuId);
            if (model != null && model.Status == -1)
            {
                var userModel = userReturnComissionRepository.GetModelBySourceId((int)model.OrderSourceType, model.OrderSourceId, model.CommissionType);
                if (userModel != null)
                {
                    userModel.UnSettlementMoney += model.CommissionMoeny;
                    Dictionary<string, object> userKeyValues = new Dictionary<string, object>()
                    {
                        { nameof(RB_User_ReturnComission_ViewModel.UnSettlementMoney),userModel.UnSettlementMoney}
                    };
                    List<WhereHelper> userWheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_User_ReturnComission_ViewModel.UserType),
                        FiledValue=model.OrderSourceType,
                        OperatorEnum= OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_User_ReturnComission_ViewModel.UserId),
                        FiledValue=model.OrderSourceId,
                        OperatorEnum= OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_User_ReturnComission_ViewModel.CommissionType),
                        FiledValue=model.CommissionType,
                        OperatorEnum= OperatorEnum.Equal
                    }
                };
                    userReturnComissionRepository.Update(userKeyValues, userWheres);
                }
                else {
                    userModel = new RB_User_ReturnComission_ViewModel()
                    {
                        UserId = model.OrderSourceId,
                        UserType = model.OrderSourceType,
                        CommissionType = model.CommissionType,
                        CanCashOutMoney = 0,
                        CashOutMoney = 0,
                        GroupId = model.GroupId,
                        SttlementMoney = 0,
                        UnSettlementMoney = model.CommissionMoeny,
                        Id = 0
                    };
                    userReturnComissionRepository.Insert(userModel);
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_ReturnComission.Status),0}
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Order_ReturnComission.StuId),
                        FiledValue=stuId,
                        OperatorEnum= OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Order_ReturnComission.OrderId),
                        FiledValue=orderId,
                        OperatorEnum= OperatorEnum.Equal
                    }
                };
                returnComissionRepository.Update(keyValues, wheres);
            }
            
        }

        /// <summary>
        /// 初始化所有学生的课时
        /// </summary>
        /// <returns></returns>
        public bool UpdateALLStudentValidClassHours()
        {
            RB_Education_Contract_ViewModel dmodel = new RB_Education_Contract_ViewModel() { Group_Id = 100000 };
            string datebaseStr = Config.ReadConfigKey("FinanceDateBase");//财务数据库
            var list = education_ContractRepository.GetContractPageListForFinance(1, 10000, out long count, dmodel, datebaseStr);
            if (list.Any())
            {
                string orderIds = string.Join(",", list.Select(x => x.OrderId).Distinct());
                string guestIds = string.Join(",", list.Select(x => x.GuestId).Distinct());
                //查询所有的财务单据
                var flist = financeRepository.GetListSingle(new Model.ViewModel.Finance.RB_Finance_Extend() { RB_Group_Id = dmodel.Group_Id, FinanceType = 2, IsSelectNormal = 1, OrderIdStr = orderIds, GuestIdStr = guestIds });
                if (flist.Any())
                {
                    string frIds = string.Join(",", flist.Select(x => x.FrID));
                    //查询单据明细
                    var fdlist = financeDetailRepository.GetList(new Model.ViewModel.Finance.RB_FinanceDetail_Extend() { GroupId = dmodel.Group_Id, FrIds = frIds });
                }
                foreach (var item in list)
                {
                    #region 财务单据
                    item.FinanceList = flist.Where(x => x.GuestId == item.GuestId).ToList();
                    item.Income = item.FinanceList.Where(x => x.Type == Common.Enum.Finance.WFTempLateClassEnum.IN && x.Is_Cashier == 1).Sum(x => (x.Money ?? 0) + (x.Fee ?? 0));//出纳审核算有效金额
                    item.Expend = item.FinanceList.Where(x => x.Type == Common.Enum.Finance.WFTempLateClassEnum.OUT).Sum(x => (x.Money ?? 0) + (x.Fee ?? 0));//制单就算
                    #endregion
                    item.Unit_Price = 0;
                    if (item.TotalClassHours > 0)
                    {
                        if (item.TotalDiscountMoney > 0)
                        {
                            item.Unit_Price = Math.Round((item.TotalCourseFee - (item.TotalDiscountMoney / item.TotalSub) * item.TotalCourseFee) / item.TotalClassHours, 6, MidpointRounding.AwayFromZero);//根据合同计算(包含优惠， 需减去课件费等)
                        }
                        else
                        {
                            item.Unit_Price = Math.Round(item.TotalCourseFee / item.TotalClassHours, 6, MidpointRounding.AwayFromZero);//根据合同计算(包含优惠， 需减去课件费等)
                        }
                    }

                    decimal Income = item.Income - item.Expend;
                    Income = Income >= 0 ? Income : 0;
                    decimal validClassHours = item.Unit_Price > 0 ? Math.Round(Income / item.Unit_Price, 2, MidpointRounding.AwayFromZero) : 0;
                    //更新学生的有效课时
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Order_Guest.ValidClassHours),validClassHours}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Order_Guest.Id),
                              FiledValue=item.GuestId,
                            OperatorEnum= OperatorEnum.Equal
                        }
                    };
                    order_GuestRepository.Update(keyValues, wheres);
                }
            }
            return true;
        }
        #endregion

        #region 个人中心
        /// <summary>
        /// 获取我的未完成的订单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetOrderNoComplete(RB_Order_ViewModel demodel)
        {
            return orderRepository.GetOrderNoComplete(demodel);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="orderIds"></param>
        /// <returns></returns>
        public List<RB_Order_Guest_ViewModel> GetOrderGuestListByEnterID(RB_Order_Guest_ViewModel demodel)
        {
            return order_GuestRepository.GetOrderGuestListByEnterID(demodel);
        }
        #endregion

        #region 更新甲鹤小程序对应的班级招生人数
        /// <summary>
        /// 下单更新甲鹤小程序规格对应的班级人数
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool UpdateClassInventoryNum(RB_Order_ViewModel demodel)
        {
            bool flag = false;
            var courseModel = courseRepository.GetEntity(demodel.CourseId).RefMapperTo<RB_Course_ViewModel>();
            if (courseModel != null && courseModel.MallGoodsId > 0)
            {
                var svlist = goods_SpecificationValueRepository.GetList(new Edu.Model.ViewModel.Mall.RB_Goods_SpecificationValue_Extend() { GoodsId = courseModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });
                var splist = goods_SpecificationPriceRepository.GetList(new Edu.Model.ViewModel.Mall.RB_Goods_SpecificationPrice_Extend() { GoodsId = courseModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });
                if (svlist != null && svlist.Any(x => x.ClassId == demodel.ClassId))
                {
                    var svModel = svlist.Where(x => x.ClassId == demodel.ClassId).FirstOrDefault();
                    if (svModel != null && svModel.Id > 0)
                    {
                        var spModel = splist.Where(x => x.SpecificationSort == svModel.Sort.ToString()).FirstOrDefault();
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(Edu.Model.ViewModel.Mall.RB_Goods_SpecificationPrice_Extend.InventoryNum),spModel.InventoryNum - demodel.GuestNum}
                         };
                        List<WhereHelper> wheres = new List<WhereHelper>()
                        {
                            new WhereHelper(){
                                 FiledName=nameof(Edu.Model.ViewModel.Mall.RB_Goods_SpecificationPrice_Extend.Id),
                                  FiledValue=spModel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                       };
                        flag = goods_SpecificationPriceRepository.Update(keyValues, wheres);
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 取消更新甲鹤小程序规格对应的班级人数
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool UpdateCancelClassOrder(RB_Order demodel)
        {
            bool flag = false;
            var courseModel = courseRepository.GetEntity(demodel.CourseId).RefMapperTo<RB_Course_ViewModel>();
            if (courseModel != null && courseModel.MallGoodsId > 0)
            {
                var svlist = goods_SpecificationValueRepository.GetList(new Edu.Model.ViewModel.Mall.RB_Goods_SpecificationValue_Extend() { GoodsId = courseModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });
                var splist = goods_SpecificationPriceRepository.GetList(new Edu.Model.ViewModel.Mall.RB_Goods_SpecificationPrice_Extend() { GoodsId = courseModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });
                if (svlist != null && svlist.Any(x => x.ClassId == demodel.ClassId))
                {
                    var svModel = svlist.Where(x => x.ClassId == demodel.ClassId).FirstOrDefault();
                    if (svModel != null && svModel.Id > 0)
                    {
                        var spModel = splist.Where(x => x.SpecificationSort == svModel.Sort.ToString()).FirstOrDefault();
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(Edu.Model.ViewModel.Mall.RB_Goods_SpecificationPrice_Extend.InventoryNum),spModel.InventoryNum + demodel.GuestNum}
                         };
                        List<WhereHelper> wheres = new List<WhereHelper>()
                        {
                            new WhereHelper(){
                                 FiledName=nameof(Edu.Model.ViewModel.Mall.RB_Goods_SpecificationPrice_Extend.Id),
                                  FiledValue=spModel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                       };
                        flag = goods_SpecificationPriceRepository.Update(keyValues, wheres);
                    }
                }
            }
            return flag;
        }



        /// <summary>
        /// 日语培训下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>

        public virtual bool SetBatchClassOrder(List<RB_Order_ViewModel> list, UserInfo userInfo, bool isEditOrder)
        {
            bool flag = false;
            foreach (var demodel in list)
            {
                //查询班级信息
                var classModel = classRepository.GetEntity(demodel.ClassId);
                if (classModel == null)
                {
                    flag = false;

                    return flag;
                }
                if (demodel.JoinType == OrderJoinTypeEnum.Normal || demodel.JoinType == OrderJoinTypeEnum.RenewOrder)
                {
                    demodel.CourseId = classModel.CouseId;
                }
                //课程信息
                var courseModel = courseRepository.GetEntity(demodel.CourseId);

                #region 计算订单优惠信息
                //获取课程优惠
                var coursePreferentialList = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
                {
                    CourseId = demodel.CourseId
                });
                //课程优惠信息
                decimal disMoney = 0;//课程最大优惠金额
                decimal coursePrice = courseModel.SellPrice;//课程最低单价
                var coursePreferentialModel = new RB_Course_Preferential_Extend();
                if (coursePreferentialList != null && coursePreferentialList.Count > 0)
                {
                    if (demodel.GuestNum == 1)
                    {
                        coursePreferentialModel = coursePreferentialList?.Where(qitem => qitem.PriceDiscountType == CoursePriceDiscountEnum.SingleJoin)?.FirstOrDefault();
                    }
                    if (demodel.GuestNum >= 2)
                    {
                        coursePreferentialModel = coursePreferentialList?.Where(qitem => qitem.PriceDiscountType == CoursePriceDiscountEnum.DoubleJoin)?.FirstOrDefault();
                    }
                    var saleCommissionType = coursePreferentialModel?.SaleCommissionType ?? 0;
                    if (saleCommissionType == 0)
                    {
                        var tempMoney = (courseModel?.SellPrice ?? 0) * (coursePreferentialModel?.SaleCommissionMoney ?? 0);
                        disMoney = tempMoney / Convert.ToDecimal(100);
                    }
                    else
                    {
                        disMoney = coursePreferentialModel?.SaleCommissionMoney ?? 0;
                    }
                    var b2bCommissionType = coursePreferentialModel?.B2BCommissionType ?? 0;
                    if (b2bCommissionType == 0)
                    {
                        var tempMoney = (courseModel?.SellPrice ?? 0) * (coursePreferentialModel?.B2BCommissionMoney ?? 0);
                        disMoney += tempMoney / Convert.ToDecimal(100);
                    }
                    else
                    {
                        disMoney = coursePreferentialModel?.B2BCommissionMoney ?? 0;
                    }

                    var priceCommissionType = coursePreferentialModel?.PriceType ?? 0;
                    if (priceCommissionType == 0)
                    {
                        coursePrice = coursePrice * (100 - (coursePreferentialModel?.PriceMoney ?? 0)) / 100;
                    }
                    else
                    {
                        coursePrice -= (coursePreferentialModel?.PriceMoney ?? 0);
                    }
                    #region 记录提成信息
                    if (coursePreferentialModel == null)
                    {
                        coursePreferentialModel = coursePreferentialList.FirstOrDefault();
                    }
                    demodel.CommissionType = coursePreferentialModel?.SaleCommissionType ?? 0;
                    demodel.CommissionRate = coursePreferentialModel?.SaleCommissionMoney ?? 0;
                    demodel.CommissionTypeTH = coursePreferentialModel?.B2BCommissionType ?? 0;
                    demodel.CommissionRateTH = coursePreferentialModel?.B2BCommissionMoney ?? 0;
                    if (coursePreferentialModel != null)
                    {
                        demodel.CommissionRemark = "使用优惠Id:" + coursePreferentialModel.Id + " 返佣类型:" + demodel.CommissionType + " 返佣比例/金额:" + demodel.CommissionRate + " 同行返佣类型:" + demodel.CommissionTypeTH + " 同行返佣比例/金额:" + demodel.CommissionRateTH;
                    }
                    #endregion
                }
                if (demodel.IsLessPrice == 1 && demodel.LessPrice > 0)
                {
                    if (coursePreferentialList != null && coursePreferentialList.Count > 0)
                    {
                        if (demodel.LessPrice > disMoney)
                        {

                            return flag;
                        }
                    }
                    //else
                    //{
                    //    message = "此课程未配置【销售提成】信息，请通知OP在课程里面添加优惠信息!";
                    //    return flag;
                    //}
                }
                #endregion
                if (demodel.OrderSource == OrderSourceEnum.EduClient || demodel.OrderSource == OrderSourceEnum.Client)
                {
                    if (demodel.OrderSource == OrderSourceEnum.EduClient)
                    {
                        demodel.GeneralOccupation = "";
                    }
                    else if (demodel.OrderSource == OrderSourceEnum.Client)
                    {
                        demodel.EduOccupation = "";
                    }
                }
                else
                {
                    demodel.EduOccupation = "";
                    demodel.GeneralOccupation = "";
                }
                if (demodel.IsLessPrice == 0)
                {
                    demodel.LessPrice = 0;
                }
                var orderModel = new RB_Order();
                if (demodel.OrderId > 0)
                {
                    orderModel = orderRepository.GetEntity(demodel.OrderId);
                }
                if (demodel.OrderId > 0)
                {
                    int BNum = orderRepository.GetClassOrderPeopleNumRepository(demodel.ClassId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
                    if (BNum + demodel.GuestNum - orderModel.GuestNum > classModel.ClassPersion)
                    {
                        flag = false;
                        // message = "人数报超" + (classModel.ClassPersion - (BNum + demodel.GuestNum - orderModel.GuestNum));
                        return flag;
                    }
                }
                else
                {
                    int BNum = orderRepository.GetClassOrderPeopleNumRepository(demodel.ClassId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
                    if (BNum + demodel.GuestNum > classModel.ClassPersion)
                    {
                        flag = false;
                        //  message = "人数报超" + (classModel.ClassPersion - (BNum + demodel.GuestNum));
                        return flag;
                    }
                }
                //没有总经理修改订单权限
                if (!isEditOrder)
                {
                    if (demodel.Unit_Price < coursePrice)
                    {
                        flag = false;
                        //  message = "成交单价不能小于最低价格";
                        return flag;
                    }
                    if (demodel.JoinType == OrderJoinTypeEnum.InsertClass)
                    {
                        var newPreferPrice = Math.Round(coursePrice / courseModel.ClassHours * (courseModel.ClassHours - demodel.StartClassHours) * demodel.GuestNum, 2);
                        if (demodel.PreferPrice != (newPreferPrice - demodel.LessPrice))
                        {
                            flag = false;
                            //   message = "应收总额不正确";
                            return flag;
                        }
                    }
                    else if (demodel.JoinType == OrderJoinTypeEnum.TransOrder || demodel.JoinType == OrderJoinTypeEnum.SplitOrder)
                    {
                        //不验证应收
                    }
                    else
                    {
                        if (demodel.PreferPrice != (demodel.Unit_Price * demodel.GuestNum - demodel.LessPrice))
                        {
                            flag = false;
                            // message = "应收总额不正确";
                            return flag;
                        }
                    }
                }
                //日志信息
                string LogContent = "";
                //销售备注
                string SaleRemark = "";

                if (demodel.JoinType == OrderJoinTypeEnum.InsertClass)
                {
                    if (Convert.ToDateTime(Common.ConvertHelper.FormatTime(demodel.EffectTime)) < Convert.ToDateTime(Common.ConvertHelper.FormatTime(DateTime.Now)))
                    {
                        demodel.EffectStatus = 1;
                    }
                    else
                    {
                        demodel.EffectStatus = 0;
                    }
                }
                else
                {
                    demodel.EffectStatus = 1;
                    demodel.EffectTime = DateTime.Now;
                }
                if (classModel.ClassStatus == Common.Enum.Course.ClassStatusEnum.EndClass)
                {
                    flag = false;
                    //  message = "班级状态不正确";
                    return flag;
                }
                demodel.Class_Price = courseModel.SellPrice;
                int OrderId = orderRepository.Insert(demodel);
                demodel.OrderId = OrderId;
                flag = OrderId > 0;
                LogContent = "新增日语培训订单";
                //记录订单备注
                if (!string.IsNullOrEmpty(demodel.SaleRemark))
                {
                    SaleRemark = demodel.SaleRemark;
                }
                #region 更新甲鹤小程序规格对应的库存
                if (flag && demodel.JoinType != OrderJoinTypeEnum.RenewOrder)//续费订单不去更新规格库存
                {
                    System.Threading.Tasks.Task.Run(() => UpdateClassInventoryNum(demodel));
                }
                #endregion


                #region 写日志
                if (flag)
                {

                    var financeConfig = finance_ConfigRepository.GetList(new Edu.Model.ViewModel.Finance.RB_Finance_Config_ViewModel { Group_Id = demodel.Group_Id, Type = Common.Enum.Course.FinanceConfigTypeEnum.Tuition }).FirstOrDefault();
                    if (financeConfig == null)
                    {
                        financeConfig = new Edu.Model.ViewModel.Finance.RB_Finance_Config_ViewModel();
                    }

                    // var OriginalFee = Math.Round((Convert.ToDecimal(Config.SettlementRate) / 100) * (Convert.ToDecimal(payModel.amount.payer_total) / 100), 2, MidpointRounding.AwayFromZero);//手续费

                    #region 财务单据数据组装
                    var detailList = new List<object>
                    {
                        new
                        {
                            CostTypeId = financeConfig?.CostTypeId ?? 533,
                            Number = demodel.GuestNum,
                            OriginalMoney = Convert.ToDecimal(demodel.PreferPrice) ,
                            UnitPrice = Convert.ToDecimal(demodel.PreferPrice/demodel.GuestNum) ,
                            Remark = "甲鹤小程序用户下单自动生成财务单据"
                        }
                    };

                    var financeObj = new
                    {
                        IsPublic = 1,
                        BType = 1,//item.AccountType,
                        AccountId = financeConfig?.ClientID ?? 54,
                        WBMoney = Convert.ToDecimal(demodel.PreferPrice - demodel.PlatformTax),
                        TradeDate = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
                        AccountNumber = System.DateTime.Now.AddDays(-1).ToString("yyyyMMdd"),
                        TemplateId = financeConfig?.TempleteId ?? 139,
                        OrderSource = 17,
                        Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                        detailList,
                        OriginalFee = demodel.PlatformTax,
                        CreateBy = userInfo.Id,
                        RemitterName = demodel.GuestName,
                        RB_Branch_Id = userInfo.School_Id,
                        RB_Group_Id = userInfo.Group_Id,
                        RB_Depart_Id = userInfo.DeptId,
                        RB_CreateByName = userInfo.AccountName,
                        RB_DepartName = userInfo.DeptName,
                        RB_BranchName = userInfo.SchoolName,
                        RB_GroupName = userInfo.GroupName,
                        FinanceType = 2,
                        GuestId = 0,
                        OrderId,
                        TCIDList = demodel.ClassId > 0 ? new List<int>() { demodel.ClassId } : new List<int>(),
                    };
                    #endregion

                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign,
                    };
                    string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("IncomeFinanceApi"), JsonHelper.Serialize(resultInfo), "");
                    JObject parmsJob = JObject.Parse(apiResult);
                    string resultCode = parmsJob.GetStringValue("resultCode");
                    int frid = parmsJob.GetInt("data", 0);
                    if (resultCode == "1" && frid > 0)//新增记录
                    {

                    }
                    //销售备注
                    if (!string.IsNullOrEmpty(SaleRemark))
                    {
                        order_RemarkRepository.Insert(new RB_Order_Remark()
                        {
                            Id = 0,
                            Content = SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = demodel.OrderId,
                            Type = 1
                        });
                    }

                    //订单日志
                    if (!string.IsNullOrEmpty(LogContent))
                    {
                        changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                        {
                            Id = 0,
                            Type = 2,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            Group_Id = userInfo.Group_Id,
                            LogContent = LogContent,
                            School_Id = userInfo.School_Id,
                            SourceId = demodel.OrderId
                        });
                    }
                }
                #endregion

            }
            return flag;
        }


        /// <summary>
        /// 更新班级对应的商品库存
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public bool UpdateGoodsSpecification(List<int> classId)
        {
            bool flag = false;
            string classIds = string.Join(",", classId.Select(x => x));
            var classList = classRepository.GetClassAndCourseListRepository(new RB_Class_ViewModel { Q_ClassIds = classIds });
            var goodsSpecificationValueList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend { ClassIds = classIds });
            var goodsSpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (goodsSpecificationValueList != null && goodsSpecificationValueList.Any())
            {
                goodsSpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend { GoodsId = goodsSpecificationValueList.FirstOrDefault()?.GoodsId });
            }
            if (classList != null && classList.Any() && goodsSpecificationValueList != null && goodsSpecificationValueList.Any() && goodsSpecificationValueList != null && goodsSpecificationValueList.Any())
            {
                foreach (var item in classList)//查找班级对应的规格
                {
                    var valueModle = goodsSpecificationValueList.Where(x => x.ClassId == item.ClassId).FirstOrDefault();
                    if (valueModle != null && valueModle.Id > 0)
                    {
                        var priceModel = goodsSpecificationPriceList.Where(x => x.GoodsId == valueModle.GoodsId && x.SpecificationSort == (valueModle.Sort ?? 0).ToString()).FirstOrDefault();
                        if (priceModel != null && priceModel.Id > 0)
                        {
                            Dictionary<string, object> fileds = new Dictionary<string, object>()
                            {
                               { nameof(RB_Goods_SpecificationPrice_Extend.InventoryNum),item.ClassPersion-item.OrderStudentCount},
                            };
                            flag = goods_SpecificationPriceRepository.Update(fileds, new WhereHelper(nameof(RB_Goods_SpecificationPrice_Extend.Id), priceModel.Id));
                        }
                    }
                }
            }
            return flag;
        }


        #endregion
    }
}