using Edu.AOP.CustomerAttribute;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Finance;
using Edu.Model.ViewModel.Log;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Finance;
using Edu.Repository.Log;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 销售提成处理类
    /// </summary>
    public class SellCommissionModule
    {
        /// <summary>
        /// 销售提成规则
        /// </summary>
        private readonly RB_Sell_Commission_RuleRepository sell_Commission_RuleRepository = new RB_Sell_Commission_RuleRepository();
        /// <summary>
        /// 销售提成期数
        /// </summary>
        private readonly RB_Sell_Commission_PeriodsRepository sell_Commission_PeriodsRepository = new RB_Sell_Commission_PeriodsRepository();
        /// <summary>
        /// 销售提成明细
        /// </summary>
        private readonly RB_Sell_Commission_DetailsRepository sell_Commission_DetailsRepository = new RB_Sell_Commission_DetailsRepository();
        /// <summary>
        /// 销售提成抵扣
        /// </summary>
        private readonly RB_Sell_Commission_DeductionRepository sell_Commission_DeductionRepository = new RB_Sell_Commission_DeductionRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();
        /// <summary>
        /// 订单学生
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();
        /// <summary>
        /// 教师
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();
        /// <summary>
        /// 上课计划
        /// </summary>
        private readonly RB_Class_PlanRepository class_PlanRepository = new RB_Class_PlanRepository();
        /// <summary>
        /// 上课时间
        /// </summary>
        private readonly RB_Class_TimeRepository class_TimeRepository = new RB_Class_TimeRepository();
        /// <summary>
        /// 签到
        /// </summary>
        private readonly RB_Class_CheckRepository class_CheckRepository = new RB_Class_CheckRepository();
        /// <summary>
        /// 班级
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();
        /// <summary>
        /// 课程
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();
        /// <summary>
        /// 班级类型
        /// </summary>
        private readonly RB_Class_TypeRepository class_TypeRepository = new RB_Class_TypeRepository();
        /// <summary>
        /// 财务账户
        /// </summary>
        private readonly RB_ClientBankAccountRepository clientBankAccountRepository = new RB_ClientBankAccountRepository();
        /// <summary>
        /// 集团
        /// </summary>
        private readonly RB_GroupRepository groupRepository = new RB_GroupRepository();
        /// <summary>
        /// 账户
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();
        /// <summary>
        /// 部门
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();
        /// <summary>
        /// 校区
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();
        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();


        #region 基础配置
        /// <summary>
        /// 获取规则列表
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Rule_ViewModel> GetSellCommissionRuleList(int groupId)
        {
            var list = sell_Commission_RuleRepository.GetList(new RB_Sell_Commission_Rule_ViewModel() { Group_Id = groupId });
            return list;
        }

        /// <summary>
        /// 新增  修改规则
        /// </summary>
        /// <param name="firstRate"></param>
        /// <param name="deList"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetSellCommissionRule(decimal firstRate, List<RB_Sell_Commission_Rule_ViewModel> deList, UserInfo userInfo)
        {
            var olist = sell_Commission_RuleRepository.GetList(new RB_Sell_Commission_Rule_ViewModel() { Group_Id = userInfo.Group_Id });
            foreach (var item in deList)
            {
                var omodel = olist.Where(x => x.ClassType == item.ClassType && x.EnrollType == item.EnrollType).FirstOrDefault();
                if (omodel == null)
                {
                    //新增
                    item.Id = 0;
                    item.Group_Id = userInfo.Group_Id;
                    item.CreateBy = userInfo.Id;
                    item.UpdateBy = userInfo.Id;
                    item.CreateTime = DateTime.Now;
                    item.UpdateTime = DateTime.Now;
                    item.FirstRate = firstRate;
                    sell_Commission_RuleRepository.Insert(item);
                }
                else
                {
                    //修改
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Sell_Commission_Rule_ViewModel.SalesRate), item.SalesRate},
                        { nameof(RB_Sell_Commission_Rule_ViewModel.TeacherRate), item.TeacherRate},
                        { nameof(RB_Sell_Commission_Rule_ViewModel.AssistantRate), item.AssistantRate},
                        { nameof(RB_Sell_Commission_Rule_ViewModel.UpdateBy), userInfo.Id},
                        { nameof(RB_Sell_Commission_Rule_ViewModel.UpdateTime), DateTime.Now},
                        { nameof(RB_Sell_Commission_Rule_ViewModel.FirstRate), firstRate},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Sell_Commission_Rule_ViewModel.Id),
                              FiledValue= item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    sell_Commission_RuleRepository.Update(keyValues, wheres);
                }
            }
            foreach (var item in olist)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Sell_Commission_Rule_ViewModel.FirstRate), firstRate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Sell_Commission_Rule_ViewModel.Id),
                            FiledValue= item.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                sell_Commission_RuleRepository.Update(keyValues, wheres);
            }
            return true;
        }

        #endregion

        #region 提成列表

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Periods_ViewModel> GetSellCommissionPeriodsList(RB_Sell_Commission_Periods_ViewModel dmodel)
        {
            return sell_Commission_PeriodsRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取提成期数分页类别
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Periods_ViewModel> GetSellCommissionPeriodsPageList(int pageIndex, int pageSize, out long count, RB_Sell_Commission_Periods_ViewModel dmodel)
        {
            var list = sell_Commission_PeriodsRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询财务单据
                string periodsIds = string.Join(",", list.Select(x => x.Id));
                var financeList = financeRepository.GetListSingle(new RB_Finance_Extend() { RB_Group_Id = dmodel.Group_Id, FinanceType = 2, OtherType = 39, ReFinanceIds = periodsIds, IsSelectNormal = 1 });
                List<RB_Sell_Commission_Details_ViewModel> scList = new List<RB_Sell_Commission_Details_ViewModel>();
                if (dmodel.SchoolId >= 0)
                {
                    //获取该校区应发提成  
                    scList = sell_Commission_DetailsRepository.GetSchoolCommission(dmodel.SchoolId, periodsIds);
                }
                foreach (var item in list)
                {
                    var flist = financeList.Where(x => x.ReFinanceId == item.Id).Select(x => x.FrID);
                    if (flist.Any())
                    {
                        item.Financials = string.Join(",", flist);
                    }
                    item.SchooldCommission = item.SumPrice;
                    if (dmodel.SchoolId >= 0)
                    {
                        item.SchooldCommission = scList.Where(x => x.PeriodId == item.Id).FirstOrDefault()?.CurrentPeriodMoney ?? 0;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户提成列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Details_ViewModel> GetSellCommissionUserList(RB_Sell_Commission_Details_ViewModel dmodel)
        {
            var list = sell_Commission_DetailsRepository.GetSellCommissionUserList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 累计提成金额统计
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetSellCommissionStatistics(RB_Sell_Commission_Details_ViewModel dmodel)
        {
            return sell_Commission_DetailsRepository.GetSellCommissionStatistics(dmodel);
        }




        /// <summary>
        /// 获取销售提成根据用户id
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Details_ViewModel> GetSellCommissionByUser(RB_Sell_Commission_Details_ViewModel demodel)
        {
            return sell_Commission_DetailsRepository.GetSellCommissionByUser(demodel);

        }



        /// <summary>
        /// 确认销售提成
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateSureSellCommission(int UserId, int Id)
        {
            IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(RB_Sell_Commission_Details_ViewModel.SureStatus), 1 },

                };
            IList<WhereHelper> auditrecordWhereHelpers = new List<WhereHelper>
                    {
                        new WhereHelper()
                        {
                            FiledName = nameof(RB_Sell_Commission_Details_ViewModel.Id),
                            FiledValue = Id,
                            OperatorEnum = OperatorEnum.Equal
                        },
                         new WhereHelper()
                        {
                            FiledName = nameof(RB_Sell_Commission_Details_ViewModel.UserId),
                            FiledValue = UserId,
                            OperatorEnum = OperatorEnum.Equal
                        }
                    };
            return sell_Commission_DetailsRepository.Update(fileds, auditrecordWhereHelpers);

        }


        /// <summary>
        /// 获取提成统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Details_ViewModel> GetSellCommissionStatisticsPageList(int pageIndex, int pageSize, out long count, RB_Sell_Commission_Details_ViewModel dmodel)
        {
            var list = sell_Commission_DetailsRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });
                //查询出所属班级信息
                string classIds = string.Join(",", list.Select(x => x.ClassId).Distinct());
                var clist = classRepository.GetClassListRepository(new RB_Class_ViewModel() { Group_Id = dmodel.Group_Id, Q_ClassIds = classIds });
                //查询班级类型
                string classTypeIds = string.Join(",", list.Select(x => x.ClassType).Distinct());
                var ctlist = class_TypeRepository.GetClassTypeListRepository(new RB_Class_Type_ViewModel() { Q_CTypeIds = classTypeIds, Group_Id = dmodel.Group_Id });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                    item.ClassName = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault()?.ClassName ?? "";
                    item.ClassNo = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault()?.ClassNo ?? "";
                    item.ClassTypeName = ctlist.Where(x => x.CTypeId == item.ClassType).FirstOrDefault()?.CTypeName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户提成明细列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Details_ViewModel> GetSellCommissionUserDetailList(RB_Sell_Commission_Details_ViewModel dmodel)
        {
            var list = sell_Commission_DetailsRepository.GetList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });
                //查询出所属班级信息
                string classIds = string.Join(",", list.Select(x => x.ClassId).Distinct());
                var clist = classRepository.GetClassListRepository(new RB_Class_ViewModel() { Group_Id = dmodel.Group_Id, Q_ClassIds = classIds });
                //查询班级类型
                string classTypeIds = string.Join(",", list.Select(x => x.ClassType).Distinct());
                var ctlist = class_TypeRepository.GetClassTypeListRepository(new RB_Class_Type_ViewModel() { Q_CTypeIds = classTypeIds, Group_Id = dmodel.Group_Id });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                    item.ClassName = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault()?.ClassName ?? "";
                    item.ClassNo = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault()?.ClassNo ?? "";
                    item.ClassTypeName = ctlist.Where(x => x.CTypeId == item.ClassType).FirstOrDefault()?.CTypeName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户提成明细列表 （有当前发放次数的）
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Details_ViewModel> GetSellCommissionUserDetailList_V2(RB_Sell_Commission_Details_ViewModel dmodel)
        {
            var list = sell_Commission_DetailsRepository.GetSellCommissionUserDetailList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                string deptIds = string.Join(",", list.Select(x => x.Depart_Id).Distinct());
                string schoolIds = string.Join(",", list.Select(x => x.School_Id).Distinct());
                var ulist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = dmodel.Group_Id, QIds = userIds });
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = dmodel.Group_Id, QSIds = schoolIds });
                //查询出所属班级信息
                string classIds = string.Join(",", list.Select(x => x.ClassId).Distinct());
                var clist = classRepository.GetClassListRepository(new RB_Class_ViewModel() { Group_Id = dmodel.Group_Id, Q_ClassIds = classIds });
                //查询班级类型
                string classTypeIds = string.Join(",", list.Select(x => x.ClassType).Distinct());
                var ctlist = class_TypeRepository.GetClassTypeListRepository(new RB_Class_Type_ViewModel() { Q_CTypeIds = classTypeIds, Group_Id = dmodel.Group_Id });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel.EmployeeName + (umodel.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure ? "离职" : "");
                    item.DeptName = dlist.Where(x => x.DeptId == item.Depart_Id).FirstOrDefault()?.DeptName ?? "";
                    item.SchoolName = slist.Where(x => x.SId == item.School_Id).FirstOrDefault()?.SName ?? "";
                    item.ClassName = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault()?.ClassName ?? "";
                    item.ClassNo = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault()?.ClassNo ?? "";
                    item.ClassTypeName = ctlist.Where(x => x.CTypeId == item.ClassType).FirstOrDefault()?.CTypeName ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 创建提成s
        /// </summary>
        /// <param name="month"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetSellCommissionInfo(string month, UserInfo userInfo)
        {
            //首先查询该月是否已创建
            var plist = sell_Commission_PeriodsRepository.GetList(new RB_Sell_Commission_Periods_ViewModel() { Group_Id = userInfo.Group_Id, Periods = month });
            if (plist.Any())
            {
                return "当月提成已创建";
            }
            //查询 班级订单  1.尾款收齐  2.学生上课完成总课时超过15 %
            string EDate = Convert.ToDateTime(month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            #region 查询内部班
            var courseList = courseRepository.GetCourseListRepository(new RB_Course_ViewModel() { Group_Id = userInfo.Group_Id, CourseName = "内部班" });
            string courseIds = string.Join(",", courseList.Select(x => x.CourseId));
            #endregion
            var orderList = orderRepository.GetAllMoneyCollectedOrderList(userInfo.Group_Id, EDate, courseIds);//开班时间 必须在选择的月份之前  要排除内部班 --------------
            if (orderList.Any())
            {
                #region 基础数据
                //查询规则列表
                var rulelist = sell_Commission_RuleRepository.GetList(new RB_Sell_Commission_Rule_ViewModel() { Group_Id = userInfo.Group_Id });
                //查询所有的人员
                var saleIdList = orderList.Select(x => x.EnterID).Distinct().ToList();
                var teacherIdList = orderList.Where(x => x.HelpEnterId > 0).Select(x => x.HelpEnterId).Distinct().ToList();
                saleIdList.AddRange(teacherIdList);
                var userIds = string.Join(",", saleIdList);
                var UserList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = userIds });
                //查询班级信息
                string classIds = string.Join(",", orderList.Select(x => x.ClassId).Distinct());
                var clist = classRepository.GetClassListRepository(new RB_Class_ViewModel() { Group_Id = userInfo.Group_Id, Q_ClassIds = classIds });
                //查询订单下所有学生 已完成课时
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                var CheckList = class_CheckRepository.GetClassStudentHoursListForOrderMonth(userInfo.Group_Id, orderIds);//使用月份统计的  方便下面每月消费课时计算
                //查询订单下所有学员信息
                var glist = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = orderIds });
                //查询这些订单 已发放提成记录
                var dlist = sell_Commission_DetailsRepository.GetList(new RB_Sell_Commission_Details_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = orderIds });
                #endregion
                List<RB_Sell_Commission_Details_ViewModel> CurrentList = new List<RB_Sell_Commission_Details_ViewModel>();//当期的提成数据
                List<RB_Order_ViewModel> UpdateOrderList = new List<RB_Order_ViewModel>();// 只记录应发总金额
                foreach (var item in orderList)
                {
                    if (item.EnterID == item.HelpEnterId)
                    {
                        item.HelpEnterId = 0;
                    }
                    #region 当前已发提成
                    decimal ClassCommissioned = dlist.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentPeriodMoney);
                    decimal SaleCommissioned = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.EnterID).Sum(x => x.CurrentPeriodMoney);
                    decimal TeacherCommissioned = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.HelpEnterId).Sum(x => x.CurrentPeriodMoney);
                    decimal ExtraCommissioned = dlist.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentExtraMoney);
                    #endregion

                    var classModel = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault();
                    if (classModel == null) { break; }
                    int EnrollType = item.RenewOrderId > 0 ? 2 : 1;
                    var ruleModel = rulelist.Where(x => x.ClassType == classModel.ClassType && x.EnrollType == EnrollType).FirstOrDefault();//该订单适用规则

                    #region 订单应发提成 (不包括 额外提成)
                    decimal YFCommission = 0;
                    if (item.CommissionType == item.CommissionTypeTH)
                    {
                        if (item.CommissionType == 1)
                        {
                            YFCommission = item.CommissionRate + item.CommissionRateTH;// 固定金额  暂时只做人民币；
                        }
                        else
                        {
                            YFCommission = Math.Round((item.PreferPrice - item.DiscountMoney + item.LessPrice) * (item.CommissionRate + item.CommissionRateTH) / 100, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    else
                    {
                        if (item.CommissionType == 1)
                        {
                            YFCommission = item.CommissionRate;// 固定金额  暂时只做人民币；
                        }
                        else
                        {
                            YFCommission = Math.Round((item.PreferPrice - item.DiscountMoney + item.LessPrice) * item.CommissionRate / 100, 2, MidpointRounding.AwayFromZero);
                        }
                        if (item.CommissionTypeTH == 1)
                        {
                            YFCommission += item.CommissionRateTH;// 固定金额  暂时只做人民币；
                        }
                        else
                        {
                            YFCommission += Math.Round((item.PreferPrice - item.DiscountMoney + item.LessPrice) * item.CommissionRateTH / 100, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    if (item.LessPrice > 0)
                    {
                        YFCommission -= item.LessPrice;
                    }

                    if (YFCommission == 0 && ClassCommissioned == 0)
                    {
                        break;
                    }
                    #endregion

                    //销售 + 老师 应发多少提成
                    decimal saleMoney = 0, teacherMoney = 0;
                    if (item.HelpEnterId > 0)
                    {
                        saleMoney = Math.Round(YFCommission * ruleModel.SalesRate / 100, 2, MidpointRounding.AwayFromZero);
                        teacherMoney = Math.Round(YFCommission * (100 - ruleModel.SalesRate) / 100, 2, MidpointRounding.AwayFromZero);
                        if (saleMoney + teacherMoney < YFCommission)
                        {
                            saleMoney += YFCommission - saleMoney - teacherMoney;//多余的  加到销售提成里
                        }
                    }
                    else
                    {
                        saleMoney = YFCommission;
                    }

                    #region 计算课时
                    var g3list = glist.Where(x => x.OrderId == item.OrderId && x.GuestState != 2).ToList();
                    //查询这几个学生累计课时
                    decimal TotalLearn = CheckList.Where(x => x.OrderId == item.OrderId && x.MonthDate <= Convert.ToDateTime(EDate)).Sum(x => x.CurrentDeductionHours);//累计消费课时  (要查询当前发放提成日期) ld 07-02调整
                    decimal TotalHours = g3list.Sum(x => x.TotalHours);// 直接根据学生表  总课时计算   (必须签到课时 = 总课时  才发完最后一个月的)
                    #endregion

                    #region 额外提成
                    decimal ExtraCommission = item.ExtraRewardMoney - item.ExtraDeductMoney - item.ExtraCommissionMoney;//额外需要发放的提成
                    //额外奖励  直接发给销售
                    if (ExtraCommission != 0)
                    {
                        CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = item.EnterID,
                            OrderId = item.OrderId,
                            CurrentExtraMoney = ExtraCommission,
                            Remark = ExtraCommission > 0 ? "额外奖励" + ExtraCommission + "金额" : "额外扣除" + (ExtraCommission) + "金额",

                            CurrentPeriodMoney = 0,
                            ClassId = item.ClassId,
                            ClassType = classModel.ClassType,
                            PeriodId = 0,
                            Periods = month,
                            CommissionMoney = saleMoney,
                            OtherMoney = item.ExtraRewardMoney,
                            BackMoney = item.ExtraDeductMoney,
                            StudentCount = item.GuestNum,
                            TotalHours = Convert.ToInt32(TotalHours),
                            TotalLearn = Convert.ToInt32(TotalLearn),
                            CurrentHours = -1,//这种只额外奖励的  没有课时消费
                            IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                            GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                            SalesRate = 0,
                            TeacherRate = 0,
                            AssistantRate = 0,
                            FirstRate = 0,
                            DeductionMoney = 0,
                            DeductionExtraMoney = 0
                        });

                        var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        if (upmodel == null)
                        {
                            UpdateOrderList.Add(new RB_Order_ViewModel()
                            {
                                OrderId = item.OrderId,
                                CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                            });
                        }
                    }
                    #endregion

                    if (YFCommission == ClassCommissioned)
                    {
                        //正好提成已发放完成  直接更新 订单 已发放Ok
                        var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        if (upmodel == null)
                        {
                            UpdateOrderList.Add(new RB_Order_ViewModel()
                            {
                                OrderId = item.OrderId,
                                CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                            });
                        }
                    }
                    else if (YFCommission < ClassCommissioned)
                    {
                        //可能因为调整应收   导致提成多发  需要补回来  补的时候  又分 销售+老师
                        if (item.HelpEnterId > 0)
                        {
                            if (saleMoney < SaleCommissioned)
                            {
                                decimal saleMoney1 = saleMoney - SaleCommissioned;
                                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                {
                                    UserId = item.EnterID,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = saleMoney1,
                                    IsDeduction = 1,
                                    Remark = "当前提成应发：" + saleMoney + "，已实发：" + SaleCommissioned + "，销售应补金额：" + saleMoney1,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = saleMoney,
                                    OtherMoney = item.ExtraRewardMoney,
                                    BackMoney = item.ExtraDeductMoney,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                    GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                    SalesRate = 0,
                                    TeacherRate = 0,
                                    AssistantRate = 0,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    DeductionExtraMoney = 0
                                });
                            }
                            if (teacherMoney < TeacherCommissioned)
                            {
                                decimal teacherMoney1 = teacherMoney - TeacherCommissioned;
                                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                {
                                    UserId = item.HelpEnterId,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = teacherMoney1,
                                    IsDeduction = 1,
                                    Remark = "当前提成应发：" + teacherMoney + "，已实发：" + TeacherCommissioned + "，教师应补金额：" + teacherMoney1,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = teacherMoney,
                                    OtherMoney = item.ExtraRewardMoney,
                                    BackMoney = item.ExtraDeductMoney,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                    GiveOutMoney = TeacherCommissioned,
                                    SalesRate = 0,
                                    TeacherRate = 0,
                                    AssistantRate = 0,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    DeductionExtraMoney = 0
                                });
                            }
                        }
                        else
                        {
                            //销售全占
                            decimal BMoney = YFCommission - ClassCommissioned;
                            CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                            {
                                UserId = item.EnterID,
                                OrderId = item.OrderId,
                                CurrentPeriodMoney = BMoney,
                                IsDeduction = 1,
                                Remark = "当前提成应发：" + YFCommission + "，已实发：" + ClassCommissioned + "，销售应补金额：" + BMoney,

                                CurrentExtraMoney = 0,
                                ClassId = item.ClassId,
                                ClassType = classModel.ClassType,
                                PeriodId = 0,
                                Periods = month,
                                CommissionMoney = YFCommission,
                                OtherMoney = item.ExtraRewardMoney,
                                BackMoney = item.ExtraDeductMoney,
                                StudentCount = item.GuestNum,
                                TotalHours = Convert.ToInt32(TotalHours),
                                TotalLearn = Convert.ToInt32(TotalLearn),
                                CurrentHours = -1,//这种补提成的  没有课时消费
                                IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                SalesRate = 0,
                                TeacherRate = 0,
                                AssistantRate = 0,
                                FirstRate = 0,
                                DeductionMoney = 0,
                                DeductionExtraMoney = 0
                            });
                        }

                        var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        if (upmodel == null)
                        {
                            UpdateOrderList.Add(new RB_Order_ViewModel()
                            {
                                OrderId = item.OrderId,
                                CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                            });
                        }
                    }
                    else
                    {
                        #region 班级提成
                        //查询是否订单下所有学员都已退学  
                        var g2list = glist.Where(x => x.OrderId == item.OrderId).ToList();
                        if (g2list.Where(x => x.GuestState == 2).Count() == item.GuestNum)
                        {
                            //所有学生都退学了   直接计算提成  全部一次性发放
                            if (item.HelpEnterId > 0)
                            {
                                if (saleMoney > SaleCommissioned)
                                {
                                    decimal saleMoney1 = saleMoney - SaleCommissioned;
                                    CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                    {
                                        UserId = item.EnterID,
                                        OrderId = item.OrderId,
                                        CurrentPeriodMoney = saleMoney1,
                                        Remark = "当前订单学生退学，直接发放剩余提成：" + saleMoney1,

                                        ClassId = item.ClassId,
                                        ClassType = classModel.ClassType,
                                        PeriodId = 0,
                                        Periods = month,
                                        CommissionMoney = saleMoney,
                                        OtherMoney = item.ExtraRewardMoney,
                                        BackMoney = item.ExtraDeductMoney,
                                        StudentCount = item.GuestNum,
                                        TotalHours = Convert.ToInt32(TotalHours),
                                        TotalLearn = Convert.ToInt32(TotalLearn),
                                        CurrentHours = -1,//这种都退学的  没有课时消费
                                        IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                        GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                        SalesRate = 0,
                                        TeacherRate = 0,
                                        AssistantRate = 0,
                                        FirstRate = 0,
                                        DeductionMoney = 0,
                                        DeductionExtraMoney = 0
                                    });
                                }
                                if (teacherMoney < TeacherCommissioned)
                                {
                                    decimal teacherMoney1 = teacherMoney - TeacherCommissioned;
                                    CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                    {
                                        UserId = item.HelpEnterId,
                                        OrderId = item.OrderId,
                                        CurrentPeriodMoney = teacherMoney1,
                                        Remark = "当前订单学生退学，直接发放剩余提成：" + teacherMoney1,

                                        ClassId = item.ClassId,
                                        ClassType = classModel.ClassType,
                                        PeriodId = 0,
                                        Periods = month,
                                        CommissionMoney = teacherMoney,
                                        OtherMoney = item.ExtraRewardMoney,
                                        BackMoney = item.ExtraDeductMoney,
                                        StudentCount = item.GuestNum,
                                        TotalHours = Convert.ToInt32(TotalHours),
                                        TotalLearn = Convert.ToInt32(TotalLearn),
                                        CurrentHours = -1,//这种都退学的  没有课时消费
                                        IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                        GiveOutMoney = TeacherCommissioned + ExtraCommissioned,
                                        SalesRate = 0,
                                        TeacherRate = 0,
                                        AssistantRate = 0,
                                        FirstRate = 0,
                                        DeductionMoney = 0,
                                        DeductionExtraMoney = 0
                                    });
                                }
                            }
                            else
                            {
                                //销售全占
                                decimal BMoney = YFCommission - ClassCommissioned;
                                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                {
                                    UserId = item.EnterID,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = BMoney,
                                    Remark = "当前订单学生退学，直接发放剩余提成：" + BMoney,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = YFCommission,
                                    OtherMoney = item.ExtraRewardMoney,
                                    BackMoney = item.ExtraDeductMoney,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                    GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                    SalesRate = 0,
                                    TeacherRate = 0,
                                    AssistantRate = 0,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    DeductionExtraMoney = 0
                                });
                            }

                            var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                            if (upmodel == null)
                            {
                                UpdateOrderList.Add(new RB_Order_ViewModel()
                                {
                                    OrderId = item.OrderId,
                                    CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                                });
                            }
                        }
                        else
                        {
                            //验证是否满足  上课课时超15%
                            if (TotalLearn > TotalHours * Convert.ToDecimal(Config.SellCommissionFFBL))
                            {
                                //查询该订单 已发提成记录
                                //先查询销售的
                                var salelist = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.EnterID).ToList();
                                if (salelist.Any())
                                {
                                    SetCommissionNext(month, CheckList, CurrentList, item, classModel, TotalHours, saleMoney, salelist, item.EnterID, true);
                                }
                                else
                                {
                                    //直接  发首次提成
                                    decimal FirstMoney = Math.Round(saleMoney * ruleModel.FirstRate / 100, 2, MidpointRounding.AwayFromZero);
                                    CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                    {
                                        UserId = item.EnterID,
                                        OrderId = item.OrderId,
                                        CurrentPeriodMoney = FirstMoney,
                                        IsFirstCommission = 1,
                                        Remark = "首次发放提成比例：" + ruleModel.FirstRate,

                                        ClassId = item.ClassId,
                                        ClassType = classModel.ClassType,
                                        PeriodId = 0,
                                        Periods = month,
                                        CommissionMoney = saleMoney,
                                        OtherMoney = item.ExtraRewardMoney,
                                        BackMoney = item.ExtraDeductMoney,
                                        StudentCount = item.GuestNum,
                                        TotalHours = Convert.ToInt32(TotalHours),
                                        TotalLearn = Convert.ToInt32(TotalLearn),
                                        CurrentHours = -1,//这种首次发放提成的  没有课时消费
                                        IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                        GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                        SalesRate = ruleModel.SalesRate,
                                        TeacherRate = ruleModel.TeacherRate,
                                        AssistantRate = ruleModel.AssistantRate,
                                        FirstRate = ruleModel.FirstRate,
                                        DeductionMoney = 0,
                                        DeductionExtraMoney = 0
                                    });
                                }
                                if (item.HelpEnterId > 0)
                                {
                                    //给老师发提成
                                    var teacherlist = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.HelpEnterId).ToList();
                                    if (teacherlist.Any())
                                    {
                                        SetCommissionNext(month, CheckList, CurrentList, item, classModel, TotalHours, teacherMoney, teacherlist, item.HelpEnterId, false);
                                    }
                                    else
                                    {
                                        //直接  发首次提成
                                        decimal FirstMoney = Math.Round(teacherMoney * ruleModel.FirstRate / 100, 2, MidpointRounding.AwayFromZero);
                                        CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                        {
                                            UserId = item.HelpEnterId,
                                            OrderId = item.OrderId,
                                            CurrentPeriodMoney = FirstMoney,
                                            IsFirstCommission = 1,
                                            Remark = "首次发放提成比例：" + ruleModel.FirstRate,

                                            ClassId = item.ClassId,
                                            ClassType = classModel.ClassType,
                                            PeriodId = 0,
                                            Periods = month,
                                            CommissionMoney = teacherMoney,
                                            OtherMoney = item.ExtraRewardMoney,
                                            BackMoney = item.ExtraDeductMoney,
                                            StudentCount = item.GuestNum,
                                            TotalHours = Convert.ToInt32(TotalHours),
                                            TotalLearn = Convert.ToInt32(TotalLearn),
                                            CurrentHours = -1,//这种首次发的  没有课时消费
                                            IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                            GiveOutMoney = TeacherCommissioned + ExtraCommissioned,
                                            SalesRate = ruleModel.SalesRate,
                                            TeacherRate = ruleModel.TeacherRate,
                                            AssistantRate = ruleModel.AssistantRate,
                                            FirstRate = ruleModel.FirstRate,
                                            DeductionMoney = 0,
                                            DeductionExtraMoney = 0
                                        });
                                    }
                                }

                                var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                                if (upmodel == null)
                                {
                                    UpdateOrderList.Add(new RB_Order_ViewModel()
                                    {
                                        OrderId = item.OrderId,
                                        CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                                    });
                                }
                            }
                        }
                        #endregion
                    }
                }

                #region 开始遍历
                List<RB_Sell_Commission_Deduction_ViewModel> DeductionList = new List<RB_Sell_Commission_Deduction_ViewModel>();//抵扣详情
                var ExtraList = CurrentList.Where(x => x.CurrentExtraMoney > 0).ToList();//额外提成的
                var NorList = CurrentList.Where(x => x.IsDeduction != 1 && x.CurrentExtraMoney == 0).ToList();//正常的
                var DeList = CurrentList.Where(x => x.IsDeduction == 1).ToList();//需抵扣的   负数存的
                var DeExtraList = CurrentList.Where(x => x.CurrentExtraMoney < 0).ToList();//额外奖励  需抵扣的   负数存的
                //先把正常订单  额外奖励加上去
                foreach (var qitem in ExtraList)
                {
                    var norModel = NorList.Where(x => x.OrderId == qitem.OrderId && x.UserId == qitem.UserId).FirstOrDefault();
                    if (norModel == null)
                    {
                        NorList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = qitem.UserId,
                            OrderId = qitem.OrderId,
                            CurrentPeriodMoney = 0,
                            CurrentExtraMoney = qitem.CurrentExtraMoney,

                            AssistantRate = qitem.AssistantRate,
                            Remark = qitem.Remark,
                            DeductionExtraMoney = qitem.DeductionExtraMoney,
                            BackMoney = qitem.BackMoney,
                            ClassId = qitem.ClassId,
                            ClassName = qitem.ClassName,
                            ClassType = qitem.ClassType,
                            ClassTypeName = qitem.ClassTypeName,
                            CommissionMoney = qitem.CommissionMoney,
                            CurrentHours = qitem.CurrentHours,
                            DeductionMoney = qitem.DeductionMoney,
                            DeductionOrder = qitem.DeductionOrder,
                            Depart_Id = qitem.Depart_Id,
                            DeptName = qitem.DeptName,
                            FirstRate = qitem.FirstRate,
                            GiveOutMoney = qitem.GiveOutMoney,
                            Group_Id = qitem.Group_Id,
                            Id = qitem.Id,
                            IsContinueClass = qitem.IsContinueClass,
                            IsDeduction = qitem.IsDeduction,
                            IsFirstCommission = qitem.IsFirstCommission,
                            OrderIds = qitem.OrderIds,
                            OtherMoney = qitem.OtherMoney,
                            PeriodId = qitem.PeriodId,
                            Periods = qitem.Periods,
                            SalesRate = qitem.SalesRate,
                            School_Id = qitem.School_Id,
                            StudentCount = qitem.StudentCount,
                            TeacherRate = qitem.TeacherRate,
                            TotalHours = qitem.TotalHours,
                            TotalLearn = qitem.TotalLearn
                        });
                    }
                    else
                    {
                        norModel.CurrentExtraMoney = qitem.CurrentExtraMoney;
                        norModel.Remark += ";" + qitem.Remark;
                    }
                }
                //遍历班级提成需抵扣的
                foreach (var xdkitem in DeList)
                {
                    var nordList = NorList.Where(x => x.UserId == xdkitem.UserId).OrderBy(x => x.OrderId).ToList();
                    if (nordList.Any())
                    {
                        //从订单一次开始抵扣   抵扣了之后  原金额不动， 抵扣字段增加
                        foreach (var dkitem in nordList)
                        {
                            if (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney >= 0)
                            {
                                //补交完了 继续下一个
                                break;
                            }
                            if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) <= 0 && dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney <= 0)
                            {
                                //已经没有钱可以抵扣了  继续下一个 （班级提成  + 额外奖励）
                                continue;
                            }
                            if ((xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney) + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) >= 0)
                            {
                                //全部抵扣   用需抵扣
                                DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                {
                                    OrderId = xdkitem.OrderId,
                                    SourceId = dkitem.OrderId,
                                    Type = 1,
                                    DeductionMoney = 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney),
                                    DeductionExtraMoney = 0,
                                    Group_Id = userInfo.Group_Id,
                                    Remark = ""
                                });
                                if (dkitem.OrderId != xdkitem.OrderId)
                                    dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                //更新数据
                                dkitem.DeductionMoney += xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney;//存负数  表抵扣了这么多
                                xdkitem.DeductionMoney += 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney);//正数
                            }
                            else
                            {
                                if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) > 0)
                                {
                                    //部分抵扣  用正常的
                                    DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                    {
                                        OrderId = xdkitem.OrderId,
                                        SourceId = dkitem.OrderId,
                                        Type = 1,
                                        DeductionMoney = (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney),
                                        DeductionExtraMoney = 0,
                                        Group_Id = userInfo.Group_Id,
                                        Remark = ""
                                    });
                                    xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    if (dkitem.OrderId != xdkitem.OrderId)
                                        dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    //更新数据
                                    xdkitem.DeductionMoney += (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//正数
                                    dkitem.DeductionMoney += 0 - (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//存负数  表抵扣了这么多
                                }

                                //继续抵扣奖励
                                if (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney > 0)
                                {
                                    if ((xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney) + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) >= 0)
                                    {
                                        //可以抵扣完
                                        DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                        {
                                            OrderId = xdkitem.OrderId,
                                            SourceId = dkitem.OrderId,
                                            Type = 1,
                                            DeductionExtraMoney = 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney),
                                            DeductionMoney = 0,
                                            Group_Id = userInfo.Group_Id,
                                            Remark = ""
                                        });
                                        if (dkitem.OrderId != xdkitem.OrderId)
                                            dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                        xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                        //更新数据
                                        dkitem.DeductionExtraMoney += xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney;//存负数  表抵扣了这么多
                                        xdkitem.DeductionMoney += 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney);//正数
                                    }
                                    else
                                    {
                                        if ((dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) > 0)
                                        {
                                            //部分抵扣  用正常的
                                            DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                            {
                                                OrderId = xdkitem.OrderId,
                                                SourceId = dkitem.OrderId,
                                                Type = 1,
                                                DeductionMoney = (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney),
                                                DeductionExtraMoney = 0,
                                                Group_Id = userInfo.Group_Id,
                                                Remark = ""
                                            });
                                            xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            if (dkitem.OrderId != xdkitem.OrderId)
                                                dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            //更新数据
                                            xdkitem.DeductionMoney += (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//正数
                                            dkitem.DeductionExtraMoney += 0 - (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//存负数  表抵扣了这么多
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //遍历额外奖励需抵扣的    这个一般应该不会有  概率非常小
                foreach (var xdkitem in DeExtraList)
                {
                    var nordList = NorList.Where(x => x.UserId == xdkitem.UserId).OrderBy(x => x.OrderId).ToList();
                    if (nordList.Any())
                    {
                        //从订单一次开始抵扣   抵扣了之后  原金额不动， 抵扣字段增加
                        foreach (var dkitem in nordList)
                        {
                            if (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney >= 0)
                            {
                                //补交完了 继续下一个
                                break;
                            }
                            if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) <= 0 && dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney <= 0)
                            {
                                //已经没有钱可以抵扣了  继续下一个 （班级提成  + 额外奖励）
                                continue;
                            }
                            if ((xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney) + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) >= 0)
                            {
                                //全部抵扣   用需抵扣
                                DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                {
                                    OrderId = xdkitem.OrderId,
                                    SourceId = dkitem.OrderId,
                                    Type = 1,
                                    DeductionMoney = 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney),
                                    DeductionExtraMoney = 0,
                                    Group_Id = userInfo.Group_Id,
                                    Remark = ""
                                });
                                if (dkitem.OrderId != xdkitem.OrderId)
                                    dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                //更新数据
                                dkitem.DeductionMoney += xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney;//存负数  表抵扣了这么多
                                xdkitem.DeductionExtraMoney += 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney);//正数
                            }
                            else
                            {
                                if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) > 0)
                                {
                                    //部分抵扣  用正常的
                                    DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                    {
                                        OrderId = xdkitem.OrderId,
                                        SourceId = dkitem.OrderId,
                                        Type = 1,
                                        DeductionMoney = (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney),
                                        DeductionExtraMoney = 0,
                                        Group_Id = userInfo.Group_Id,
                                        Remark = ""
                                    });
                                    xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    if (dkitem.OrderId != xdkitem.OrderId)
                                        dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    //更新数据
                                    xdkitem.DeductionExtraMoney += (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//正数
                                    dkitem.DeductionMoney += 0 - (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//存负数  表抵扣了这么多
                                }

                                //继续抵扣奖励
                                if (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney > 0)
                                {
                                    if ((xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney) + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) >= 0)
                                    {
                                        //可以抵扣完
                                        DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                        {
                                            OrderId = xdkitem.OrderId,
                                            SourceId = dkitem.OrderId,
                                            Type = 1,
                                            DeductionExtraMoney = 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney),
                                            DeductionMoney = 0,
                                            Group_Id = userInfo.Group_Id,
                                            Remark = ""
                                        });
                                        if (dkitem.OrderId != xdkitem.OrderId)
                                            dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                        xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                        //更新数据
                                        dkitem.DeductionExtraMoney += xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney;//存负数  表抵扣了这么多
                                        xdkitem.DeductionExtraMoney += 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney);//正数                                        
                                    }
                                    else
                                    {
                                        if ((dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) > 0)
                                        {
                                            //部分抵扣  用正常的
                                            DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                            {
                                                OrderId = xdkitem.OrderId,
                                                SourceId = dkitem.OrderId,
                                                Type = 1,
                                                DeductionMoney = (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney),
                                                DeductionExtraMoney = 0,
                                                Group_Id = userInfo.Group_Id,
                                                Remark = ""
                                            });
                                            xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            if (dkitem.OrderId != xdkitem.OrderId)
                                                dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            //更新数据
                                            xdkitem.DeductionExtraMoney += (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//正数
                                            dkitem.DeductionExtraMoney += 0 - (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//存负数  表抵扣了这么多
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //这里  DeList  DeExtraList   可能会有重复数据   这里需要排除  ----------------------------------
                foreach (var qitem in DeList)
                {
                    qitem.CurrentPeriodMoney = 0 - qitem.DeductionMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                    var norModel = NorList.Where(x => x.OrderId == qitem.OrderId && x.UserId == qitem.UserId).FirstOrDefault();
                    if (norModel == null)
                    {
                        NorList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = qitem.UserId,
                            OrderId = qitem.OrderId,
                            CurrentPeriodMoney = qitem.CurrentPeriodMoney,
                            CurrentExtraMoney = qitem.CurrentExtraMoney,
                            DeductionMoney = qitem.DeductionMoney,
                            DeductionExtraMoney = qitem.DeductionExtraMoney,
                            Remark = qitem.Remark,

                            AssistantRate = qitem.AssistantRate,
                            BackMoney = qitem.BackMoney,
                            ClassId = qitem.ClassId,
                            ClassName = qitem.ClassName,
                            ClassType = qitem.ClassType,
                            ClassTypeName = qitem.ClassTypeName,
                            CommissionMoney = qitem.CommissionMoney,
                            CurrentHours = qitem.CurrentHours,
                            DeductionOrder = qitem.DeductionOrder,
                            Depart_Id = qitem.Depart_Id,
                            DeptName = qitem.DeptName,
                            FirstRate = qitem.FirstRate,
                            GiveOutMoney = qitem.GiveOutMoney,
                            Group_Id = qitem.Group_Id,
                            Id = qitem.Id,
                            IsContinueClass = qitem.IsContinueClass,
                            IsDeduction = qitem.IsDeduction,
                            IsFirstCommission = qitem.IsFirstCommission,
                            OrderIds = qitem.OrderIds,
                            OtherMoney = qitem.OtherMoney,
                            PeriodId = qitem.PeriodId,
                            Periods = qitem.Periods,
                            SalesRate = qitem.SalesRate,
                            School_Id = qitem.School_Id,
                            StudentCount = qitem.StudentCount,
                            TeacherRate = qitem.TeacherRate,
                            TotalHours = qitem.TotalHours,
                            TotalLearn = qitem.TotalLearn
                        });
                    }
                    else
                    {
                        if (qitem.OrderId == norModel.OrderId)
                        {
                            norModel.CurrentPeriodMoney = qitem.CurrentPeriodMoney;
                            norModel.DeductionMoney = qitem.DeductionMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                        else
                        {
                            norModel.CurrentPeriodMoney += qitem.CurrentPeriodMoney;
                            norModel.CurrentExtraMoney += qitem.CurrentExtraMoney;
                            norModel.DeductionMoney += qitem.DeductionMoney;
                            norModel.DeductionExtraMoney += qitem.DeductionExtraMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                    }
                }

                foreach (var qitem in DeExtraList)
                {
                    qitem.CurrentExtraMoney = 0 - qitem.DeductionExtraMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                    var norModel = NorList.Where(x => x.OrderId == qitem.OrderId && x.UserId == qitem.UserId).FirstOrDefault();
                    if (norModel == null)
                    {
                        NorList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = qitem.UserId,
                            OrderId = qitem.OrderId,
                            CurrentPeriodMoney = qitem.CurrentPeriodMoney,
                            CurrentExtraMoney = qitem.CurrentExtraMoney,
                            DeductionMoney = qitem.DeductionMoney,
                            DeductionExtraMoney = qitem.DeductionExtraMoney,
                            Remark = qitem.Remark,

                            AssistantRate = qitem.AssistantRate,
                            BackMoney = qitem.BackMoney,
                            ClassId = qitem.ClassId,
                            ClassName = qitem.ClassName,
                            ClassType = qitem.ClassType,
                            ClassTypeName = qitem.ClassTypeName,
                            CommissionMoney = qitem.CommissionMoney,
                            CurrentHours = qitem.CurrentHours,
                            DeductionOrder = qitem.DeductionOrder,
                            Depart_Id = qitem.Depart_Id,
                            DeptName = qitem.DeptName,
                            FirstRate = qitem.FirstRate,
                            GiveOutMoney = qitem.GiveOutMoney,
                            Group_Id = qitem.Group_Id,
                            Id = qitem.Id,
                            IsContinueClass = qitem.IsContinueClass,
                            IsDeduction = qitem.IsDeduction,
                            IsFirstCommission = qitem.IsFirstCommission,
                            OrderIds = qitem.OrderIds,
                            OtherMoney = qitem.OtherMoney,
                            PeriodId = qitem.PeriodId,
                            Periods = qitem.Periods,
                            SalesRate = qitem.SalesRate,
                            School_Id = qitem.School_Id,
                            StudentCount = qitem.StudentCount,
                            TeacherRate = qitem.TeacherRate,
                            TotalHours = qitem.TotalHours,
                            TotalLearn = qitem.TotalLearn
                        });
                    }
                    else
                    {
                        if (qitem.OrderId == norModel.OrderId)
                        {
                            norModel.CurrentExtraMoney = qitem.CurrentExtraMoney;
                            norModel.DeductionExtraMoney = qitem.DeductionExtraMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                        else
                        {
                            norModel.CurrentPeriodMoney += qitem.CurrentPeriodMoney;
                            norModel.CurrentExtraMoney += qitem.CurrentExtraMoney;
                            norModel.DeductionMoney += qitem.DeductionMoney;
                            norModel.DeductionExtraMoney += qitem.DeductionExtraMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                    }
                }

                #endregion

                #region 开始创建
                var trans = sell_Commission_PeriodsRepository.DbTransaction;
                try
                {
                    int PeriodsId = sell_Commission_PeriodsRepository.Insert(new Model.Entity.Course.RB_Sell_Commission_Periods()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Financials = "",
                        Group_Id = userInfo.Group_Id,
                        Name = month + "期提成",
                        Periods = month,
                        SumPrice = 0
                    }, trans);
                    if (PeriodsId > 0)
                    {
                        foreach (var qitem in NorList)
                        {
                            var userModel = UserList.Where(x => x.Id == qitem.UserId).FirstOrDefault();
                            qitem.Depart_Id = userModel?.Dept_Id ?? 0;
                            qitem.School_Id = userModel?.School_Id ?? 0;
                            qitem.Group_Id = userInfo.Group_Id;
                            qitem.PeriodId = PeriodsId;
                            sell_Commission_DetailsRepository.Insert(qitem, trans);
                        }
                        #region 屏蔽的
                        //foreach (var qitem in DeList)
                        //{
                        //    var userModel = UserList.Where(x => x.Id == qitem.UserId).FirstOrDefault();
                        //    qitem.Depart_Id = userModel?.Dept_Id ?? 0;
                        //    qitem.School_Id = userModel?.School_Id ?? 0;
                        //    qitem.Group_Id = userInfo.Group_Id;
                        //    qitem.PeriodId = PeriodsId;
                        //    qitem.CurrentPeriodMoney = 0 - qitem.DeductionMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                        //    sell_Commission_DetailsRepository.Insert(qitem, trans);
                        //}
                        //foreach (var qitem in DeExtraList)
                        //{
                        //    var userModel = UserList.Where(x => x.Id == qitem.UserId).FirstOrDefault();
                        //    qitem.Depart_Id = userModel?.Dept_Id ?? 0;
                        //    qitem.School_Id = userModel?.School_Id ?? 0;
                        //    qitem.Group_Id = userInfo.Group_Id;
                        //    qitem.PeriodId = PeriodsId;
                        //    qitem.CurrentExtraMoney = 0 - qitem.DeductionExtraMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                        //    sell_Commission_DetailsRepository.Insert(qitem, trans);
                        //}
                        #endregion

                        #region 计算累计应发
                        decimal SumPrice = NorList.Sum(x => x.CurrentPeriodMoney + x.CurrentExtraMoney + x.CurrentExtraMoney + x.DeductionExtraMoney);
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(Model.Entity.Course.RB_Sell_Commission_Periods.SumPrice),SumPrice}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(Model.Entity.Course.RB_Sell_Commission_Periods.Id),
                                  FiledValue=PeriodsId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        sell_Commission_PeriodsRepository.Update(keyValues, wheres, trans);
                        #endregion

                        //抵扣的明细
                        DateTime dtNow = DateTime.Now;
                        foreach (var qitem in DeductionList)
                        {
                            qitem.PeriodsId = PeriodsId;
                            qitem.CreateBy = userInfo.Id;
                            qitem.CreateTime = dtNow;
                            sell_Commission_DeductionRepository.Insert(qitem, trans);
                        }
                    }
                    sell_Commission_PeriodsRepository.DBSession.Commit();

                    #region 订单更新
                    //再次查询所有订单的
                    //查询这些订单 已发放提成记录
                    string torderIds = string.Join(",", UpdateOrderList.Select(x => x.OrderId).Distinct());
                    var dtlist = sell_Commission_DetailsRepository.GetList(new RB_Sell_Commission_Details_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = torderIds });
                    foreach (var item in UpdateOrderList)
                    {
                        //求实际的
                        decimal ClassCommissioned = dtlist.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentPeriodMoney);
                        decimal ExtraCommissioned = dtlist.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentExtraMoney);
                        decimal BackMoney = 0;
                        int IsCommissionGiveOK = 0;
                        if (item.CommissionMoney < ClassCommissioned + ExtraCommissioned)
                        {
                            //表示扣多了   
                            BackMoney = ClassCommissioned + ExtraCommissioned - item.CommissionMoney;
                        }
                        if (item.CommissionMoney == ClassCommissioned + ExtraCommissioned)
                        {
                            //表示扣多了   
                            IsCommissionGiveOK = 1;//发放完毕  
                        }

                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Order_ViewModel.CommissionMoney),ClassCommissioned},
                            { nameof(RB_Order_ViewModel.IsCommissionGive),1},
                            { nameof(RB_Order_ViewModel.CommissionBack),BackMoney},
                            { nameof(RB_Order_ViewModel.ExtraCommissionMoney),ExtraCommissioned},
                            { nameof(RB_Order_ViewModel.IsCommissionGiveOK),IsCommissionGiveOK}
                        };
                        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
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetSellCommissionInfo");
                    sell_Commission_PeriodsRepository.DBSession.Rollback();
                    return "出错了，请联系管理员";
                }
                #endregion
            }

            return "";
        }

        /// <summary>
        /// 生成当期提成
        /// </summary>
        /// <param name="month"></param>
        /// <param name="CheckList"></param>
        /// <param name="CurrentList"></param>
        /// <param name="CurrentOrderList"></param>
        /// <param name="item"></param>
        /// <param name="classModel"></param>
        /// <param name="TotalHours"></param>
        /// <param name="saleMoney"></param>
        /// <param name="salelist"></param>
        /// <param name="EnterID"></param>
        private static void SetCommissionNext(string month, List<RB_Class_Check_ViewModel> CheckList, List<RB_Sell_Commission_Details_ViewModel> CurrentList, RB_Order_ViewModel item, RB_Class_ViewModel classModel, decimal TotalHours, decimal saleMoney, List<RB_Sell_Commission_Details_ViewModel> salelist, int EnterID, bool IsSale = true)
        {
            var firstCommissionModel = salelist.Where(x => x.IsFirstCommission == 1).FirstOrDefault();
            //从最后一次发放提成开始计算
            var salemodel = salelist.OrderByDescending(x => x.Id).FirstOrDefault();
            string StartTime = month;//开始时间
            string EndTime = month;//结束时间
            if (salemodel.IsFirstCommission == 1)
            {
                StartTime = classModel.OpenTime.ToString("yyyy-MM");//开始学习的时间  暂时使用 班级的开班时间
            }
            else
            {
                if (salemodel.Periods.Contains("~"))
                {
                    StartTime = Convert.ToDateTime(salemodel.Periods.Split('~')[1] + "-01").AddMonths(1).ToString("yyyy-MM");//根据 最后的期数  再加一个月
                }
                else
                {
                    StartTime = Convert.ToDateTime(salemodel.Periods + "-01").AddMonths(1).ToString("yyyy-MM");//根据 最后的期数  再加一个月
                }
            }

            DateTime STime = Convert.ToDateTime(StartTime + "-01");
            DateTime ETime = Convert.ToDateTime(EndTime + "-01").AddMonths(1).AddDays(-1);
            //以前的总发放提成
            decimal oldCommission = salelist.Sum(x => x.CurrentPeriodMoney);
            decimal oldExtraCommission = salelist.Sum(x => x.CurrentExtraMoney);
            //当期消费课时
            decimal currentHours = CheckList.Where(x => x.OrderId == item.OrderId && x.MonthDate >= STime && x.MonthDate <= ETime).Sum(x => x.CurrentDeductionHours);
            //当期累计消费课时
            decimal currentTHours = CheckList.Where(x => x.OrderId == item.OrderId && x.MonthDate <= ETime).Sum(x => x.CurrentDeductionHours);
            if (currentTHours >= TotalHours)
            {
                //课已完成   发放剩余所有的提成
                decimal currentMoney = saleMoney - oldCommission;
                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                {
                    UserId = EnterID,
                    OrderId = item.OrderId,
                    CurrentPeriodMoney = currentMoney,
                    Remark = "最后一个月提成：总应发" + saleMoney + " - 累计已发" + oldCommission,

                    ClassId = item.ClassId,
                    ClassType = classModel.ClassType,
                    PeriodId = 0,
                    Periods = StartTime == EndTime ? StartTime : StartTime + "~" + EndTime,
                    CommissionMoney = saleMoney,
                    OtherMoney = IsSale ? item.ExtraRewardMoney : 0,
                    BackMoney = IsSale ? item.ExtraDeductMoney : 0,
                    StudentCount = item.GuestNum,
                    TotalHours = Convert.ToInt32(TotalHours),
                    TotalLearn = Convert.ToInt32(currentTHours),
                    CurrentHours = Convert.ToInt32(currentHours),
                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                    GiveOutMoney = oldCommission + oldExtraCommission,
                    SalesRate = 0,
                    TeacherRate = 0,
                    AssistantRate = 0,
                    FirstRate = 0,
                    DeductionMoney = 0,
                    DeductionExtraMoney = 0
                });
            }
            else
            {
                //计算当期消费课时
                decimal SurplusMoney = Math.Round(saleMoney * (100 - firstCommissionModel.FirstRate) / 100, 2, MidpointRounding.AwayFromZero);
                decimal cHoursMoney = Math.Round((currentHours / TotalHours) * SurplusMoney, 2, MidpointRounding.AwayFromZero);//当期应发提成

                #region 以前发放提成
                //当期以前消费课时
                decimal ctotalHours = CheckList.Where(x => x.OrderId == item.OrderId && x.MonthDate < STime).Sum(x => x.CurrentDeductionHours);
                ctotalHours = ctotalHours > TotalHours ? TotalHours : ctotalHours;
                //计算当期以前  应发提成  对比 历史发放提成， 如果发放有多  需扣除 ， 发少了  需补上
                decimal FirstMoney = Math.Round(saleMoney * firstCommissionModel.FirstRate / 100, 2, MidpointRounding.AwayFromZero);
                decimal tHoursMoney = Math.Round((ctotalHours / TotalHours) * SurplusMoney, 2, MidpointRounding.AwayFromZero);//当期以前  应发这么多
                decimal moreMoney = 0;
                string Remark = "当月应发提成：" + cHoursMoney + ";";
                if (oldCommission - (FirstMoney + tHoursMoney) >= 1)
                {
                    //以前多发了  从当期开始  慢慢扣回去;   少发了的  就不管  最后一个月 全发剩下的
                    moreMoney = oldCommission - (FirstMoney + tHoursMoney);
                    cHoursMoney -= moreMoney;
                    Remark = "因当前应发提成：" + (FirstMoney + tHoursMoney) + "，已发累计提成：" + oldCommission + "，当期扣回：" + moreMoney;
                }
                #endregion
                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                {
                    UserId = EnterID,
                    OrderId = item.OrderId,
                    CurrentPeriodMoney = cHoursMoney < 0 ? 0 : cHoursMoney,//这里 如果是负数  要记得处理 (直接默认成0 记录为何0)
                    Remark = Remark,

                    ClassId = item.ClassId,
                    ClassType = classModel.ClassType,
                    PeriodId = 0,
                    Periods = StartTime == EndTime ? StartTime : StartTime + "~" + EndTime,
                    CommissionMoney = saleMoney,
                    OtherMoney = IsSale ? item.ExtraRewardMoney : 0,
                    BackMoney = IsSale ? item.ExtraDeductMoney : 0,
                    StudentCount = item.GuestNum,
                    TotalHours = Convert.ToInt32(TotalHours),
                    TotalLearn = Convert.ToInt32(currentTHours),
                    CurrentHours = Convert.ToInt32(currentHours),
                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                    GiveOutMoney = oldCommission + oldExtraCommission,
                    SalesRate = 0,
                    TeacherRate = 0,
                    AssistantRate = 0,
                    FirstRate = 0,
                    DeductionMoney = 0,
                    DeductionExtraMoney = 0
                });

            }
        }

        /// <summary>
        /// 获取两日期间的所有月份
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        private List<string> GetTwoDateMonth(string startTime, string endTime)
        {
            List<string> DateList = new List<string>();
            if (startTime == endTime)
            {
                DateList.Add(startTime);
                return DateList;
            }
            else
            {
                string sTime = startTime;
                while (true)
                {
                    DateList.Add(sTime);
                    sTime = Convert.ToDateTime(sTime + "-01").AddMonths(1).ToString("yyyy-MM");
                    if (sTime == endTime)
                    {
                        break;
                    }
                }
                return DateList;
            }
        }

        /// <summary>
        /// 验证用户离职
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string GetUserLeaveOrderCommission(int userId, UserInfo userInfo)
        {
            int count = orderRepository.GetUserLeaveOrderCommission(userId, userInfo.Group_Id);
            if (count <= 0)
            {
                return "";
            }
            else
            {
                return "该用户有" + count + "个订单提成需补交，无法设置离职";
            }
        }

        /// <summary>
        /// 获取未发放提成用户列表 + 提成金额
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetSellCommissionSendEmployeeList(int periodId, UserInfo userInfo)
        {
            var model = sell_Commission_PeriodsRepository.GetEntity(periodId);
            if (model == null) { return "周期不存在"; }
            List<int> EmpIdList = new List<int>();
            if (!string.IsNullOrEmpty(model.EmpIds))
            {
                EmpIdList = JsonHelper.DeserializeObject<List<int>>("[" + model.EmpIds + "]");
            }
            var list = GetSellCommissionUserList(new RB_Sell_Commission_Details_ViewModel() { Group_Id = userInfo.Group_Id, PeriodId = periodId });
            return ApiResult.Success("", list.Select(x => new
            {
                x.UserId,
                x.UserName,
                x.StudentCount,
                CurrentPeriodMoney = x.CurrentPeriodMoney + x.CurrentExtraMoney,
                IsGiveOut = EmpIdList.Contains(x.UserId) ? 1 : 2
            }));
        }

        /// <summary>
        /// 设置发放提成
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="empIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetSellCommissionSendEmployee(int periodId, string empIds, UserInfo userInfo)
        {
            var model = sell_Commission_PeriodsRepository.GetEntity(periodId);
            if (model == null) { return "周期不存在"; }
            if (model.Group_Id != userInfo.Group_Id) { return "集团不正确"; }
            List<int> EmpIdList = new List<int>();
            if (!string.IsNullOrEmpty(model.EmpIds))
            {
                EmpIdList = JsonHelper.DeserializeObject<List<int>>("[" + model.EmpIds + "]");
            }
            List<int> NewIdList = JsonHelper.DeserializeObject<List<int>>("[" + empIds + "]");
            foreach (var item in NewIdList)
            {
                if (EmpIdList.Contains(item))
                {
                    return "用户ID" + item + "已发放了提成，无法重复发放";
                }
            }
            EmpIdList.AddRange(NewIdList);
            string empids2 = string.Join(",", EmpIdList);
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Sell_Commission_Periods_ViewModel.EmpIds),empids2}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName= nameof(RB_Sell_Commission_Periods_ViewModel.Id),
                      FiledValue=periodId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = sell_Commission_PeriodsRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        #endregion


        #region 本月预计提成
        /// <summary>
        /// 本月预计提成计算
        /// </summary>
        /// <param name="month"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public List<RB_Sell_Commission_Details_ViewModel> GetEstimateSellCommissionInfo(string month, UserInfo userInfo)
        {
            //首先查询该月是否已创建
            var plist = sell_Commission_PeriodsRepository.GetList(new RB_Sell_Commission_Periods_ViewModel() { Group_Id = userInfo.Group_Id, Periods = month });
            if (plist.Any())
            {
                return new List<RB_Sell_Commission_Details_ViewModel>();
            }
            //查询 班级订单  1.尾款收齐  2.学生上课完成总课时超过15 %
            string EDate = Convert.ToDateTime(month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            #region 查询内部班
            var courseList = courseRepository.GetCourseListRepository(new RB_Course_ViewModel() { Group_Id = userInfo.Group_Id, CourseName = "内部班" });
            string courseIds = string.Join(",", courseList.Select(x => x.CourseId));
            #endregion
            var orderList = orderRepository.GetAllMoneyCollectedOrderList(userInfo.Group_Id, EDate, courseIds).Where(x => x.EnterID == userInfo.Id);//开班时间 必须在选择的月份之前  要排除内部班 --------------
            if (orderList.Any())
            {
                #region 基础数据
                //查询规则列表
                var rulelist = sell_Commission_RuleRepository.GetList(new RB_Sell_Commission_Rule_ViewModel() { Group_Id = userInfo.Group_Id });
                //查询所有的人员
                var saleIdList = orderList.Select(x => x.EnterID).Distinct().ToList();
                //var teacherIdList = orderList.Where(x => x.HelpEnterId > 0&&x.HelpEnterId==userInfo.Id).Select(x => x.HelpEnterId).Distinct().ToList();
                //saleIdList.AddRange(teacherIdList);
                var userIds = string.Join(",", saleIdList);
                var UserList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = userIds });
                //查询班级信息
                string classIds = string.Join(",", orderList.Select(x => x.ClassId).Distinct());
                var clist = classRepository.GetClassListRepository(new RB_Class_ViewModel() { Group_Id = userInfo.Group_Id, Q_ClassIds = classIds });
                //查询订单下所有学生 已完成课时
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                var CheckList = class_CheckRepository.GetClassStudentHoursListForOrderMonth(userInfo.Group_Id, orderIds);//使用月份统计的  方便下面每月消费课时计算
                //查询订单下所有学员信息
                var glist = order_GuestRepository.GetOrderGuestListRepository(new RB_Order_Guest_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = orderIds });
                //查询这些订单 已发放提成记录
                var dlist = sell_Commission_DetailsRepository.GetList(new RB_Sell_Commission_Details_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = orderIds });
                #endregion
                List<RB_Sell_Commission_Details_ViewModel> CurrentList = new List<RB_Sell_Commission_Details_ViewModel>();//当期的提成数据
                List<RB_Sell_Commission_Details_ViewModel> NorList = new List<RB_Sell_Commission_Details_ViewModel>();//当期的提成数据
                List<RB_Order_ViewModel> UpdateOrderList = new List<RB_Order_ViewModel>();// 只记录应发总金额
                foreach (var item in orderList)
                {
                    if (item.EnterID == item.HelpEnterId)
                    {
                        item.HelpEnterId = 0;
                    }
                    #region 当前已发提成
                    decimal ClassCommissioned = dlist.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentPeriodMoney);
                    decimal SaleCommissioned = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.EnterID).Sum(x => x.CurrentPeriodMoney);
                    decimal TeacherCommissioned = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.HelpEnterId).Sum(x => x.CurrentPeriodMoney);
                    decimal ExtraCommissioned = dlist.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentExtraMoney);
                    #endregion

                    var classModel = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault();
                    if (classModel == null) { break; }
                    int EnrollType = item.RenewOrderId > 0 ? 2 : 1;
                    var ruleModel = rulelist.Where(x => x.ClassType == classModel.ClassType && x.EnrollType == EnrollType).FirstOrDefault();//该订单适用规则

                    #region 订单应发提成 (不包括 额外提成)
                    decimal YFCommission = 0;
                    if (item.CommissionType == item.CommissionTypeTH)
                    {
                        if (item.CommissionType == 1)
                        {
                            YFCommission = item.CommissionRate + item.CommissionRateTH;// 固定金额  暂时只做人民币；
                        }
                        else
                        {
                            YFCommission = Math.Round((item.PreferPrice - item.DiscountMoney + item.LessPrice) * (item.CommissionRate + item.CommissionRateTH) / 100, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    else
                    {
                        if (item.CommissionType == 1)
                        {
                            YFCommission = item.CommissionRate;// 固定金额  暂时只做人民币；
                        }
                        else
                        {
                            YFCommission = Math.Round((item.PreferPrice - item.DiscountMoney + item.LessPrice) * item.CommissionRate / 100, 2, MidpointRounding.AwayFromZero);
                        }
                        if (item.CommissionTypeTH == 1)
                        {
                            YFCommission += item.CommissionRateTH;// 固定金额  暂时只做人民币；
                        }
                        else
                        {
                            YFCommission += Math.Round((item.PreferPrice - item.DiscountMoney + item.LessPrice) * item.CommissionRateTH / 100, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    if (item.LessPrice > 0)
                    {
                        YFCommission -= item.LessPrice;
                    }

                    if (YFCommission == 0 && ClassCommissioned == 0)
                    {
                        break;
                    }
                    #endregion

                    //销售 + 老师 应发多少提成
                    decimal saleMoney = 0, teacherMoney = 0;
                    if (item.HelpEnterId > 0)
                    {
                        saleMoney = Math.Round(YFCommission * ruleModel.SalesRate / 100, 2, MidpointRounding.AwayFromZero);
                        teacherMoney = Math.Round(YFCommission * (100 - ruleModel.SalesRate) / 100, 2, MidpointRounding.AwayFromZero);
                        if (saleMoney + teacherMoney < YFCommission)
                        {
                            saleMoney += YFCommission - saleMoney - teacherMoney;//多余的  加到销售提成里
                        }
                    }
                    else
                    {
                        saleMoney = YFCommission;
                    }

                    #region 计算课时
                    var g3list = glist.Where(x => x.OrderId == item.OrderId && x.GuestState != 2).ToList();
                    //查询这几个学生累计课时
                    decimal TotalLearn = CheckList.Where(x => x.OrderId == item.OrderId).Sum(x => x.CurrentDeductionHours);//累计消费课时
                    decimal TotalHours = g3list.Sum(x => x.TotalHours);// 直接根据学生表  总课时计算   (必须签到课时 = 总课时  才发完最后一个月的)
                    #endregion

                    #region 额外提成
                    decimal ExtraCommission = item.ExtraRewardMoney - item.ExtraDeductMoney - item.ExtraCommissionMoney;//额外需要发放的提成
                    //额外奖励  直接发给销售
                    if (ExtraCommission != 0)
                    {
                        CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = item.EnterID,
                            OrderId = item.OrderId,
                            CurrentExtraMoney = ExtraCommission,
                            Remark = ExtraCommission > 0 ? "额外奖励" + ExtraCommission + "金额" : "额外扣除" + (ExtraCommission) + "金额",

                            CurrentPeriodMoney = 0,
                            ClassId = item.ClassId,
                            ClassType = classModel.ClassType,
                            PeriodId = 0,
                            Periods = month,
                            CommissionMoney = saleMoney,
                            OtherMoney = item.ExtraRewardMoney,
                            BackMoney = item.ExtraDeductMoney,
                            StudentCount = item.GuestNum,
                            TotalHours = Convert.ToInt32(TotalHours),
                            TotalLearn = Convert.ToInt32(TotalLearn),
                            CurrentHours = -1,//这种只额外奖励的  没有课时消费
                            IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                            GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                            SalesRate = 0,
                            TeacherRate = 0,
                            AssistantRate = 0,
                            FirstRate = 0,
                            DeductionMoney = 0,
                            DeductionExtraMoney = 0
                        });

                        var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        if (upmodel == null)
                        {
                            UpdateOrderList.Add(new RB_Order_ViewModel()
                            {
                                OrderId = item.OrderId,
                                CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                            });
                        }
                    }
                    #endregion

                    if (YFCommission == ClassCommissioned)
                    {
                        //正好提成已发放完成  直接更新 订单 已发放Ok
                        var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        if (upmodel == null)
                        {
                            UpdateOrderList.Add(new RB_Order_ViewModel()
                            {
                                OrderId = item.OrderId,
                                CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                            });
                        }
                    }
                    else if (YFCommission < ClassCommissioned)
                    {
                        //可能因为调整应收   导致提成多发  需要补回来  补的时候  又分 销售+老师
                        if (item.HelpEnterId > 0)
                        {
                            if (saleMoney < SaleCommissioned)
                            {
                                decimal saleMoney1 = saleMoney - SaleCommissioned;
                                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                {
                                    UserId = item.EnterID,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = saleMoney1,
                                    IsDeduction = 1,
                                    Remark = "当前提成应发：" + saleMoney + "，已实发：" + SaleCommissioned + "，销售应补金额：" + saleMoney1,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = saleMoney,
                                    OtherMoney = item.ExtraRewardMoney,
                                    BackMoney = item.ExtraDeductMoney,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                    GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                    SalesRate = 0,
                                    TeacherRate = 0,
                                    AssistantRate = 0,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    DeductionExtraMoney = 0
                                });
                            }
                            if (teacherMoney < TeacherCommissioned)
                            {
                                decimal teacherMoney1 = teacherMoney - TeacherCommissioned;
                                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                {
                                    UserId = item.HelpEnterId,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = teacherMoney1,
                                    IsDeduction = 1,
                                    Remark = "当前提成应发：" + teacherMoney + "，已实发：" + TeacherCommissioned + "，教师应补金额：" + teacherMoney1,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = teacherMoney,
                                    OtherMoney = item.ExtraRewardMoney,
                                    BackMoney = item.ExtraDeductMoney,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                    GiveOutMoney = TeacherCommissioned,
                                    SalesRate = 0,
                                    TeacherRate = 0,
                                    AssistantRate = 0,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    DeductionExtraMoney = 0
                                });
                            }
                        }
                        else
                        {
                            //销售全占
                            decimal BMoney = YFCommission - ClassCommissioned;
                            CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                            {
                                UserId = item.EnterID,
                                OrderId = item.OrderId,
                                CurrentPeriodMoney = BMoney,
                                IsDeduction = 1,
                                Remark = "当前提成应发：" + YFCommission + "，已实发：" + ClassCommissioned + "，销售应补金额：" + BMoney,

                                CurrentExtraMoney = 0,
                                ClassId = item.ClassId,
                                ClassType = classModel.ClassType,
                                PeriodId = 0,
                                Periods = month,
                                CommissionMoney = YFCommission,
                                OtherMoney = item.ExtraRewardMoney,
                                BackMoney = item.ExtraDeductMoney,
                                StudentCount = item.GuestNum,
                                TotalHours = Convert.ToInt32(TotalHours),
                                TotalLearn = Convert.ToInt32(TotalLearn),
                                CurrentHours = -1,//这种补提成的  没有课时消费
                                IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                SalesRate = 0,
                                TeacherRate = 0,
                                AssistantRate = 0,
                                FirstRate = 0,
                                DeductionMoney = 0,
                                DeductionExtraMoney = 0
                            });
                        }

                        var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        if (upmodel == null)
                        {
                            UpdateOrderList.Add(new RB_Order_ViewModel()
                            {
                                OrderId = item.OrderId,
                                CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                            });
                        }
                    }
                    else
                    {
                        #region 班级提成
                        //查询是否订单下所有学员都已退学  
                        var g2list = glist.Where(x => x.OrderId == item.OrderId).ToList();
                        if (g2list.Where(x => x.GuestState == 2).Count() == item.GuestNum)
                        {
                            //所有学生都退学了   直接计算提成  全部一次性发放
                            if (item.HelpEnterId > 0)
                            {
                                if (saleMoney > SaleCommissioned)
                                {
                                    decimal saleMoney1 = saleMoney - SaleCommissioned;
                                    CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                    {
                                        UserId = item.EnterID,
                                        OrderId = item.OrderId,
                                        CurrentPeriodMoney = saleMoney1,
                                        Remark = "当前订单学生退学，直接发放剩余提成：" + saleMoney1,

                                        ClassId = item.ClassId,
                                        ClassType = classModel.ClassType,
                                        PeriodId = 0,
                                        Periods = month,
                                        CommissionMoney = saleMoney,
                                        OtherMoney = item.ExtraRewardMoney,
                                        BackMoney = item.ExtraDeductMoney,
                                        StudentCount = item.GuestNum,
                                        TotalHours = Convert.ToInt32(TotalHours),
                                        TotalLearn = Convert.ToInt32(TotalLearn),
                                        CurrentHours = -1,//这种都退学的  没有课时消费
                                        IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                        GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                        SalesRate = 0,
                                        TeacherRate = 0,
                                        AssistantRate = 0,
                                        FirstRate = 0,
                                        DeductionMoney = 0,
                                        DeductionExtraMoney = 0
                                    });
                                }
                                if (teacherMoney < TeacherCommissioned)
                                {
                                    decimal teacherMoney1 = teacherMoney - TeacherCommissioned;
                                    CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                    {
                                        UserId = item.HelpEnterId,
                                        OrderId = item.OrderId,
                                        CurrentPeriodMoney = teacherMoney1,
                                        Remark = "当前订单学生退学，直接发放剩余提成：" + teacherMoney1,

                                        ClassId = item.ClassId,
                                        ClassType = classModel.ClassType,
                                        PeriodId = 0,
                                        Periods = month,
                                        CommissionMoney = teacherMoney,
                                        OtherMoney = item.ExtraRewardMoney,
                                        BackMoney = item.ExtraDeductMoney,
                                        StudentCount = item.GuestNum,
                                        TotalHours = Convert.ToInt32(TotalHours),
                                        TotalLearn = Convert.ToInt32(TotalLearn),
                                        CurrentHours = -1,//这种都退学的  没有课时消费
                                        IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                        GiveOutMoney = TeacherCommissioned + ExtraCommissioned,
                                        SalesRate = 0,
                                        TeacherRate = 0,
                                        AssistantRate = 0,
                                        FirstRate = 0,
                                        DeductionMoney = 0,
                                        DeductionExtraMoney = 0
                                    });
                                }
                            }
                            else
                            {
                                //销售全占
                                decimal BMoney = YFCommission - ClassCommissioned;
                                CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                {
                                    UserId = item.EnterID,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = BMoney,
                                    Remark = "当前订单学生退学，直接发放剩余提成：" + BMoney,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = YFCommission,
                                    OtherMoney = item.ExtraRewardMoney,
                                    BackMoney = item.ExtraDeductMoney,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                    GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                    SalesRate = 0,
                                    TeacherRate = 0,
                                    AssistantRate = 0,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    DeductionExtraMoney = 0
                                });
                            }

                            var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                            if (upmodel == null)
                            {
                                UpdateOrderList.Add(new RB_Order_ViewModel()
                                {
                                    OrderId = item.OrderId,
                                    CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                                });
                            }
                        }
                        else
                        {
                            //验证是否满足  上课课时超15%
                            if (TotalLearn > TotalHours * Convert.ToDecimal(Config.SellCommissionFFBL))
                            {
                                //查询该订单 已发提成记录
                                //先查询销售的
                                var salelist = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.EnterID).ToList();
                                if (salelist.Any())
                                {
                                    SetCommissionNext(month, CheckList, CurrentList, item, classModel, TotalHours, saleMoney, salelist, item.EnterID, true);
                                }
                                else
                                {
                                    //直接  发首次提成
                                    decimal FirstMoney = Math.Round(saleMoney * ruleModel.FirstRate / 100, 2, MidpointRounding.AwayFromZero);
                                    CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                    {
                                        UserId = item.EnterID,
                                        OrderId = item.OrderId,
                                        CurrentPeriodMoney = FirstMoney,
                                        IsFirstCommission = 1,
                                        Remark = "首次发放提成比例：" + ruleModel.FirstRate,

                                        ClassId = item.ClassId,
                                        ClassType = classModel.ClassType,
                                        PeriodId = 0,
                                        Periods = month,
                                        CommissionMoney = saleMoney,
                                        OtherMoney = item.ExtraRewardMoney,
                                        BackMoney = item.ExtraDeductMoney,
                                        StudentCount = item.GuestNum,
                                        TotalHours = Convert.ToInt32(TotalHours),
                                        TotalLearn = Convert.ToInt32(TotalLearn),
                                        CurrentHours = -1,//这种首次发放提成的  没有课时消费
                                        IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                        GiveOutMoney = SaleCommissioned + ExtraCommissioned,
                                        SalesRate = ruleModel.SalesRate,
                                        TeacherRate = ruleModel.TeacherRate,
                                        AssistantRate = ruleModel.AssistantRate,
                                        FirstRate = ruleModel.FirstRate,
                                        DeductionMoney = 0,
                                        DeductionExtraMoney = 0
                                    });
                                }
                                if (item.HelpEnterId > 0)
                                {
                                    //给老师发提成
                                    var teacherlist = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == item.HelpEnterId).ToList();
                                    if (teacherlist.Any())
                                    {
                                        SetCommissionNext(month, CheckList, CurrentList, item, classModel, TotalHours, teacherMoney, teacherlist, item.HelpEnterId, false);
                                    }
                                    else
                                    {
                                        //直接  发首次提成
                                        decimal FirstMoney = Math.Round(teacherMoney * ruleModel.FirstRate / 100, 2, MidpointRounding.AwayFromZero);
                                        CurrentList.Add(new RB_Sell_Commission_Details_ViewModel()
                                        {
                                            UserId = item.HelpEnterId,
                                            OrderId = item.OrderId,
                                            CurrentPeriodMoney = FirstMoney,
                                            IsFirstCommission = 1,
                                            Remark = "首次发放提成比例：" + ruleModel.FirstRate,

                                            ClassId = item.ClassId,
                                            ClassType = classModel.ClassType,
                                            PeriodId = 0,
                                            Periods = month,
                                            CommissionMoney = teacherMoney,
                                            OtherMoney = item.ExtraRewardMoney,
                                            BackMoney = item.ExtraDeductMoney,
                                            StudentCount = item.GuestNum,
                                            TotalHours = Convert.ToInt32(TotalHours),
                                            TotalLearn = Convert.ToInt32(TotalLearn),
                                            CurrentHours = -1,//这种首次发的  没有课时消费
                                            IsContinueClass = item.RenewOrderId > 0 ? 1 : 0,
                                            GiveOutMoney = TeacherCommissioned + ExtraCommissioned,
                                            SalesRate = ruleModel.SalesRate,
                                            TeacherRate = ruleModel.TeacherRate,
                                            AssistantRate = ruleModel.AssistantRate,
                                            FirstRate = ruleModel.FirstRate,
                                            DeductionMoney = 0,
                                            DeductionExtraMoney = 0
                                        });
                                    }
                                }

                                var upmodel = UpdateOrderList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                                if (upmodel == null)
                                {
                                    UpdateOrderList.Add(new RB_Order_ViewModel()
                                    {
                                        OrderId = item.OrderId,
                                        CommissionMoney = YFCommission + (item.ExtraRewardMoney - item.ExtraDeductMoney)
                                    });
                                }
                            }
                        }
                        #endregion
                    }
                }

                #region 开始遍历
                List<RB_Sell_Commission_Deduction_ViewModel> DeductionList = new List<RB_Sell_Commission_Deduction_ViewModel>();//抵扣详情
                var ExtraList = CurrentList.Where(x => x.CurrentExtraMoney > 0).ToList();//额外提成的
                NorList = CurrentList.Where(x => x.IsDeduction != 1 && x.CurrentExtraMoney == 0).ToList();//正常的
                var DeList = CurrentList.Where(x => x.IsDeduction == 1).ToList();//需抵扣的   负数存的
                var DeExtraList = CurrentList.Where(x => x.CurrentExtraMoney < 0).ToList();//额外奖励  需抵扣的   负数存的
                //先把正常订单  额外奖励加上去
                foreach (var qitem in ExtraList)
                {
                    var norModel = NorList.Where(x => x.OrderId == qitem.OrderId && x.UserId == qitem.UserId).FirstOrDefault();
                    if (norModel == null)
                    {
                        NorList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = qitem.UserId,
                            OrderId = qitem.OrderId,
                            CurrentPeriodMoney = 0,
                            CurrentExtraMoney = qitem.CurrentExtraMoney,

                            AssistantRate = qitem.AssistantRate,
                            Remark = qitem.Remark,
                            DeductionExtraMoney = qitem.DeductionExtraMoney,
                            BackMoney = qitem.BackMoney,
                            ClassId = qitem.ClassId,
                            ClassName = qitem.ClassName,
                            ClassType = qitem.ClassType,
                            ClassTypeName = qitem.ClassTypeName,
                            CommissionMoney = qitem.CommissionMoney,
                            CurrentHours = qitem.CurrentHours,
                            DeductionMoney = qitem.DeductionMoney,
                            DeductionOrder = qitem.DeductionOrder,
                            Depart_Id = qitem.Depart_Id,
                            DeptName = qitem.DeptName,
                            FirstRate = qitem.FirstRate,
                            GiveOutMoney = qitem.GiveOutMoney,
                            Group_Id = qitem.Group_Id,
                            Id = qitem.Id,
                            IsContinueClass = qitem.IsContinueClass,
                            IsDeduction = qitem.IsDeduction,
                            IsFirstCommission = qitem.IsFirstCommission,
                            OrderIds = qitem.OrderIds,
                            OtherMoney = qitem.OtherMoney,
                            PeriodId = qitem.PeriodId,
                            Periods = qitem.Periods,
                            SalesRate = qitem.SalesRate,
                            School_Id = qitem.School_Id,
                            StudentCount = qitem.StudentCount,
                            TeacherRate = qitem.TeacherRate,
                            TotalHours = qitem.TotalHours,
                            TotalLearn = qitem.TotalLearn
                        });
                    }
                    else
                    {
                        norModel.CurrentExtraMoney = qitem.CurrentExtraMoney;
                        norModel.Remark += ";" + qitem.Remark;
                    }
                }
                //遍历班级提成需抵扣的
                foreach (var xdkitem in DeList)
                {
                    var nordList = NorList.Where(x => x.UserId == xdkitem.UserId).OrderBy(x => x.OrderId).ToList();
                    if (nordList.Any())
                    {
                        //从订单一次开始抵扣   抵扣了之后  原金额不动， 抵扣字段增加
                        foreach (var dkitem in nordList)
                        {
                            if (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney >= 0)
                            {
                                //补交完了 继续下一个
                                break;
                            }
                            if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) <= 0 && dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney <= 0)
                            {
                                //已经没有钱可以抵扣了  继续下一个 （班级提成  + 额外奖励）
                                continue;
                            }
                            if ((xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney) + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) >= 0)
                            {
                                //全部抵扣   用需抵扣
                                DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                {
                                    OrderId = xdkitem.OrderId,
                                    SourceId = dkitem.OrderId,
                                    Type = 1,
                                    DeductionMoney = 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney),
                                    DeductionExtraMoney = 0,
                                    Group_Id = userInfo.Group_Id,
                                    Remark = ""
                                });
                                if (dkitem.OrderId != xdkitem.OrderId)
                                    dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                //更新数据
                                dkitem.DeductionMoney += xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney;//存负数  表抵扣了这么多
                                xdkitem.DeductionMoney += 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney);//正数
                            }
                            else
                            {
                                if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) > 0)
                                {
                                    //部分抵扣  用正常的
                                    DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                    {
                                        OrderId = xdkitem.OrderId,
                                        SourceId = dkitem.OrderId,
                                        Type = 1,
                                        DeductionMoney = (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney),
                                        DeductionExtraMoney = 0,
                                        Group_Id = userInfo.Group_Id,
                                        Remark = ""
                                    });
                                    xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    if (dkitem.OrderId != xdkitem.OrderId)
                                        dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    //更新数据
                                    xdkitem.DeductionMoney += (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//正数
                                    dkitem.DeductionMoney += 0 - (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//存负数  表抵扣了这么多
                                }

                                //继续抵扣奖励
                                if (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney > 0)
                                {
                                    if ((xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney) + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) >= 0)
                                    {
                                        //可以抵扣完
                                        DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                        {
                                            OrderId = xdkitem.OrderId,
                                            SourceId = dkitem.OrderId,
                                            Type = 1,
                                            DeductionExtraMoney = 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney),
                                            DeductionMoney = 0,
                                            Group_Id = userInfo.Group_Id,
                                            Remark = ""
                                        });
                                        if (dkitem.OrderId != xdkitem.OrderId)
                                            dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                        xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney));
                                        //更新数据
                                        dkitem.DeductionExtraMoney += xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney;//存负数  表抵扣了这么多
                                        xdkitem.DeductionMoney += 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney);//正数
                                    }
                                    else
                                    {
                                        if ((dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) > 0)
                                        {
                                            //部分抵扣  用正常的
                                            DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                            {
                                                OrderId = xdkitem.OrderId,
                                                SourceId = dkitem.OrderId,
                                                Type = 1,
                                                DeductionMoney = (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney),
                                                DeductionExtraMoney = 0,
                                                Group_Id = userInfo.Group_Id,
                                                Remark = ""
                                            });
                                            xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            if (dkitem.OrderId != xdkitem.OrderId)
                                                dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            //更新数据
                                            xdkitem.DeductionMoney += (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//正数
                                            dkitem.DeductionExtraMoney += 0 - (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//存负数  表抵扣了这么多
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //遍历额外奖励需抵扣的    这个一般应该不会有  概率非常小
                foreach (var xdkitem in DeExtraList)
                {
                    var nordList = NorList.Where(x => x.UserId == xdkitem.UserId).OrderBy(x => x.OrderId).ToList();
                    if (nordList.Any())
                    {
                        //从订单一次开始抵扣   抵扣了之后  原金额不动， 抵扣字段增加
                        foreach (var dkitem in nordList)
                        {
                            if (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney >= 0)
                            {
                                //补交完了 继续下一个
                                break;
                            }
                            if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) <= 0 && dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney <= 0)
                            {
                                //已经没有钱可以抵扣了  继续下一个 （班级提成  + 额外奖励）
                                continue;
                            }
                            if ((xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney) + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) >= 0)
                            {
                                //全部抵扣   用需抵扣
                                DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                {
                                    OrderId = xdkitem.OrderId,
                                    SourceId = dkitem.OrderId,
                                    Type = 1,
                                    DeductionMoney = 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney),
                                    DeductionExtraMoney = 0,
                                    Group_Id = userInfo.Group_Id,
                                    Remark = ""
                                });
                                if (dkitem.OrderId != xdkitem.OrderId)
                                    dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                //更新数据
                                dkitem.DeductionMoney += xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney;//存负数  表抵扣了这么多
                                xdkitem.DeductionExtraMoney += 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney);//正数
                            }
                            else
                            {
                                if ((dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) > 0)
                                {
                                    //部分抵扣  用正常的
                                    DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                    {
                                        OrderId = xdkitem.OrderId,
                                        SourceId = dkitem.OrderId,
                                        Type = 1,
                                        DeductionMoney = (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney),
                                        DeductionExtraMoney = 0,
                                        Group_Id = userInfo.Group_Id,
                                        Remark = ""
                                    });
                                    xdkitem.Remark += "; 订单" + dkitem.OrderId + " 帮补交" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    if (dkitem.OrderId != xdkitem.OrderId)
                                        dkitem.Remark += "; 帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);
                                    //更新数据
                                    xdkitem.DeductionExtraMoney += (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//正数
                                    dkitem.DeductionMoney += 0 - (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney);//存负数  表抵扣了这么多
                                }

                                //继续抵扣奖励
                                if (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney > 0)
                                {
                                    if ((xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney) + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) >= 0)
                                    {
                                        //可以抵扣完
                                        DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                        {
                                            OrderId = xdkitem.OrderId,
                                            SourceId = dkitem.OrderId,
                                            Type = 1,
                                            DeductionExtraMoney = 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney),
                                            DeductionMoney = 0,
                                            Group_Id = userInfo.Group_Id,
                                            Remark = ""
                                        });
                                        if (dkitem.OrderId != xdkitem.OrderId)
                                            dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                        xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney));
                                        //更新数据
                                        dkitem.DeductionExtraMoney += xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney;//存负数  表抵扣了这么多
                                        xdkitem.DeductionExtraMoney += 0 - (xdkitem.CurrentExtraMoney + xdkitem.DeductionExtraMoney);//正数                                        
                                    }
                                    else
                                    {
                                        if ((dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney) > 0)
                                        {
                                            //部分抵扣  用正常的
                                            DeductionList.Add(new RB_Sell_Commission_Deduction_ViewModel()
                                            {
                                                OrderId = xdkitem.OrderId,
                                                SourceId = dkitem.OrderId,
                                                Type = 1,
                                                DeductionMoney = (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney),
                                                DeductionExtraMoney = 0,
                                                Group_Id = userInfo.Group_Id,
                                                Remark = ""
                                            });
                                            xdkitem.Remark += "; 订单" + dkitem.OrderId + " 使用额外奖励帮补交" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            if (dkitem.OrderId != xdkitem.OrderId)
                                                dkitem.Remark += "; 使用额外奖励帮订单" + xdkitem.OrderId + " 抵扣" + (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);
                                            //更新数据
                                            xdkitem.DeductionExtraMoney += (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//正数
                                            dkitem.DeductionExtraMoney += 0 - (dkitem.CurrentExtraMoney + dkitem.DeductionExtraMoney);//存负数  表抵扣了这么多
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //这里  DeList  DeExtraList   可能会有重复数据   这里需要排除  ----------------------------------
                foreach (var qitem in DeList)
                {
                    qitem.CurrentPeriodMoney = 0 - qitem.DeductionMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                    var norModel = NorList.Where(x => x.OrderId == qitem.OrderId && x.UserId == qitem.UserId).FirstOrDefault();
                    if (norModel == null)
                    {
                        NorList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = qitem.UserId,
                            OrderId = qitem.OrderId,
                            CurrentPeriodMoney = qitem.CurrentPeriodMoney,
                            CurrentExtraMoney = qitem.CurrentExtraMoney,
                            DeductionMoney = qitem.DeductionMoney,
                            DeductionExtraMoney = qitem.DeductionExtraMoney,
                            Remark = qitem.Remark,

                            AssistantRate = qitem.AssistantRate,
                            BackMoney = qitem.BackMoney,
                            ClassId = qitem.ClassId,
                            ClassName = qitem.ClassName,
                            ClassType = qitem.ClassType,
                            ClassTypeName = qitem.ClassTypeName,
                            CommissionMoney = qitem.CommissionMoney,
                            CurrentHours = qitem.CurrentHours,
                            DeductionOrder = qitem.DeductionOrder,
                            Depart_Id = qitem.Depart_Id,
                            DeptName = qitem.DeptName,
                            FirstRate = qitem.FirstRate,
                            GiveOutMoney = qitem.GiveOutMoney,
                            Group_Id = qitem.Group_Id,
                            Id = qitem.Id,
                            IsContinueClass = qitem.IsContinueClass,
                            IsDeduction = qitem.IsDeduction,
                            IsFirstCommission = qitem.IsFirstCommission,
                            OrderIds = qitem.OrderIds,
                            OtherMoney = qitem.OtherMoney,
                            PeriodId = qitem.PeriodId,
                            Periods = qitem.Periods,
                            SalesRate = qitem.SalesRate,
                            School_Id = qitem.School_Id,
                            StudentCount = qitem.StudentCount,
                            TeacherRate = qitem.TeacherRate,
                            TotalHours = qitem.TotalHours,
                            TotalLearn = qitem.TotalLearn
                        });
                    }
                    else
                    {
                        if (qitem.OrderId == norModel.OrderId)
                        {
                            norModel.CurrentPeriodMoney = qitem.CurrentPeriodMoney;
                            norModel.DeductionMoney = qitem.DeductionMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                        else
                        {
                            norModel.CurrentPeriodMoney += qitem.CurrentPeriodMoney;
                            norModel.CurrentExtraMoney += qitem.CurrentExtraMoney;
                            norModel.DeductionMoney += qitem.DeductionMoney;
                            norModel.DeductionExtraMoney += qitem.DeductionExtraMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                    }
                }

                foreach (var qitem in DeExtraList)
                {
                    qitem.CurrentExtraMoney = 0 - qitem.DeductionExtraMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                    var norModel = NorList.Where(x => x.OrderId == qitem.OrderId && x.UserId == qitem.UserId).FirstOrDefault();
                    if (norModel == null)
                    {
                        NorList.Add(new RB_Sell_Commission_Details_ViewModel()
                        {
                            UserId = qitem.UserId,
                            OrderId = qitem.OrderId,
                            CurrentPeriodMoney = qitem.CurrentPeriodMoney,
                            CurrentExtraMoney = qitem.CurrentExtraMoney,
                            DeductionMoney = qitem.DeductionMoney,
                            DeductionExtraMoney = qitem.DeductionExtraMoney,
                            Remark = qitem.Remark,

                            AssistantRate = qitem.AssistantRate,
                            BackMoney = qitem.BackMoney,
                            ClassId = qitem.ClassId,
                            ClassName = qitem.ClassName,
                            ClassType = qitem.ClassType,
                            ClassTypeName = qitem.ClassTypeName,
                            CommissionMoney = qitem.CommissionMoney,
                            CurrentHours = qitem.CurrentHours,
                            DeductionOrder = qitem.DeductionOrder,
                            Depart_Id = qitem.Depart_Id,
                            DeptName = qitem.DeptName,
                            FirstRate = qitem.FirstRate,
                            GiveOutMoney = qitem.GiveOutMoney,
                            Group_Id = qitem.Group_Id,
                            Id = qitem.Id,
                            IsContinueClass = qitem.IsContinueClass,
                            IsDeduction = qitem.IsDeduction,
                            IsFirstCommission = qitem.IsFirstCommission,
                            OrderIds = qitem.OrderIds,
                            OtherMoney = qitem.OtherMoney,
                            PeriodId = qitem.PeriodId,
                            Periods = qitem.Periods,
                            SalesRate = qitem.SalesRate,
                            School_Id = qitem.School_Id,
                            StudentCount = qitem.StudentCount,
                            TeacherRate = qitem.TeacherRate,
                            TotalHours = qitem.TotalHours,
                            TotalLearn = qitem.TotalLearn
                        });
                    }
                    else
                    {
                        if (qitem.OrderId == norModel.OrderId)
                        {
                            norModel.CurrentExtraMoney = qitem.CurrentExtraMoney;
                            norModel.DeductionExtraMoney = qitem.DeductionExtraMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                        else
                        {
                            norModel.CurrentPeriodMoney += qitem.CurrentPeriodMoney;
                            norModel.CurrentExtraMoney += qitem.CurrentExtraMoney;
                            norModel.DeductionMoney += qitem.DeductionMoney;
                            norModel.DeductionExtraMoney += qitem.DeductionExtraMoney;
                            norModel.Remark += ";" + qitem.Remark;
                        }
                    }
                }

                #endregion

                return NorList;
            }

            return new List<RB_Sell_Commission_Details_ViewModel>();
        }

        #endregion
    }
}
