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.Entity.Sell;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Finance;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Log;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Customer;
using Edu.Repository.Finance;
using Edu.Repository.Grade;
using Edu.Repository.Log;
using Edu.Repository.Sell;
using Edu.Repository.StudyAbroad;
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 SellAchievementsModule
    {
        /// <summary>
        /// 时长顾问提成规则
        /// </summary>
        private readonly RB_Sell_Achievements_RuleRepository sell_Achievements_RuleRepository = new RB_Sell_Achievements_RuleRepository();
        /// <summary>
        /// 业绩提成周期
        /// </summary>
        private readonly RB_Sell_Achievements_PeriodsRepository sell_Achievements_PeriodsRepository = new RB_Sell_Achievements_PeriodsRepository();
        /// <summary>
        /// 业绩提成明细
        /// </summary>
        private readonly RB_Sell_Achievements_DetailsRepository sell_Achievements_DetailsRepository = new RB_Sell_Achievements_DetailsRepository();
        /// <summary>
        /// 业绩提成抵扣
        /// </summary>
        private readonly RB_Sell_Achievements_DeductionRepository sell_Achievements_DeductionRepository = new RB_Sell_Achievements_DeductionRepository();
        /// <summary>
        /// 业绩提成关联表
        /// </summary>
        private readonly RB_Sell_Achievements_EmpRepository sell_Achievements_EmpRepository = new RB_Sell_Achievements_EmpRepository();
        /// <summary>
        /// 同行返佣
        /// </summary>
        private readonly RB_Customer_BalanceDetailRepository customer_BalanceDetailRepository = new RB_Customer_BalanceDetailRepository();

        /// <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_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_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_Achievements_Rule_ViewModel> GetSellAchievementsRuleList(int groupId)
        {
            var list = sell_Achievements_RuleRepository.GetList(new RB_Sell_Achievements_Rule_ViewModel() { Group_Id = groupId });
            if (list.Any()) {
                string courseIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.CourseIds)).Select(x => x.CourseIds));
                List<RB_Course_ViewModel> courseList = new List<RB_Course_ViewModel>();
                if (!string.IsNullOrEmpty(courseIds)) {
                    courseList = courseRepository.GetCourseListRepository(new RB_Course_ViewModel() { Group_Id = groupId, QCourseIds = courseIds });
                }
                //查询人员
                string empIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.EmpIds)).Select(x => x.EmpIds));
                if (list.Where(x => !string.IsNullOrEmpty(x.ChildEmpIds)).Any())
                {
                    empIds += (empIds != "" ? "," : "") + string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.ChildEmpIds)).Select(x => x.ChildEmpIds));
                }
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds)) {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = empIds });
                }
                string schooldIds = string.Join(",", list.Select(x => x.SchoolIds));
                List<RB_School_ViewModel> slist = new List<RB_School_ViewModel>();
                if (!string.IsNullOrEmpty(schooldIds)) {
                    slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = groupId, QSIds = schooldIds });
                }

                foreach (var item in list) {
                    item.RateList = new List<AchievementsRateModel>();
                    if (!string.IsNullOrEmpty(item.Content)) {
                        item.RateList = JsonHelper.DeserializeObject<List<AchievementsRateModel>>(item.Content);
                    }
                    item.CourseList = courseList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                    item.EmpList = empList.Where(x => ("," + item.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                    item.ChildEmpList = new List<Employee_ViewModel>();
                    if (!string.IsNullOrEmpty(item.ChildEmpIds)) { 
                        item.ChildEmpList = empList.Where(x => ("," + item.ChildEmpIds + ",").Contains("," + x.Id + ",")).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.SchoolIds)) {
                        var sclist = slist.Where(x => ("," + item.SchoolIds + ",").Contains("," + x.SId + ",")).ToList();
                        item.SchoolName = string.Join(",", sclist.Select(x => x.SName));
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 删除规则
        /// </summary>
        /// <param name="ruleId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelSellAchievementsRule(int ruleId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Sell_Achievements_Rule_ViewModel.Status), 1},
                { nameof(RB_Sell_Achievements_Rule_ViewModel.UpdateBy), userInfo.Id},
                { nameof(RB_Sell_Achievements_Rule_ViewModel.UpdateTime), DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_Sell_Achievements_Rule_ViewModel.Id),
                      FiledValue = ruleId,
                       OperatorEnum =OperatorEnum.Equal
                }
            };
            bool flag = sell_Achievements_RuleRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 新增  修改规则
        /// </summary>
        /// <param name="firstRate"></param>
        /// <param name="deList"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetSellAchievementsRule(RB_Sell_Achievements_Rule_ViewModel demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.Name), demodel.Name},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.Type), demodel.Type},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.CourseType), demodel.CourseType},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.CourseIds), demodel.CourseIds},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.FirstRate), demodel.FirstRate},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.EmpIds), demodel.EmpIds},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.ChildEmpIds), demodel.ChildEmpIds},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.CourseRate), demodel.CourseRate},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.Content), demodel.Content},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.SchoolIds), demodel.SchoolIds},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_Sell_Achievements_Rule_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Sell_Achievements_Rule_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                return sell_Achievements_RuleRepository.Update(keyValues, wheres);
            }
            else {
                bool flag = sell_Achievements_RuleRepository.Insert(demodel) > 0;
                return flag;
            }
        }

        #endregion

        #region 提成列表

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Achievements_Periods_ViewModel> GetSellAchievementsPeriodsList(RB_Sell_Achievements_Periods_ViewModel dmodel)
        {
            return sell_Achievements_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_Achievements_Periods_ViewModel> GetSellAchievementsPeriodsPageList(int pageIndex, int pageSize, out long count, RB_Sell_Achievements_Periods_ViewModel dmodel)
        {
            var list = sell_Achievements_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 = 50, ReFinanceIds = periodsIds, IsSelectNormal = 1 });
                List<RB_Sell_Achievements_Details_ViewModel> scList = new List<RB_Sell_Achievements_Details_ViewModel>();
                if (dmodel.SchoolId >= 0)
                {
                    //获取该校区应发提成  
                    scList = sell_Achievements_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_Achievements_Details_ViewModel> GetSellAchievementsUserList(RB_Sell_Achievements_Details_ViewModel dmodel)
        {
            var list = sell_Achievements_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 GetSellAchievementsStatistics(RB_Sell_Achievements_Details_ViewModel dmodel)
        {
            return sell_Achievements_DetailsRepository.GetSellCommissionStatistics(dmodel);
        }

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

        /// <summary>
        /// 确认销售提成
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateSureSellAchievements(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_Achievements_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_Achievements_Details_ViewModel> GetSellAchievementsStatisticsPageList(int pageIndex, int pageSize, out long count, RB_Sell_Achievements_Details_ViewModel dmodel)
        {
            var list = sell_Achievements_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_Achievements_Details_ViewModel> GetSellAchievementsUserDetailList(RB_Sell_Achievements_Details_ViewModel dmodel)
        {
            var list = sell_Achievements_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_Achievements_Details_ViewModel> GetSellAchievementsUserDetailList_V2(RB_Sell_Achievements_Details_ViewModel dmodel)
        {
            var list = sell_Achievements_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>
        /// 生成当期提成
        /// </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="empModel"></param>
        private static void SetCommissionNext(string month, List<RB_Class_Check_ViewModel> CheckList, List<RB_Sell_Achievements_Details_ViewModel> CurrentList, RB_Order_ViewModel item, RB_Class_ViewModel classModel, decimal TotalHours, decimal saleMoney, List<RB_Sell_Achievements_Details_ViewModel> salelist, RB_Sell_Achievements_Emp_ViewModel empModel, 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 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_Achievements_Details_ViewModel()
                {
                    UserId = empModel.EmpId,
                    OrderId = item.OrderId,
                    CurrentPeriodMoney = currentMoney,
                    Remark = "最后一个月提成：总应发" + saleMoney + " - 累计已发" + oldCommission,

                    ClassId = item.ClassId,
                    ClassType = classModel.ClassType,
                    PeriodId = 0,
                    Periods = StartTime == EndTime ? StartTime : StartTime + "~" + EndTime,
                    CommissionMoney = saleMoney,
                    StudentCount = item.GuestNum,
                    TotalHours = Convert.ToInt32(TotalHours),
                    TotalLearn = Convert.ToInt32(currentTHours),
                    CurrentHours = Convert.ToInt32(currentHours),
                    GiveOutMoney = oldCommission,
                    FirstRate = 0,
                    DeductionMoney = 0,
                    IsDept = empModel.IsDept,
                    UserType = empModel.Type,
                    RelatedId = empModel.Id
                });
                empModel.GiveOutMoney = saleMoney;
                empModel.GiveOutState = 1;
            }
            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_Achievements_Details_ViewModel()
                {
                    UserId = empModel.EmpId,
                    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,
                    StudentCount = item.GuestNum,
                    TotalHours = Convert.ToInt32(TotalHours),
                    TotalLearn = Convert.ToInt32(currentTHours),
                    CurrentHours = Convert.ToInt32(currentHours),
                    GiveOutMoney = oldCommission,                    
                    FirstRate = 0,
                    DeductionMoney = 0,
                    IsDept = empModel.IsDept,
                    UserType = empModel.Type,
                    RelatedId = empModel.Id
                });
                empModel.GiveOutMoney = (cHoursMoney < 0 ? 0 : cHoursMoney) + oldCommission;
                empModel.GiveOutState = 2;
            }
        }        

        /// <summary>
        /// 获取未发放提成用户列表 + 提成金额
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetSellAchievementsSendEmployeeList(int periodId, UserInfo userInfo)
        {
            var model = sell_Achievements_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 = GetSellAchievementsUserList(new RB_Sell_Achievements_Details_ViewModel() { Group_Id = userInfo.Group_Id, PeriodId = periodId });
            return list.Select(x => new
            {
                x.UserId,
                x.UserName,
                x.StudentCount,
                x.CurrentPeriodMoney,
                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 SetSellAchievementsSendEmployee(int periodId, string empIds, UserInfo userInfo)
        {
            var model = sell_Achievements_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_Achievements_Periods_ViewModel.EmpIds),empids2}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName= nameof(RB_Sell_Achievements_Periods_ViewModel.Id),
                      FiledValue=periodId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = sell_Achievements_PeriodsRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        #endregion

        #region 生成业绩

        /// <summary>
        /// 生成业绩提成
        /// </summary>
        /// <param name="month"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetAchievementsCommissionInfo(string month, UserInfo userInfo)
        {
            //首先查询该月是否已创建
            var plist = sell_Achievements_PeriodsRepository.GetList(new RB_Sell_Achievements_Periods_ViewModel() { Group_Id = userInfo.Group_Id, Periods = month });
            if (plist.Any())
            {
                return "当月提成已创建";
            }
            //根据规则  分成  市场  顾问  老师
            //查询规则列表
            var rulelist = sell_Achievements_RuleRepository.GetList(new RB_Sell_Achievements_Rule_ViewModel() { Group_Id = userInfo.Group_Id });
            string SchoolIds = string.Join(",", rulelist.Select(x => x.SchoolIds));

            //查询 班级订单  1.尾款收齐
            string SDate = Config.NewAchievementsEnable;
            string EDate = Convert.ToDateTime(month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            var orderList = orderRepository.GetAllAchievementsSendOrderList(userInfo.Group_Id, SDate, EDate, 1, "", SchoolIds);//查询所有的
            List<RB_Sell_Achievements_Emp_ViewModel> AchEmpList = new List<RB_Sell_Achievements_Emp_ViewModel>();//需要新增当月的
            if (orderList.Any()) {
                //首先查询 根据规则  适配当月业绩  并生成对应的  订单人员业绩提成                
                foreach (var item in rulelist) {
                    //初始化规则比列
                    item.RateList = new List<AchievementsRateModel>();
                    if (!string.IsNullOrEmpty(item.Content))
                    {
                        item.RateList = JsonHelper.DeserializeObject<List<AchievementsRateModel>>(item.Content);
                    }
                }
                //根据订单  查询同行返佣
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                var bdList = customer_BalanceDetailRepository.GetCustomerBalanceDetailListRepository(new Model.ViewModel.Customer.RB_Customer_BalanceDetail_ViewModel() { Group_Id = userInfo.Group_Id, QOrderIds = orderIds });

                foreach (var item in rulelist.Where(x => x.Type == 3)) {
                    //老师适配规则
                    var teaOrderList = orderList.Where(x => x.HelpEnterId > 0 && ("," + item.EmpIds + ",").Contains("," + x.HelpEnterId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                    if (!string.IsNullOrEmpty(item.CourseIds)) {
                        if (item.CourseType == 1)
                        {
                            teaOrderList = teaOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                        }
                        else {
                            teaOrderList = teaOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                        }
                    }
                    if (teaOrderList.Any()) {
                        //这里应该要根据每个人的求
                        var teaList = teaOrderList.Select(x => x.HelpEnterId).ToList();
                        foreach (var teaId in teaList)
                        {
                            var orderChildList = teaOrderList.Where(x => x.HelpEnterId == teaId).ToList();
                            //计算老师业绩
                            decimal TotalYj = orderChildList.Sum(x => x.PreferPrice - x.DiscountMoney);
                            //计算订单累计返佣
                            decimal bdMoney = bdList.Where(x => orderChildList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                            decimal YjMoney = TotalYj - bdMoney;//排除同行返佣
                                                                //根据业绩所在区间 查询比例
                            var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                            if (rateModel != null)
                            {
                                foreach (var qitem in orderChildList)
                                {
                                    //当前订单的业绩
                                    decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                    decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission;
                                    AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                    {
                                        EmpId = qitem.HelpEnterId,
                                        GiveOutMoney = 0,
                                        GiveOutState = 2,
                                        Group_Id = userInfo.Group_Id,
                                        Id = 0,
                                        IsDept = 2,
                                        OrderId = qitem.OrderId,
                                        PeriodsId = 0,
                                        Rate = rateModel.Rate,
                                        PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                        RuleId = item.Id,
                                        SaleMoney = YjMoney,
                                        OrderSaleMoney = orderYj,
                                        Type = 3,
                                        Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；订单b2b返佣：" + bdCommission + "；订单业绩:" + orderYj
                                    });
                                }
                            }
                        }
                    }
                }

                foreach (var item in rulelist.Where(x => x.Type != 3)) {
                    if (string.IsNullOrEmpty(item.ChildEmpIds))
                    {
                        //非部门情况
                        //市场
                        if (item.Type == 1)
                        {
                            var sellOrderList = orderList.Where(x => x.EnterID > 0 && ("," + item.EmpIds + ",").Contains("," + x.EnterID + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                            if (!string.IsNullOrEmpty(item.CourseIds))
                            {
                                if (item.CourseType == 1)
                                {
                                    sellOrderList = sellOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                                else
                                {
                                    sellOrderList = sellOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                            }
                            if (sellOrderList.Any())
                            {
                                //这里应该要根据每个人的求
                                var enterList = sellOrderList.Select(x => x.EnterID).ToList();
                                foreach (var enterId in enterList)
                                {
                                    var orderChildList = sellOrderList.Where(x => x.EnterID == enterId).ToList();
                                    //计算市场业绩
                                    decimal TotalYj = orderChildList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                    //计算订单累计返佣
                                    decimal bdMoney = bdList.Where(x => orderChildList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                    //查询老师的提成
                                    decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && orderChildList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                    decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                    //根据业绩所在区间 查询比例
                                    var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                    if (rateModel != null)
                                    {
                                        foreach (var qitem in orderChildList)
                                        {
                                            //当前订单的业绩
                                            decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                            decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                            decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                            AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                            {
                                                EmpId = qitem.EnterID,
                                                GiveOutMoney = 0,
                                                GiveOutState = 2,
                                                Group_Id = userInfo.Group_Id,
                                                Id = 0,
                                                IsDept = 2,
                                                OrderId = qitem.OrderId,
                                                PeriodsId = 0,
                                                Rate = rateModel.Rate,
                                                PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                RuleId = item.Id,
                                                SaleMoney = YjMoney,
                                                OrderSaleMoney = orderYj,
                                                Type = 1,
                                                Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                            });
                                        }
                                    }
                                }
                            }
                        }
                        //顾问
                        else
                        {
                            var consultantOrderList = orderList.Where(x => x.CourseConsultantId > 0 && ("," + item.EmpIds + ",").Contains("," + x.CourseConsultantId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                            if (!string.IsNullOrEmpty(item.CourseIds))
                            {
                                if (item.CourseType == 1)
                                {
                                    consultantOrderList = consultantOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                                else
                                {
                                    consultantOrderList = consultantOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                            }
                            if (consultantOrderList.Any())
                            {
                                //这里应该要根据每个人的求
                                var consultantIdList = consultantOrderList.Select(x => x.CourseConsultantId).ToList();
                                foreach (var ConsultantId in consultantIdList)
                                {
                                    //课程顾问
                                    var orderChildList = consultantOrderList.Where(x => x.CourseConsultantId == ConsultantId).ToList();
                                    //计算市场业绩
                                    decimal TotalYj = orderChildList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                    //计算订单累计返佣
                                    decimal bdMoney = bdList.Where(x => orderChildList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                    //查询老师的提成
                                    decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && orderChildList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                    decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                       //根据业绩所在区间 查询比例
                                    var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                    if (rateModel != null)
                                    {
                                        foreach (var qitem in orderChildList)
                                        {
                                            //当前订单的业绩
                                            decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                            decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                            decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                            AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                            {
                                                EmpId = qitem.CourseConsultantId,
                                                GiveOutMoney = 0,
                                                GiveOutState = 2,
                                                Group_Id = userInfo.Group_Id,
                                                Id = 0,
                                                IsDept = 2,
                                                OrderId = qitem.OrderId,
                                                PeriodsId = 0,
                                                Rate = rateModel.Rate,
                                                PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                RuleId = item.Id,
                                                SaleMoney = YjMoney,
                                                OrderSaleMoney = orderYj,
                                                Type = 2,
                                                Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else {
                        //部门情况
                        //部门领取提成人
                        List<int> EmpList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                        if (item.Type == 1)
                        {
                            var sellOrderList = orderList.Where(x => x.EnterID > 0 && ("," + item.ChildEmpIds + ",").Contains("," + x.EnterID + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                            if (!string.IsNullOrEmpty(item.CourseIds))
                            {
                                if (item.CourseType == 1)
                                {
                                    sellOrderList = sellOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                                else
                                {
                                    sellOrderList = sellOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                            }
                            if (sellOrderList.Any())
                            {                                
                                //计算市场业绩
                                decimal TotalYj = sellOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                //计算订单累计返佣
                                decimal bdMoney = bdList.Where(x => sellOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                //查询老师的提成
                                decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && sellOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                   //根据业绩所在区间 查询比例
                                var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                if (rateModel != null)
                                {
                                    foreach (var qitem in sellOrderList)
                                    {
                                        //当前订单的业绩
                                        decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                        decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                        decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                        foreach (var emp in EmpList)
                                        {
                                            AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                            {
                                                EmpId = emp,
                                                GiveOutMoney = 0,
                                                GiveOutState = 2,
                                                Group_Id = userInfo.Group_Id,
                                                Id = 0,
                                                IsDept = 1,
                                                OrderId = qitem.OrderId,
                                                PeriodsId = 0,
                                                Rate = rateModel.Rate,
                                                PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                RuleId = item.Id,
                                                SaleMoney = YjMoney,
                                                OrderSaleMoney = orderYj,
                                                Type = 1,
                                                Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                            });
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            var consultantOrderList = orderList.Where(x => x.CourseConsultantId > 0 && ("," + item.ChildEmpIds + ",").Contains("," + x.CourseConsultantId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                            if (!string.IsNullOrEmpty(item.CourseIds))
                            {
                                if (item.CourseType == 1)
                                {
                                    consultantOrderList = consultantOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                                else
                                {
                                    consultantOrderList = consultantOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                            }
                            if (consultantOrderList.Any())
                            {
                                //课程顾问
                                //计算市场业绩
                                decimal TotalYj = consultantOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                //计算订单累计返佣
                                decimal bdMoney = bdList.Where(x => consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                //查询老师的提成
                                decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                   //根据业绩所在区间 查询比例
                                var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                if (rateModel != null)
                                {
                                    foreach (var qitem in consultantOrderList)
                                    {
                                        //当前订单的业绩
                                        decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                        decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                        decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                        foreach (var emp in EmpList)
                                        {
                                            AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                            {
                                                EmpId = emp,
                                                GiveOutMoney = 0,
                                                GiveOutState = 2,
                                                Group_Id = userInfo.Group_Id,
                                                Id = 0,
                                                IsDept = 1,
                                                OrderId = qitem.OrderId,
                                                PeriodsId = 0,
                                                Rate = rateModel.Rate,
                                                PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                RuleId = item.Id,
                                                SaleMoney = YjMoney,
                                                OrderSaleMoney = orderYj,
                                                Type = 2,
                                                Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (AchEmpList.Any()) {
                //先插入  拿到ID
                foreach (var item in AchEmpList)
                {
                    item.Id = sell_Achievements_EmpRepository.Insert(item);
                }
            }

            //查询历史未发放完毕的
            var oldAchEmpList = sell_Achievements_EmpRepository.GetList(new RB_Sell_Achievements_Emp_ViewModel() { Group_Id = userInfo.Group_Id, GiveOutState = 2, IsSelectNor = 1 });
            if (oldAchEmpList.Any()) {
                AchEmpList.AddRange(oldAchEmpList);
            }

            if (AchEmpList.Any())
            {
                #region 历史周期
                List<RB_Sell_Achievements_Periods_ViewModel> historyList = new List<RB_Sell_Achievements_Periods_ViewModel>();
                string periodsIds = string.Join(",", oldAchEmpList.Select(x => x.PeriodsId));
                if (!string.IsNullOrEmpty(periodsIds)) {
                    historyList = sell_Achievements_PeriodsRepository.GetList(new RB_Sell_Achievements_Periods_ViewModel() { Group_Id = userInfo.Group_Id, PeriodsIds = periodsIds });
                }
                #endregion

                #region 基础数据
                string orderIds = string.Join(",", AchEmpList.Select(x => x.OrderId).Distinct());
                orderList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel() { Group_Id = userInfo.Group_Id, QOrderIds = orderIds });
                //查询所有的人员
                var saleIdList = orderList.Where(x => x.EnterID > 0).Select(x => x.EnterID).Distinct().ToList();
                var teacherIdList = orderList.Where(x => x.HelpEnterId > 0).Select(x => x.HelpEnterId).Distinct().ToList();
                var consultantIdList = orderList.Where(x => x.CourseConsultantId > 0).Select(x => x.CourseConsultantId).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 });
                //查询订单下所有学生 已完成课时
                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_Achievements_DetailsRepository.GetList(new RB_Sell_Achievements_Details_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = orderIds });
                #endregion

                #region 提成明细
                List<RB_Sell_Achievements_Details_ViewModel> CurrentList = new List<RB_Sell_Achievements_Details_ViewModel>();//当期的提成数据
                foreach (var item in orderList)
                {
                    foreach (var AchModel in AchEmpList.Where(x => x.OrderId == item.OrderId))
                    {
                        var classModel = clist.Where(x => x.ClassId == item.ClassId).FirstOrDefault();
                        if (classModel == null) { continue; }
                        //当前已发提成
                        decimal SaleCommissioned = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == AchModel.EmpId && x.UserType == AchModel.Type && x.IsDept == AchModel.IsDept).Sum(x => x.CurrentPeriodMoney);

                        //订单应发提成 
                        decimal YFCommission = AchModel.PushMoney;
                        if (YFCommission == 0 && SaleCommissioned == 0)
                        {
                            continue;
                        }

                        #region 计算课时
                        var g3list = glist.Where(x => x.OrderId == item.OrderId).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

                        if (YFCommission == SaleCommissioned)
                        {
                            //正好提成已发放完成  直接更新 订单 已发放Ok
                            AchModel.GiveOutMoney = YFCommission;
                            AchModel.GiveOutState = 1;
                        }
                        else if (YFCommission < SaleCommissioned)
                        {
                            //可能因为调整应收   导致提成多发  需要补回来
                            decimal BMoney = YFCommission - SaleCommissioned;
                            CurrentList.Add(new RB_Sell_Achievements_Details_ViewModel()
                            {
                                UserId = AchModel.EmpId,
                                OrderId = item.OrderId,
                                CurrentPeriodMoney = BMoney,
                                IsDeduction = 1,
                                Remark = "当前提成应发：" + YFCommission + "，已实发：" + SaleCommissioned + "，应补金额：" + BMoney,

                                ClassId = item.ClassId,
                                ClassType = classModel.ClassType,
                                PeriodId = 0,
                                Periods = month,
                                CommissionMoney = YFCommission,
                                StudentCount = item.GuestNum,
                                TotalHours = Convert.ToInt32(TotalHours),
                                TotalLearn = Convert.ToInt32(TotalLearn),
                                CurrentHours = -1,//这种补提成的  没有课时消费
                                GiveOutMoney = SaleCommissioned,
                                FirstRate = 0,
                                DeductionMoney = 0,
                                IsDept = AchModel.IsDept,
                                UserType = AchModel.Type,
                                RelatedId = AchModel.Id
                            });

                            AchModel.GiveOutMoney = SaleCommissioned;
                            AchModel.GiveOutState = 2;
                        }
                        else
                        {
                            #region 班级提成
                            //查询是否订单下所有学员都已退学  
                            var g2list = glist.Where(x => x.OrderId == item.OrderId).ToList();
                            if (g2list.Where(x => x.GuestState == GuestStateEnum.DropOut).Count() == item.GuestNum)
                            {
                                //所有学生都退学了   直接计算提成  全部一次性发放
                                //销售全占
                                decimal BMoney = YFCommission - SaleCommissioned;
                                CurrentList.Add(new RB_Sell_Achievements_Details_ViewModel()
                                {
                                    UserId = AchModel.EmpId,
                                    OrderId = item.OrderId,
                                    CurrentPeriodMoney = BMoney,
                                    Remark = "当前订单学生退学，直接发放剩余提成：" + BMoney,

                                    ClassId = item.ClassId,
                                    ClassType = classModel.ClassType,
                                    PeriodId = 0,
                                    Periods = month,
                                    CommissionMoney = YFCommission,
                                    StudentCount = item.GuestNum,
                                    TotalHours = Convert.ToInt32(TotalHours),
                                    TotalLearn = Convert.ToInt32(TotalLearn),
                                    CurrentHours = -1,//这种补提成的  没有课时消费
                                    GiveOutMoney = SaleCommissioned,
                                    FirstRate = 0,
                                    DeductionMoney = 0,
                                    IsDept = AchModel.IsDept,
                                    UserType = AchModel.Type,
                                    RelatedId = AchModel.Id
                                });
                                AchModel.GiveOutMoney = YFCommission;
                                AchModel.GiveOutState = 1;
                            }
                            else
                            {
                                //查询当期所使用的规则
                                RB_Sell_Achievements_Rule_ViewModel ruleModel;
                                if (AchModel.PeriodsId > 0)
                                {
                                    var pmodel = historyList.Where(x => x.Id == AchModel.PeriodsId).FirstOrDefault();
                                    var rList = JsonHelper.DeserializeObject<List<RB_Sell_Achievements_Rule_ViewModel>>(pmodel.AdminRemark);
                                    ruleModel = rList.Where(x => x.Id == AchModel.RuleId).FirstOrDefault();
                                }
                                else
                                {
                                    ruleModel = rulelist.Where(x => x.Id == AchModel.RuleId).FirstOrDefault();
                                }
                                //验证是否满足  上课课时超15%
                                if (TotalLearn > TotalHours * (ruleModel.CourseRate /100))
                                {
                                    //查询该订单 已发提成记录
                                    //先查询销售的
                                    var salelist = dlist.Where(x => x.OrderId == item.OrderId && x.UserId == AchModel.EmpId && x.UserType == AchModel.Type && x.IsDept == AchModel.IsDept).ToList();
                                    if (salelist.Any())
                                    {
                                        SetCommissionNext(month, CheckList, CurrentList, item, classModel, TotalHours, YFCommission, salelist, AchModel, true);
                                    }
                                    else
                                    {
                                        //直接  发首次提成
                                        decimal FirstMoney = Math.Round(YFCommission * ruleModel.FirstRate / 100, 2, MidpointRounding.AwayFromZero);
                                        CurrentList.Add(new RB_Sell_Achievements_Details_ViewModel()
                                        {
                                            UserId = AchModel.EmpId,
                                            OrderId = item.OrderId,
                                            CurrentPeriodMoney = FirstMoney,
                                            IsFirstCommission = 1,
                                            Remark = "首次发放提成比例：" + ruleModel.FirstRate,

                                            ClassId = item.ClassId,
                                            ClassType = classModel.ClassType,
                                            PeriodId = 0,
                                            Periods = month,
                                            CommissionMoney = YFCommission,
                                            StudentCount = item.GuestNum,
                                            TotalHours = Convert.ToInt32(TotalHours),
                                            TotalLearn = Convert.ToInt32(TotalLearn),
                                            CurrentHours = -1,//这种首次发放提成的  没有课时消费
                                            GiveOutMoney = SaleCommissioned,
                                            FirstRate = ruleModel.FirstRate,
                                            DeductionMoney = 0,
                                            IsDept = AchModel.IsDept,
                                            UserType = AchModel.Type,
                                            RelatedId = AchModel.Id
                                        });
                                        AchModel.GiveOutMoney = FirstMoney;
                                        if (ruleModel.FirstRate == 100)
                                        {//这种直接发放全发
                                            AchModel.GiveOutState = 1;
                                        }
                                        else
                                        {
                                            AchModel.GiveOutState = 2;
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }
                #endregion

                #region 开始遍历
                List<RB_Sell_Achievements_Deduction_ViewModel> DeductionList = new List<RB_Sell_Achievements_Deduction_ViewModel>();//抵扣详情
                var NorList = CurrentList.Where(x => x.IsDeduction != 1).ToList();//正常的
                var DeList = CurrentList.Where(x => x.IsDeduction == 1).ToList();//需抵扣的   负数存的

                //遍历班级提成需抵扣的
                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)
                            {
                                //已经没有钱可以抵扣了  继续下一个 （班级提成  + 额外奖励）
                                continue;
                            }
                            if ((xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney) + (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney) >= 0)
                            {
                                //全部抵扣   用需抵扣
                                DeductionList.Add(new RB_Sell_Achievements_Deduction_ViewModel()
                                {
                                    OrderId = xdkitem.OrderId,
                                    SourceId = dkitem.OrderId,
                                    Type = 1,
                                    DeductionMoney = 0 - (xdkitem.CurrentPeriodMoney + xdkitem.DeductionMoney),
                                    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_Achievements_Deduction_ViewModel()
                                    {
                                        OrderId = xdkitem.OrderId,
                                        SourceId = dkitem.OrderId,
                                        Type = 1,
                                        DeductionMoney = (dkitem.CurrentPeriodMoney + dkitem.DeductionMoney),
                                        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);//存负数  表抵扣了这么多
                                }
                            }
                        }
                    }

                    xdkitem.CurrentPeriodMoney = 0 - xdkitem.DeductionMoney;//直接赋值  抵扣的负数  这样子 当期应发=0
                }
                #endregion

                #region 开始创建
                var trans = sell_Achievements_PeriodsRepository.DbTransaction;
                try
                {
                    int PeriodsId = sell_Achievements_PeriodsRepository.Insert(new RB_Sell_Achievements_Periods()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Financials = "",
                        Group_Id = userInfo.Group_Id,
                        Name = month + "期提成",
                        Periods = month,
                        SumPrice = 0,
                        AdminRemark = JsonHelper.Serialize(rulelist)
                    }, trans);
                    if (PeriodsId > 0)
                    {
                        foreach (var qitem in CurrentList)
                        {
                            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_Achievements_DetailsRepository.Insert(qitem, trans);
                        }

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

                        #region 抵扣的明细
                        DateTime dtNow = DateTime.Now;
                        foreach (var qitem in DeductionList)
                        {
                            qitem.PeriodsId = PeriodsId;
                            qitem.CreateBy = userInfo.Id;
                            qitem.CreateTime = dtNow;
                            sell_Achievements_DeductionRepository.Insert(qitem, trans);
                        }
                        #endregion
                    }
                    sell_Achievements_PeriodsRepository.DBSession.Commit();

                    #region 订单关联更新
                    //查询所有相关的提成明细
                    string oIds = string.Join(",", AchEmpList.Select(x => x.OrderId).Distinct());
                    var adList = sell_Achievements_DetailsRepository.GetList(new RB_Sell_Achievements_Details_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = oIds });
                    //再次查询
                    foreach (var item in AchEmpList) {
                        var TotalCommission = adList.Where(x => x.OrderId == item.OrderId && x.UserId == item.EmpId && x.UserType == item.Type && x.IsDept == item.IsDept).Sum(x => x.CurrentPeriodMoney);
                        item.GiveOutMoney = TotalCommission;
                        item.GiveOutState = 2;
                        if (item.PushMoney == item.GiveOutMoney) {
                            item.GiveOutState = 1;
                        }
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Sell_Achievements_Emp.GiveOutMoney), item.GiveOutMoney},
                            { nameof(RB_Sell_Achievements_Emp.GiveOutState), item.GiveOutState},
                        };
                        if (item.PeriodsId == 0) {
                            keyValues.Add(nameof(RB_Sell_Achievements_Emp.PeriodsId), PeriodsId);
                        }
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName = nameof(RB_Sell_Achievements_Emp.Id),
                                  FiledValue = item.Id,
                                   OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        sell_Achievements_EmpRepository.Update(keyValues, wheres);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetAchievementsCommissionInfo");
                    sell_Achievements_PeriodsRepository.DBSession.Rollback();
                    return "出错了，请联系管理员";
                }
                #endregion
            }

            return "";
        }

        #endregion

        #region 业绩效验
        /// <summary>
        /// 效验退款后 业绩提成是否达标
        /// </summary>
        /// <param name="orderId"></param>
        public bool ValidataAchievements(int orderId)
        {
            DateTime EnableDate = Convert.ToDateTime(Config.NewAchievementsEnable);
            //查询订单信息
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            if (orderModel.CreateTime < EnableDate) { return false; }
            //查询订单业绩关联
            var empList = sell_Achievements_EmpRepository.GetList(new RB_Sell_Achievements_Emp_ViewModel() { Group_Id = orderModel.Group_Id, OrderId = orderId });
            if (empList.Any()) {
                //查询业绩期数
                int PeriodsId = empList.FirstOrDefault().PeriodsId;
                var periodsModel = sell_Achievements_PeriodsRepository.GetEntity(PeriodsId);
                if (periodsModel == null) { return false; }
                var rulelist = JsonHelper.DeserializeObject<List<RB_Sell_Achievements_Rule_ViewModel>>(periodsModel.AdminRemark);
                //查询关联的所有订单
                var allList = sell_Achievements_EmpRepository.GetList(new RB_Sell_Achievements_Emp_ViewModel() { Group_Id = orderModel.Group_Id, PeriodsId = PeriodsId });
                string orderIds = string.Join(",", allList.Select(x => x.OrderId).Distinct());
                var orderList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel() { Group_Id = orderModel.Group_Id, QOrderIds = orderIds });
                //重新计算
                List<RB_Sell_Achievements_Emp_ViewModel> AchEmpList = new List<RB_Sell_Achievements_Emp_ViewModel>();//需要新增当月的
                if (orderList.Any())
                {
                    //首先查询 根据规则  适配当月业绩  并生成对应的  订单人员业绩提成                
                    foreach (var item in rulelist)
                    {
                        //初始化规则比列
                        item.RateList = new List<AchievementsRateModel>();
                        if (!string.IsNullOrEmpty(item.Content))
                        {
                            item.RateList = JsonHelper.DeserializeObject<List<AchievementsRateModel>>(item.Content);
                        }
                    }
                    //根据订单  查询同行返佣
                    orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                    var bdList = customer_BalanceDetailRepository.GetCustomerBalanceDetailListRepository(new Model.ViewModel.Customer.RB_Customer_BalanceDetail_ViewModel() { Group_Id = orderModel.Group_Id, QOrderIds = orderIds });

                    foreach (var item in rulelist.Where(x => x.Type == 3))
                    {
                        //老师适配规则
                        var teaOrderList = orderList.Where(x => x.HelpEnterId > 0 && ("," + item.EmpIds + ",").Contains("," + x.HelpEnterId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                        if (!string.IsNullOrEmpty(item.CourseIds))
                        {
                            if (item.CourseType == 1)
                            {
                                teaOrderList = teaOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                            }
                            else
                            {
                                teaOrderList = teaOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                            }
                        }
                        if (teaOrderList.Any())
                        {
                            //计算老师业绩
                            decimal TotalYj = teaOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                            //计算订单累计返佣
                            decimal bdMoney = bdList.Where(x => teaOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                            decimal YjMoney = TotalYj - bdMoney;//排除同行返佣
                                                                //根据业绩所在区间 查询比例
                            var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                            if (rateModel != null)
                            {
                                foreach (var qitem in teaOrderList)
                                {
                                    //当前订单的业绩
                                    decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                    decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission;
                                    AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                    {
                                        EmpId = qitem.HelpEnterId,
                                        GiveOutMoney = 0,
                                        GiveOutState = 2,
                                        Group_Id = orderModel.Group_Id,
                                        Id = 0,
                                        IsDept = 2,
                                        OrderId = qitem.OrderId,
                                        PeriodsId = 0,
                                        Rate = rateModel.Rate,
                                        PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                        RuleId = item.Id,
                                        SaleMoney = YjMoney,
                                        OrderSaleMoney = orderYj,
                                        Type = 3,
                                        Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；订单b2b返佣：" + bdCommission + "；订单业绩:" + orderYj
                                    });
                                }
                            }
                        }
                    }

                    foreach (var item in rulelist.Where(x => x.Type != 3))
                    {
                        if (string.IsNullOrEmpty(item.ChildEmpIds))
                        {
                            //非部门情况
                            //市场
                            if (item.Type == 1)
                            {
                                var sellOrderList = orderList.Where(x => x.EnterID > 0 && ("," + item.EmpIds + ",").Contains("," + x.EnterID + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                if (sellOrderList.Any())
                                {
                                    //计算市场业绩
                                    decimal TotalYj = sellOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                    //计算订单累计返佣
                                    decimal bdMoney = bdList.Where(x => sellOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                    //查询老师的提成
                                    decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && sellOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                    decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                       //根据业绩所在区间 查询比例
                                    var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                    if (rateModel != null)
                                    {
                                        foreach (var qitem in sellOrderList)
                                        {
                                            //当前订单的业绩
                                            decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                            decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                            decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                            AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                            {
                                                EmpId = qitem.EnterID,
                                                GiveOutMoney = 0,
                                                GiveOutState = 2,
                                                Group_Id = orderModel.Group_Id,
                                                Id = 0,
                                                IsDept = 2,
                                                OrderId = qitem.OrderId,
                                                PeriodsId = 0,
                                                Rate = rateModel.Rate,
                                                PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                RuleId = item.Id,
                                                SaleMoney = YjMoney,
                                                OrderSaleMoney = orderYj,
                                                Type = 1,
                                                Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                            });
                                        }
                                    }
                                }
                            }
                            //顾问
                            else
                            {
                                var consultantOrderList = orderList.Where(x => x.CourseConsultantId > 0 && ("," + item.EmpIds + ",").Contains("," + x.CourseConsultantId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                if (consultantOrderList.Any())
                                {
                                    //课程顾问
                                    //计算市场业绩
                                    decimal TotalYj = consultantOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                    //计算订单累计返佣
                                    decimal bdMoney = bdList.Where(x => consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                    //查询老师的提成
                                    decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                    decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                       //根据业绩所在区间 查询比例
                                    var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                    if (rateModel != null)
                                    {
                                        foreach (var qitem in consultantOrderList)
                                        {
                                            //当前订单的业绩
                                            decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                            decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                            decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                            AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                            {
                                                EmpId = qitem.CourseConsultantId,
                                                GiveOutMoney = 0,
                                                GiveOutState = 2,
                                                Group_Id = orderModel.Group_Id,
                                                Id = 0,
                                                IsDept = 2,
                                                OrderId = qitem.OrderId,
                                                PeriodsId = 0,
                                                Rate = rateModel.Rate,
                                                PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                RuleId = item.Id,
                                                SaleMoney = YjMoney,
                                                OrderSaleMoney = orderYj,
                                                Type = 2,
                                                Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                            });
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //部门情况
                            //部门领取提成人
                            List<int> EmpList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                            if (item.Type == 1)
                            {
                                var sellOrderList = orderList.Where(x => x.EnterID > 0 && ("," + item.ChildEmpIds + ",").Contains("," + x.EnterID + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                if (sellOrderList.Any())
                                {
                                    //计算市场业绩
                                    decimal TotalYj = sellOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                    //计算订单累计返佣
                                    decimal bdMoney = bdList.Where(x => sellOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                    //查询老师的提成
                                    decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && sellOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                    decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                       //根据业绩所在区间 查询比例
                                    var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                    if (rateModel != null)
                                    {
                                        foreach (var qitem in sellOrderList)
                                        {
                                            //当前订单的业绩
                                            decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                            decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                            decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                            foreach (var emp in EmpList)
                                            {
                                                AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                                {
                                                    EmpId = emp,
                                                    GiveOutMoney = 0,
                                                    GiveOutState = 2,
                                                    Group_Id = orderModel.Group_Id,
                                                    Id = 0,
                                                    IsDept = 1,
                                                    OrderId = qitem.OrderId,
                                                    PeriodsId = 0,
                                                    Rate = rateModel.Rate,
                                                    PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                    RuleId = item.Id,
                                                    SaleMoney = YjMoney,
                                                    OrderSaleMoney = orderYj,
                                                    Type = 1,
                                                    Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var consultantOrderList = orderList.Where(x => x.CourseConsultantId > 0 && ("," + item.ChildEmpIds + ",").Contains("," + x.CourseConsultantId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                if (consultantOrderList.Any())
                                {
                                    //课程顾问
                                    //计算市场业绩
                                    decimal TotalYj = consultantOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                    //计算订单累计返佣
                                    decimal bdMoney = bdList.Where(x => consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                    //查询老师的提成
                                    decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                    decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                       //根据业绩所在区间 查询比例
                                    var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                    if (rateModel != null)
                                    {
                                        foreach (var qitem in consultantOrderList)
                                        {
                                            //当前订单的业绩
                                            decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                            decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                            decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                            foreach (var emp in EmpList)
                                            {
                                                AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                                {
                                                    EmpId = emp,
                                                    GiveOutMoney = 0,
                                                    GiveOutState = 2,
                                                    Group_Id = orderModel.Group_Id,
                                                    Id = 0,
                                                    IsDept = 1,
                                                    OrderId = qitem.OrderId,
                                                    PeriodsId = 0,
                                                    Rate = rateModel.Rate,
                                                    PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                    RuleId = item.Id,
                                                    SaleMoney = YjMoney,
                                                    OrderSaleMoney = orderYj,
                                                    Type = 2,
                                                    Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //先验证是否掉档次了  没有掉档次的话  就当前订单处理  掉了就要整个处理
                foreach (var item in empList) {
                    var emodel = AchEmpList.Where(x => x.OrderId == item.OrderId && x.EmpId == item.EmpId && x.Type == item.Type && x.IsDept == item.IsDept).FirstOrDefault();
                    if (emodel == null) { continue; }//没查到那就不管了
                    if (emodel.Rate != item.Rate)
                    {
                        //比例变更  相关订单都要重新跑
                        var upList = allList.Where(x => x.EmpId == item.EmpId && x.Type == item.Type && x.IsDept == item.IsDept).ToList();
                        foreach (var qitem in upList) {
                            var ecmodel = AchEmpList.Where(x => x.OrderId == qitem.OrderId && x.EmpId == qitem.EmpId && x.Type == qitem.Type && x.IsDept == qitem.IsDept).FirstOrDefault();
                            if (ecmodel == null) { continue; }
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.PushMoney), ecmodel.PushMoney},
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.Rate), ecmodel.Rate},
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.SaleMoney), ecmodel.SaleMoney},
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.Remark), qitem.Remark +"；（订单"+orderId+"退款，导致当月业绩掉档，应发提成由'"+qitem.PushMoney+"'变成'"+ecmodel.PushMoney+"'；当月业绩由'"+qitem.SaleMoney+"'变成'"+ecmodel.SaleMoney+"'；提成比例由'"+qitem.Rate+"'变成'"+ecmodel.Rate+"'）"},
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.GiveOutState), 2},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_Sell_Achievements_Emp_ViewModel.Id),
                                      FiledValue = qitem.Id,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            sell_Achievements_EmpRepository.Update(keyValues, wheres);
                        }
                    }
                    else {
                        //比例未变更  对当前订单修改
                        if (item.PushMoney != emodel.PushMoney) {
                            //需要更新应发提成
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.PushMoney), emodel.PushMoney},
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.Remark), item.Remark +"；（订单"+orderId+"退款，应发提成由'"+item.PushMoney+"'变成'"+emodel.PushMoney+"'）"},
                                { nameof(RB_Sell_Achievements_Emp_ViewModel.GiveOutState), 2},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_Sell_Achievements_Emp_ViewModel.Id),
                                      FiledValue = item.Id,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            sell_Achievements_EmpRepository.Update(keyValues, wheres);
                        }
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 获取业绩变更日志
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="userType"></param>
        /// <param name="isDept"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string GetSellAchievementsChangeLog(int orderId, int userId, int userType, int isDept, int groupId, out string msg)
        {
            msg = "";
            var empModel = sell_Achievements_EmpRepository.GetList(new RB_Sell_Achievements_Emp_ViewModel() { Group_Id = groupId, OrderId = orderId, EmpId = userId, Type = userType, IsDept = isDept }).FirstOrDefault();
            if (empModel == null) {
                msg = "未查询到相关信息";
                return "";
            }
            return "业绩比例：" + empModel.Rate + "%；业绩描述：" + empModel.Remark;
        }
        #endregion

        #region 销售中心

        /// <summary>
        /// 获取销售中心业绩
        /// </summary>
        /// <param name="month"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetSellCenterAchievementsStatistics(string month, UserInfo userInfo)
        {
            List<RB_Sell_Achievements_Rule_ViewModel> rulelist = new List<RB_Sell_Achievements_Rule_ViewModel>();
            //获取当月期数
            var periodsModel = sell_Achievements_PeriodsRepository.GetList(new RB_Sell_Achievements_Periods_ViewModel() { Group_Id = userInfo.Group_Id, Periods = month }).FirstOrDefault();
            if (periodsModel == null)
            {
                //查询最新的提成规则
                rulelist = sell_Achievements_RuleRepository.GetList(new RB_Sell_Achievements_Rule_ViewModel() { Group_Id = userInfo.Group_Id });
            }
            else {
                rulelist = JsonHelper.DeserializeObject<List<RB_Sell_Achievements_Rule_ViewModel>>(periodsModel.AdminRemark);
            }
            //非部门规则
            var RuleModel = rulelist.Where(x => string.IsNullOrEmpty(x.ChildEmpIds) && ("," + x.EmpIds + ",").Contains("," + userInfo.Id + ",")).FirstOrDefault();
            if (RuleModel != null)
            {
                RuleModel.RateList = JsonHelper.DeserializeObject<List<AchievementsRateModel>>(RuleModel.Content);
            }

            decimal TotalSaleMoney = 0, NewSaleMoney = 0, RenewSaleMoney = 0;// 业绩  新收  续费
            decimal MonthCommission = 0;//当月提成金额
            //提成金额  累计提成  已发放  待发放；
            if (periodsModel == null)
            {
                //需要默认查询一次当月的
                #region 查询当月业绩

                string SchoolIds = string.Join(",", rulelist.Select(x => x.SchoolIds));

                //查询 班级订单  1.尾款收齐
                string SDate = Config.NewAchievementsEnable;
                string EDate = Convert.ToDateTime(month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
                var orderList = orderRepository.GetAllAchievementsSendOrderList(userInfo.Group_Id, SDate, EDate, 1, "", SchoolIds);//查询所有的
                List<RB_Sell_Achievements_Emp_ViewModel> AchEmpList = new List<RB_Sell_Achievements_Emp_ViewModel>();//需要新增当月的
                if (orderList.Any())
                {
                    //首先查询 根据规则  适配当月业绩  并生成对应的  订单人员业绩提成                
                    foreach (var item in rulelist)
                    {
                        //初始化规则比列
                        item.RateList = new List<AchievementsRateModel>();
                        if (!string.IsNullOrEmpty(item.Content))
                        {
                            item.RateList = JsonHelper.DeserializeObject<List<AchievementsRateModel>>(item.Content);
                        }
                    }
                    //根据订单  查询同行返佣
                    string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                    var bdList = customer_BalanceDetailRepository.GetCustomerBalanceDetailListRepository(new Model.ViewModel.Customer.RB_Customer_BalanceDetail_ViewModel() { Group_Id = userInfo.Group_Id, QOrderIds = orderIds });

                    if (RuleModel!=null&&RuleModel.Type == 3)
                    {
                        //当前匹配教师规则  只查询老师的业绩
                        foreach (var item in rulelist.Where(x => x.Id == RuleModel.Id))
                        {
                            //老师适配规则
                            var teaOrderList = orderList.Where(x => x.HelpEnterId > 0 && ("," + item.EmpIds + ",").Contains("," + x.HelpEnterId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                            if (!string.IsNullOrEmpty(item.CourseIds))
                            {
                                if (item.CourseType == 1)
                                {
                                    teaOrderList = teaOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                                else
                                {
                                    teaOrderList = teaOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                            }
                            if (teaOrderList.Any())
                            {
                                //计算老师业绩
                                decimal TotalYj = teaOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                //计算订单累计返佣
                                decimal bdMoney = bdList.Where(x => teaOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                decimal YjMoney = TotalYj - bdMoney;//排除同行返佣
                                                                    //根据业绩所在区间 查询比例
                                var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                if (rateModel != null)
                                {
                                    foreach (var qitem in teaOrderList)
                                    {
                                        //当前订单的业绩
                                        decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                        decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission;
                                        AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                        {
                                            EmpId = qitem.HelpEnterId,
                                            GiveOutMoney = 0,
                                            GiveOutState = 2,
                                            Group_Id = userInfo.Group_Id,
                                            Id = 0,
                                            IsDept = 2,
                                            OrderId = qitem.OrderId,
                                            PeriodsId = 0,
                                            Rate = rateModel.Rate,
                                            PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                            RuleId = item.Id,
                                            SaleMoney = YjMoney,
                                            OrderSaleMoney = orderYj,
                                            Type = 3,
                                            Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；订单b2b返佣：" + bdCommission + "；订单业绩:" + orderYj
                                        });
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //先查询出教师的  再查询适配规则的
                        foreach (var item in rulelist.Where(x => x.Type == 3))
                        {
                            //老师适配规则
                            var teaOrderList = orderList.Where(x => x.HelpEnterId > 0 && ("," + item.EmpIds + ",").Contains("," + x.HelpEnterId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                            if (!string.IsNullOrEmpty(item.CourseIds))
                            {
                                if (item.CourseType == 1)
                                {
                                    teaOrderList = teaOrderList.Where(x => ("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                                else
                                {
                                    teaOrderList = teaOrderList.Where(x => !("," + item.CourseIds + ",").Contains("," + x.CourseId + ",")).ToList();
                                }
                            }
                            if (teaOrderList.Any())
                            {
                                //计算老师业绩
                                decimal TotalYj = teaOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                //计算订单累计返佣
                                decimal bdMoney = bdList.Where(x => teaOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                decimal YjMoney = TotalYj - bdMoney;//排除同行返佣
                                                                    //根据业绩所在区间 查询比例
                                var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                if (rateModel != null)
                                {
                                    foreach (var qitem in teaOrderList)
                                    {
                                        //当前订单的业绩
                                        decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                        decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission;
                                        AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                        {
                                            EmpId = qitem.HelpEnterId,
                                            GiveOutMoney = 0,
                                            GiveOutState = 2,
                                            Group_Id = userInfo.Group_Id,
                                            Id = 0,
                                            IsDept = 2,
                                            OrderId = qitem.OrderId,
                                            PeriodsId = 0,
                                            Rate = rateModel.Rate,
                                            PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                            RuleId = item.Id,
                                            SaleMoney = YjMoney,
                                            OrderSaleMoney = orderYj,
                                            Type = 3,
                                            Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；订单b2b返佣：" + bdCommission + "；订单业绩:" + orderYj
                                        });
                                    }
                                }
                            }
                        }
                        //再查询当前用户的
                        foreach (var item in rulelist.Where(x => x.Id == (RuleModel?.Id??0)))
                        {
                            if (string.IsNullOrEmpty(item.ChildEmpIds))
                            {
                                //非部门情况
                                //市场
                                if (item.Type == 1)
                                {
                                    var sellOrderList = orderList.Where(x => x.EnterID > 0 && ("," + item.EmpIds + ",").Contains("," + x.EnterID + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                    if (sellOrderList.Any())
                                    {
                                        //计算市场业绩
                                        decimal TotalYj = sellOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                        //计算订单累计返佣
                                        decimal bdMoney = bdList.Where(x => sellOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                        //查询老师的提成
                                        decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && sellOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                        decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                           //根据业绩所在区间 查询比例
                                        var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                        if (rateModel != null)
                                        {
                                            foreach (var qitem in sellOrderList)
                                            {
                                                //当前订单的业绩
                                                decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                                decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                                decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                                AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                                {
                                                    EmpId = qitem.EnterID,
                                                    GiveOutMoney = 0,
                                                    GiveOutState = 2,
                                                    Group_Id = userInfo.Group_Id,
                                                    Id = 0,
                                                    IsDept = 2,
                                                    OrderId = qitem.OrderId,
                                                    PeriodsId = 0,
                                                    Rate = rateModel.Rate,
                                                    PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                    RuleId = item.Id,
                                                    SaleMoney = YjMoney,
                                                    OrderSaleMoney = orderYj,
                                                    Type = 1,
                                                    Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                                });
                                            }
                                        }
                                    }
                                }
                                //顾问
                                else
                                {
                                    var consultantOrderList = orderList.Where(x => x.CourseConsultantId > 0 && ("," + item.EmpIds + ",").Contains("," + x.CourseConsultantId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                    if (consultantOrderList.Any())
                                    {
                                        //课程顾问
                                        //计算市场业绩
                                        decimal TotalYj = consultantOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                        //计算订单累计返佣
                                        decimal bdMoney = bdList.Where(x => consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                        //查询老师的提成
                                        decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                        decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                           //根据业绩所在区间 查询比例
                                        var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                        if (rateModel != null)
                                        {
                                            foreach (var qitem in consultantOrderList)
                                            {
                                                //当前订单的业绩
                                                decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                                decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                                decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                                AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                                {
                                                    EmpId = qitem.CourseConsultantId,
                                                    GiveOutMoney = 0,
                                                    GiveOutState = 2,
                                                    Group_Id = userInfo.Group_Id,
                                                    Id = 0,
                                                    IsDept = 2,
                                                    OrderId = qitem.OrderId,
                                                    PeriodsId = 0,
                                                    Rate = rateModel.Rate,
                                                    PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                    RuleId = item.Id,
                                                    SaleMoney = YjMoney,
                                                    OrderSaleMoney = orderYj,
                                                    Type = 2,
                                                    Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //部门情况
                                //部门领取提成人
                                List<int> EmpList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                                if (item.Type == 1)
                                {
                                    var sellOrderList = orderList.Where(x => x.EnterID > 0 && ("," + item.ChildEmpIds + ",").Contains("," + x.EnterID + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                    if (sellOrderList.Any())
                                    {
                                        //计算市场业绩
                                        decimal TotalYj = sellOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                        //计算订单累计返佣
                                        decimal bdMoney = bdList.Where(x => sellOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                        //查询老师的提成
                                        decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && sellOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                        decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                           //根据业绩所在区间 查询比例
                                        var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                        if (rateModel != null)
                                        {
                                            foreach (var qitem in sellOrderList)
                                            {
                                                //当前订单的业绩
                                                decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                                decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                                decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                                foreach (var emp in EmpList)
                                                {
                                                    AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                                    {
                                                        EmpId = emp,
                                                        GiveOutMoney = 0,
                                                        GiveOutState = 2,
                                                        Group_Id = userInfo.Group_Id,
                                                        Id = 0,
                                                        IsDept = 1,
                                                        OrderId = qitem.OrderId,
                                                        PeriodsId = 0,
                                                        Rate = rateModel.Rate,
                                                        PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                        RuleId = item.Id,
                                                        SaleMoney = YjMoney,
                                                        OrderSaleMoney = orderYj,
                                                        Type = 1,
                                                        Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    var consultantOrderList = orderList.Where(x => x.CourseConsultantId > 0 && ("," + item.ChildEmpIds + ",").Contains("," + x.CourseConsultantId + ",") && ("," + item.SchoolIds + ",").Contains("," + x.ClassSchoolId + ",")).ToList();
                                    if (consultantOrderList.Any())
                                    {
                                        //课程顾问
                                        //计算市场业绩
                                        decimal TotalYj = consultantOrderList.Sum(x => x.PreferPrice - x.DiscountMoney);
                                        //计算订单累计返佣
                                        decimal bdMoney = bdList.Where(x => consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId) && x.BalanceType == 1).Sum(x => x.Money);
                                        //查询老师的提成
                                        decimal teacherMoney = AchEmpList.Where(x => x.Type == 3 && consultantOrderList.Select(y => y.OrderId).Contains(x.OrderId)).Sum(x => x.PushMoney);
                                        decimal YjMoney = TotalYj - bdMoney - teacherMoney;//排除同行返佣 老师的提成
                                                                                           //根据业绩所在区间 查询比例
                                        var rateModel = item.RateList.Where(x => x.StartValue < YjMoney && (x.EndValue >= YjMoney || x.EndValue == -1)).FirstOrDefault();
                                        if (rateModel != null)
                                        {
                                            foreach (var qitem in consultantOrderList)
                                            {
                                                //当前订单的业绩
                                                decimal bdCommission = bdList.Where(x => x.OrderId == qitem.OrderId && x.BalanceType == 1).Sum(x => x.Money);
                                                decimal tCommission = AchEmpList.Where(x => x.Type == 3 && x.OrderId == qitem.OrderId).Sum(x => x.PushMoney);
                                                decimal orderYj = qitem.PreferPrice - qitem.DiscountMoney - bdCommission - tCommission;
                                                foreach (var emp in EmpList)
                                                {
                                                    AchEmpList.Add(new RB_Sell_Achievements_Emp_ViewModel()
                                                    {
                                                        EmpId = emp,
                                                        GiveOutMoney = 0,
                                                        GiveOutState = 2,
                                                        Group_Id = userInfo.Group_Id,
                                                        Id = 0,
                                                        IsDept = 1,
                                                        OrderId = qitem.OrderId,
                                                        PeriodsId = 0,
                                                        Rate = rateModel.Rate,
                                                        PushMoney = Math.Round(orderYj * rateModel.Rate / 100, 2, MidpointRounding.AwayFromZero),
                                                        RuleId = item.Id,
                                                        SaleMoney = YjMoney,
                                                        OrderSaleMoney = orderYj,
                                                        Type = 2,
                                                        Remark = "当月业绩：" + TotalYj + "；当月B2B返佣：" + bdMoney + "；当月老师提成：" + teacherMoney + "；订单b2b返佣：" + bdCommission + "；订单老师提成：" + tCommission + "；订单业绩:" + orderYj
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    var empList = AchEmpList.Where(x => x.EmpId == userInfo.Id).ToList();
                    //当月提成
                    MonthCommission = empList.Sum(x => x.PushMoney);
                    TotalSaleMoney = empList.FirstOrDefault()?.SaleMoney ?? 0;
                    //查询当月订单  新收  续费
                    string goIds = string.Join(",", empList.Select(x => x.OrderId).Distinct());
                    var glist = order_GuestRepository.GetSingleListRepository(new RB_Order_Guest_ViewModel() { Group_Id = userInfo.Group_Id, OrderIds = goIds });

                    NewSaleMoney = empList.Where(x => glist.Where(z => z.RenewState != 2).Select(z => z.OrderId).Contains(x.OrderId)).Sum(x => x.OrderSaleMoney);
                    RenewSaleMoney = empList.Where(x => glist.Where(z => z.RenewState == 2).Select(z => z.OrderId).Contains(x.OrderId)).Sum(x => x.OrderSaleMoney);
                }

                #endregion

            }
            else {
                var emoModel = sell_Achievements_EmpRepository.GetMonthSaleMoney(userInfo.Id, periodsModel.Id, userInfo.Group_Id);
                //查询本月提成
                MonthCommission = emoModel.PushMoney;
                //查询本月交易额
                TotalSaleMoney = emoModel.SaleMoney;
                //查询本月订单  新收  续费  退费
                var orderList = sell_Achievements_EmpRepository.GetMonthNorOrderMoney(userInfo.Id, periodsModel.Id, userInfo.Group_Id);
                NewSaleMoney = orderList.Where(x => x.Type != 2).FirstOrDefault()?.OrderSaleMoney ?? 0;
                RenewSaleMoney = orderList.Where(x => x.Type == 2).FirstOrDefault()?.OrderSaleMoney ?? 0;
            }

            //查询累计提成  已发放  待发放
            var empTModel = sell_Achievements_EmpRepository.GetEmpTotalCommission(userInfo.Id, userInfo.Group_Id);
            decimal TotalCommission = empTModel.PushMoney;
            decimal GiveOutCommission = empTModel.GiveOutMoney;
            decimal WaitCommission = TotalCommission - GiveOutCommission;

            return new
            {
                TotalSaleMoney,
                NewSaleMoney,
                RenewSaleMoney,
                MonthCommission,
                TotalCommission,
                GiveOutCommission,
                WaitCommission,
                RateList = RuleModel?.RateList ?? new List<AchievementsRateModel>()
            };
        }

        /// <summary>
        /// 获取我的提成发放分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Sell_Achievements_Emp_ViewModel> GetAchievementsEmpPageList(int pageIndex, int pageSize, out long count, RB_Sell_Achievements_Emp_ViewModel demodel)
        {
            var list = sell_Achievements_EmpRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }
        #endregion
    }
}
