using Edu.Model.ViewModel.Sell;
using Edu.Repository.Bonus;
using Edu.Repository.Sell;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Edu.Model.Entity.Bonus;
using Edu.Model.ViewModel.Bonus;
using Edu.Common.Plugin;
using VT.FW.DB;
using Edu.Repository.User;
using Edu.Model.CacheModel;
using Edu.AOP.CustomerAttribute;
using Edu.Model.ViewModel.User;
using Edu.Repository.Finance;
using Edu.Model.ViewModel.Finance;
using Edu.Repository.Course;

namespace Edu.Module.Course
{
    /// <summary>
    /// 员工月度人头奖金处理类
    /// </summary>
    public class EmployeeBonusModule
    {
        /// <summary>
        ///  课程顾问、市场达标奖金配置仓储层对象
        /// </summary>
        private readonly RB_Bonus_PlanRepository bonus_PlanRepository = new RB_Bonus_PlanRepository();

        /// <summary>
        /// 员工人头奖励仓储层对象
        /// </summary>
        private readonly RB_Personnel_BonusRepository personnel_BonusRepository = new RB_Personnel_BonusRepository();

        /// <summary>
        /// 员工人头奖励抵扣详情仓储层对象
        /// </summary>
        private readonly RB_Personnel_DeductionRepository personnel_DeductionRepository = new RB_Personnel_DeductionRepository();

        /// <summary>
        /// 员工人头奖励详情仓储层对象
        /// </summary>
        private readonly RB_Personnel_BonusDetailRepository personnel_BonusDetailRepository = new RB_Personnel_BonusDetailRepository();

        /// <summary>
        /// 人头奖金日志仓储层对象
        /// </summary>
        private readonly RB_Personnel_BonusLogRepository personnel_BonusLogRepository = new RB_Personnel_BonusLogRepository();

        /// <summary>
        /// 订单仓储层对象
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();

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

        /// <summary>
        /// 员工人头奖金仓储层对象
        /// </summary>
        private readonly RB_Personnel_PeriodRepository personnel_PeriodRepository = new RB_Personnel_PeriodRepository();

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

        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();

        /// <summary>
        /// 课程仓储层对象
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();


        /// <summary>
        /// 获取人头奖金期数分页列表
        /// </summary>
        /// <param name="pageIdex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Personnel_Period_Extend> GetPersonnelPeriodPageModule(int pageIdex, int pageSize, out long rowsCount, RB_Personnel_Period_Extend query)
        {
            var list = personnel_PeriodRepository.GetPersonnelPeriodPageRepository(pageIdex, pageSize, out rowsCount, query);
            if (list != null)
            {
                string ids = string.Join(",", list.Select(qitem => qitem.Id));
                var bonusList = personnel_BonusRepository.GetPersonnelBonusListRepository(new RB_Personnel_Bonus_Extend()
                {
                    QPeriodIds = ids
                });
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (bonusList != null && bonusList.Count > 0)
                {
                    string empIds = string.Join(",", bonusList.Select(qitem => qitem.EmployeeId));
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
                    {
                        QIds = empIds
                    });
                }
                string periodsIds = string.Join(",", list.Select(x => x.Id));
                var financeList = financeRepository.GetListSingle(new RB_Finance_Extend() { RB_Group_Id = query.Group_Id, FinanceType = 2, OtherType = 51, ReFinanceIds = ids, IsSelectNormal = 1 });
                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);
                    }
                    var tempList = bonusList?.Where(qitem => qitem.PeriodId == item.Id)?.ToList();
                    if (tempList != null && tempList.Count > 0)
                    {
                        foreach (var subItem in tempList)
                        {
                            subItem.EmployeeName = empList?.Where(qitem => qitem.Id == subItem.EmployeeId)?.FirstOrDefault()?.EmployeeName ?? "";
                        }
                    }
                    item.SumPrice = tempList?.Sum(qitem => qitem.CurRewardMoney + qitem.ClueNumSalary + qitem.OpenBonus - qitem.BeforeMoney) ?? 0;
                    item.BonusList = tempList;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取员工人头奖励分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Personnel_Bonus_Extend> GetPersonnelBonusPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Personnel_Bonus_Extend query)
        {
            var list = personnel_BonusRepository.GetPersonnelBonusPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string Ids = string.Join(",", list.Select(qitem => qitem.Id));
                var detailList = personnel_BonusDetailRepository.GetPersonnelBonusDetailListRepository(new RB_Personnel_BonusDetail_Extend()
                {
                    QBonusIds = Ids
                });
                var deductionList = personnel_DeductionRepository.GetPersonnelBonusListRepository(new RB_Personnel_Deduction_Extend()
                {
                    QBonusIds = Ids
                });
                var logList = personnel_BonusLogRepository.GetPersonnelBonusLogListRepository(new RB_Personnel_BonusLog_Extend()
                {
                    QBonusIds = Ids
                });
                foreach (var item in list)
                {
                    item.DetailList = detailList?.Where(qitem => qitem.BonusId == item.Id)?.ToList();
                    item.DeductionList = deductionList?.Where(qitem => qitem.BonusId == item.Id)?.ToList();
                    item.BonusLogList = logList?.Where(qitem => qitem.BonusId == item.Id)?.ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 生成业绩
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="sDate"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool CreateEmployeeBonusModule(UserInfo userInfo, out string message, string sDate = "")
        {
            message = "";
            bool flag = false;
            DateTime d1 = DateTime.Now;
            if (!string.IsNullOrEmpty(sDate))
            {
                var tempDate = Convert.ToDateTime(sDate);
                d1 = new DateTime(tempDate.Year, tempDate.Month, 1);
            }
            else
            {
                d1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            }
            string startDate = Common.ConvertHelper.FormatDate(d1);
            DateTime endTime = d1.AddMonths(1).AddDays(-1);
            string endDate = Common.ConvertHelper.FormatDate(endTime);
            var empPeriod = new RB_Personnel_Period()
            {
                Name = string.Format("{0}-{1}期人头奖励", endTime.Year, endTime.Month),
                Periods = string.Format("{0}-{1}", endTime.Year, endTime.Month),
                CreateBy = userInfo.Id,
                CreateTime = DateTime.Now,
                SumPrice = 0,
                Group_Id = userInfo.Group_Id,
                Financials = "",
                EmpIds = "",
                Remark = "",
            };
            var newId = personnel_PeriodRepository.Insert(empPeriod);
            empPeriod.Id = newId;
            flag = newId > 0;
            if (flag)
            {
                //人头配置列表
                var planList = bonus_PlanRepository.GetBounsPlanListRepository(new RB_Bonus_PlanExtend()
                {
                    Group_Id = userInfo.Group_Id
                }, isGetDetail: true);
                if (planList == null || (planList != null && planList.Count <= 0))
                {
                    flag = false;
                    message = "请先配置市场人员和课程顾问的提成配置";
                    return flag;
                }
                foreach (var item in planList)
                {
                    var saleList = Common.ConvertHelper.StringToList(item.SaleIds);
                    foreach (var saleId in saleList)
                    {
                        CalcPersionBonusModule(empPeriod, item, userInfo.Group_Id, startDate, endDate, saleId);
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 修改人头奖励发放状态
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="Month"></param>
        /// <param name="EmployeeId"></param>
        /// <returns></returns>
        public bool SetEmployeeBounsIsIssueModule(string Ids)
        {
           return  personnel_BonusRepository.SetEmployeeBounsIsIssueRepository(Ids);
        }

        /// <summary>
        /// 订单退款变更
        /// </summary>
        public void ChangeEmployeeBonusModule(int orderId)
        {
            //待冲抵金额
            decimal deductionMoney = 0;
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel != null)
            {
                //查询销售已发放的奖励
                var saleBonusList = personnel_BonusRepository.GetPersonnelBonusListRepository(new RB_Personnel_Bonus_Extend()
                {
                    QEmployeeIds = orderModel.EnterID.ToString() + "," + (orderModel?.CourseConsultantId ?? 0).ToString(),
                    YearNum = orderModel.CreateTime.Year,
                    MonthNum = orderModel.CreateTime.Month,
                });
                if (saleBonusList != null && saleBonusList.Count > 0)
                {
                    //人头配置列表
                    var planList = bonus_PlanRepository.GetBounsPlanListRepository(new RB_Bonus_PlanExtend()
                    {
                        Group_Id = orderModel.Group_Id
                    }, isGetDetail: true);

                    foreach (var sItem in saleBonusList)
                    {
                        var planModel = planList?.Where(qitem => qitem.Id == sItem.PlanId)?.FirstOrDefault();
                        foreach (var dItem in sItem.DetailList)
                        {
                            Dictionary<string, object> detailFileds = new Dictionary<string, object>();
                            detailFileds.Clear();
                            var tempCurMonthOrder = orderModel;
                            if (dItem.OrderId == orderModel.OrderId)
                            {
                                var newMoney = tempCurMonthOrder.Income - tempCurMonthOrder.Refund - tempCurMonthOrder.PlatformTax;
                                detailFileds.Add(nameof(RB_Personnel_BonusDetail_Extend.OrderGuestNum), 0);
                                detailFileds.Add(nameof(RB_Personnel_BonusDetail_Extend.OrderMoney), newMoney);
                                detailFileds.Add(nameof(RB_Personnel_BonusDetail_Extend.OrderState), orderModel.OrderState);
                                string _log1 = $"订单号【{dItem.OrderId}】的订单状态由:{dItem.OrderState.ToName()}=>{tempCurMonthOrder?.OrderState.ToName()}" +
                                    $"订单人数由:{dItem.OrderGuestNum}=>0,订单金额由:{dItem.OrderMoney}=>{newMoney}"
                                    ;
                                personnel_BonusLogRepository.AddPersonnelBonusLogRepository(sItem.Id, 1, dItem.OrderId, _log1);
                                dItem.OrderGuestNum = 0;
                                dItem.OrderMoney = newMoney;
                                dItem.OrderState = orderModel.OrderState;
                            }
                            if (detailFileds != null && detailFileds.Count > 0)
                            {
                                personnel_BonusDetailRepository.Update(detailFileds, new WhereHelper(nameof(RB_Personnel_BonusDetail_Extend.Id), dItem.Id));
                            }
                        }

                        //当月有效订单数量
                        bool isNormalOrder = sItem.DetailList.Where(qitem => qitem.OrderState == Common.Enum.Course.OrderStateEnum.Normal).Count() > 0;

                        var sumNum = sItem?.DetailList?.Sum(qitem => qitem.OrderGuestNum) ?? 0;
                        var sumOrderMoney = sItem?.DetailList?.Sum(qitem => qitem.OrderMoney);
                        //历史人头提成方案
                        var hisModel = Common.Plugin.JsonHelper.DeserializeObject<CurrentMonthBonusData>(sItem.HisBonusData);
                        var curRewardMoney = GetHisStepAwardAmount(hisModel, sumNum);
                        deductionMoney = sItem.CurRewardMoney - curRewardMoney;
                        //修改已发放
                        string _bonusLog = $"订单号变更:完成人数:{sItem.CurGuestNum}=>{sumNum},订单完成金额由:{sItem.CurOrderMoney}=>{sumOrderMoney}"
                                + $"奖励金额由:{sItem.CurRewardMoney}=>{curRewardMoney}"
                                  ;
                        Dictionary<string, object> bonusFileds = new Dictionary<string, object>()
                        {
                            {nameof(RB_Personnel_Bonus.CurGuestNum),sumNum },
                            {nameof(RB_Personnel_Bonus.CurOrderMoney),sumOrderMoney },
                            {nameof(RB_Personnel_Bonus.IsReach),(sumOrderMoney>hisModel.MonthGoalMoney?1:0) },
                        };
                        decimal newOpenBonus = 0;
                        //当月有开单奖金且没有有效订单
                        if (sItem.OpenBonus > 0 && !isNormalOrder)
                        {
                            newOpenBonus = sItem.OpenBonus;
                            _bonusLog += $",开单奖金由：{sItem.OpenBonus}=>0";
                        }
                        bonusFileds.Add(nameof(RB_Personnel_Bonus.DeductionMoney), deductionMoney + newOpenBonus);
                        personnel_BonusRepository.Update(bonusFileds, new WhereHelper(nameof(RB_Personnel_Bonus.Id), sItem.Id));
                        personnel_BonusLogRepository.AddPersonnelBonusLogRepository(sItem.Id, 1, 0, _bonusLog);
                    }
                }
            }
        }

        /// <summary>
        /// 获取历史梯度奖励金额
        /// </summary>
        /// <param name="item"></param>
        /// <param name="GuestNum"></param>
        /// <returns></returns>
        private decimal GetHisStepAwardAmount(CurrentMonthBonusData item, int GuestNum)
        {
            decimal awardAmount = 0;
            if (item != null && item.DetailList != null && item.DetailList.Count > 0)
            {
                for (var i = 0; i < item.DetailList.Count; i++)
                {
                    var tempNum = item.DetailList[i];
                    if (tempNum.StartNum <= GuestNum && GuestNum <= tempNum.EndNum)
                    {
                        awardAmount = tempNum.Money;
                    }
                }
            }
            return awardAmount;
        }

        /// <summary>
        /// 计算人员业绩
        /// </summary>
        /// <param name="item"></param>
        /// <param name="GroupId"></param>
        /// <param name="endDate"></param>
        /// <param name="saleId"></param>
        private void CalcPersionBonusModule(RB_Personnel_Period period, RB_Bonus_PlanExtend item, int GroupId, string startDate, string endDate, int saleId)
        {
          
            var orderList = GetSaleOrderList(item, GroupId,startDate,endDate, saleId, out List<RB_Order_ViewModel> allOrderList,out int IsOpenOrder);
            var curNum = orderList?.Where(qitem => !item.NotUseCourseIds.Contains(qitem.CourseId.ToString())).Sum(qitem => qitem.GuestNum) ?? 0;
            var curOrderMoney = orderList?.Where(qitem=>!item.NotUseCourseIds.Contains(qitem.CourseId.ToString())).Sum(qitem => qitem.OrderMoney) ?? 0;

            //查询未平账的人员
            var saleBonusList = personnel_BonusRepository.GetPersonnelBonusListRepository(new RB_Personnel_Bonus_Extend()
            {
                EmployeeId = saleId,
                PlanType = item.PlanType,
                IsNoBalance = 1,
            });
            //计算差额
            var chaE = saleBonusList?.Sum(qitem => qitem.DeductionMoney - qitem.FinishDeductionMoney) ?? 0;

            decimal DeductionMoney = 0;
            var ClueCount = studentRepository.GetStudentStaticRepository(saleId.ToString(), startDate, endDate)?.Sum(qitem=>qitem.ClueCount)??0;
            //新增当月的人头奖励
            var pModel = new RB_Personnel_Bonus()
            {
                Id = 0,
                PeriodId = period.Id,
                PlanId = item.Id,
                PlanType = item.PlanType,
                YearNum = Convert.ToDateTime(startDate).Year,
                MonthNum = Convert.ToDateTime(startDate).Month,
                EmployeeId = saleId,
                CurGuestNum = curNum,
                CurOrderMoney = curOrderMoney,
                Group_Id = GroupId,
                CurRewardMoney = GetStepAwardAmount(item, curNum),
                CreateBy = 1,
                CreateTime = DateTime.Now,
                UpdateBy = 1,
                UpdateTime = DateTime.Now,
                DeductionMoney = DeductionMoney,
                OpenBonus = IsOpenOrder > 0 ? item.OpenBonus : 0,
                ClueNum = ClueCount,
                ClueNumSalary = ClueCount > 5 ? item.ClueNumSalary : 0,
                IsIssue = 0
            };
            pModel.IsReach = pModel.CurOrderMoney > item.MonthGoalMoney ? 1 : 0;

            //历史提成数据
            var CurrentMonthBonusData = new CurrentMonthBonusData()
            {
                OpenBonus = item.OpenBonus,
                ClueNumSalary = item.ClueNumSalary,
                MonthGoalMoney = item.MonthGoalMoney,
                DetailList = new List<CurrentMonthBonusDataDetails>()
            };
            foreach (var sItem in item.DetailList)
            {
                CurrentMonthBonusData.DetailList.Add(new CurrentMonthBonusDataDetails()
                {
                    StartNum = sItem.StartNum,
                    EndNum = sItem.EndNum,
                    Money = sItem.Money
                });
            }
            pModel.HisBonusData = Common.Plugin.JsonHelper.Serialize(CurrentMonthBonusData);

            //当月总业绩
            var totalMoney = (pModel.CurRewardMoney + pModel.OpenBonus + pModel.ClueNumSalary);
            if (totalMoney >= chaE)
            {
                pModel.BeforeMoney = chaE;
            }
            else
            {
                pModel.BeforeMoney = totalMoney;
            }
            var newId = personnel_BonusRepository.Insert(pModel);
            pModel.Id = newId;
            //写抵扣记录表信息
            if (pModel.BeforeMoney > 0)
            {
                decimal tempChaE = chaE;
                foreach (var sItem in saleBonusList)
                {
                    if (tempChaE > 0)
                    {
                        if (sItem.DeductionMoney <= tempChaE)
                        {
                            var deductionModel = new RB_Personnel_Deduction()
                            {
                                BonusId = sItem.Id,
                                CreateBy = 1,
                                CreateTime = DateTime.Now,
                                DeductionMoney = sItem.DeductionMoney,
                                DeductionContent = "抵扣" + sItem.YearNum + "年" + sItem.MonthNum + "月的待抵扣金额" + sItem.DeductionMoney,
                            };
                            personnel_DeductionRepository.Insert(deductionModel);
                            Dictionary<string, object> fileds = new Dictionary<string, object>()
                            {
                                {nameof(RB_Personnel_Bonus_Extend.FinishDeductionMoney),(sItem?.FinishDeductionMoney??0)+sItem.DeductionMoney }
                            };
                            personnel_BonusRepository.Update(fileds, new WhereHelper(nameof(RB_Personnel_Bonus_Extend.Id), sItem.Id));
                            //冲抵以前日志
                            string logContent = pModel.YearNum + "年" + pModel.MonthNum + "月,完成抵扣金额" + sItem.DeductionMoney;
                            personnel_BonusLogRepository.AddPersonnelBonusLogRepository(sItem.Id, 1, 0, logContent);

                            //添加本月的日志
                            string logContent2 = "抵扣" + sItem.YearNum + "年" + sItem.MonthNum + "月, 人头奖励" + sItem.DeductionMoney;
                            personnel_BonusLogRepository.AddPersonnelBonusLogRepository(pModel.Id, 1, 0, logContent2);
                            tempChaE -= sItem.DeductionMoney;
                        }
                        else
                        {
                            var deductionModel = new RB_Personnel_Deduction()
                            {
                                BonusId = sItem.Id,
                                CreateBy = 1,
                                CreateTime = DateTime.Now,
                                DeductionMoney = tempChaE,
                                DeductionContent = "抵扣" + sItem.YearNum + "年" + sItem.MonthNum + "月超出金额" + tempChaE + "元.",
                            };
                            personnel_DeductionRepository.Insert(deductionModel);
                            Dictionary<string, object> fileds = new Dictionary<string, object>()
                            {
                                {nameof(RB_Personnel_Bonus_Extend.FinishDeductionMoney),(sItem?.FinishDeductionMoney??0)+tempChaE }
                            };
                            personnel_BonusRepository.Update(fileds, new WhereHelper(nameof(RB_Personnel_Bonus_Extend.Id), sItem.Id));
                            string logContent = pModel.YearNum + "年" + pModel.MonthNum + "月,抵扣金额" + tempChaE;
                            personnel_BonusLogRepository.AddPersonnelBonusLogRepository(sItem.Id, 1, 0, logContent);

                            //添加本月的日志
                            string logContent2 = "抵扣" + sItem.YearNum + "年" + sItem.MonthNum + "月, 人头奖励" + tempChaE;
                            personnel_BonusLogRepository.AddPersonnelBonusLogRepository(pModel.Id, 1, 0, logContent2);
                            tempChaE = 0;
                        }
                    }
                }
            }

            foreach (var oItem in allOrderList)
            {
                var detailModel = new RB_Personnel_BonusDetail()
                {
                    Id = 0,
                    BonusId = pModel.Id,
                    OrderId = oItem.OrderId,
                    OrderState = oItem.OrderState,
                    OrderMoney = oItem.Income - oItem.Refund - oItem.PlatformTax,
                    OrderGuestNum = oItem.GuestNum,
                    Remarks = (item.NotUseCourseIds.Contains(oItem.CourseId.ToString()) ? "【不适用】" : "") + courseRepository.GetEntity(oItem.CourseId)?.CourseName ?? "",
                };
                var newDetailId = personnel_BonusDetailRepository.Insert(detailModel);
                detailModel.Id = newDetailId;
            }
        }


        /// <summary>
        /// 获取梯度奖励金额
        /// </summary>
        /// <param name="item"></param>
        /// <param name="GuestNum"></param>
        /// <returns></returns>
        private decimal GetStepAwardAmount(RB_Bonus_PlanExtend item, int GuestNum)
        {
            decimal awardAmount = 0;
            if (item != null && item.DetailList != null && item.DetailList.Count > 0)
            {
                for (var i = 0; i < item.DetailList.Count; i++)
                {
                    var tempNum = item.DetailList[i];
                    if (tempNum.StartNum <= GuestNum && GuestNum <= tempNum.EndNum)
                    {
                        awardAmount = tempNum.Money;
                    }
                }
            }
            return awardAmount;
        }

        /// <summary>
        /// 获取当前人员订单列表
        /// </summary>
        /// <param name="item"></param>
        /// <param name="GroupId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="SaleId"></param>
        /// <param name="orderList"></param>
        /// <param name="isOpenOrder">是否有开单</param>
        /// <returns></returns>
        private List<PersionOrderItem> GetSaleOrderList(RB_Bonus_PlanExtend item, int GroupId,string startDate,string endDate, int SaleId, out List<RB_Order_ViewModel> orderList,out int isOpenOrder)
        {
            List<PersionOrderItem> list = new List<PersionOrderItem>();
            //所有当前人员订单列表
            orderList = orderRepository.GetAllBonusOrderListRepository(GroupId, startDate, endDate, item.PlanType, SaleId);
            //适用课程
            if (!string.IsNullOrEmpty(item.UseCourseIds))
            {
                orderList = orderList?.Where(qitem => item.UseCourseIds.Contains(qitem.CourseId.ToString()))?.ToList();
            }
            isOpenOrder= orderList.Count>0?1:0;
            
            //按照年份、月份统计订单人数和金额
            var groupList = orderList
                 .GroupBy(qitem => new { qitem.CreateTime.Year, qitem.CreateTime.Month,qitem.CourseId, })
                 .Select(qitem => new
                 {
                     qitem.Key.Year,
                     qitem.Key.Month,
                     qitem.Key.CourseId,
                     GuestNum = qitem.Sum(s => s.GuestNum),
                     OrderMoney = qitem.Sum(s => s.Income - s.Refund - s.PlatformTax)
                 });

            foreach (var gItem in groupList)
            {
                list.Add(new PersionOrderItem()
                {
                    Year = gItem.Year,
                    Month = gItem.Month,
                    GuestNum = gItem.GuestNum,
                    OrderMoney = gItem.OrderMoney,
                    CourseId=gItem.CourseId,
                });
            }
            return list;
        }

        /// <summary>
        /// 获取首页员工人头奖励统计
        /// </summary>
        /// <param name="EmpId">员工编号</param>
        /// <param name="Type">1-月度统计，2-年度统计</param>
        /// <param name="Year">年份</param>
        /// <param name="Month">月份</param>
        /// <returns></returns>
        public EmpStaticItem GetEmpBonusStaticModule(UserInfo user, int Type, int Year, int Month)
        {
            EmpStaticItem empItem = new EmpStaticItem();
            //月度统计
            if (Type == 1)
            {
                empItem = GetMonthDataModule(user, Year, Month);
            }
            //年度统计
            else
            {
                empItem = GetYearDataModule(user, Year);
            }
            return empItem;
        }

        /// <summary>
        /// 人头奖励月度统计
        /// </summary>
        /// <param name="user"></param>
        /// <param name="Type"></param>
        /// <param name="Year"></param>
        /// <param name="Month"></param>
        /// <returns></returns>
        private EmpStaticItem GetMonthDataModule(UserInfo user, int Year, int Month)
        {
            EmpStaticItem monthData = new EmpStaticItem();
            int CurrentYear = DateTime.Now.Year;
            int CurrentMonth = DateTime.Now.Month;
            //当月
            if (Year == CurrentYear && Month == CurrentMonth)
            {
                monthData = GetCurrentMonthData(user);
            }
            else
            {
                DateTime d1 = new DateTime(Year, Month, 1);
                string startDate = Common.ConvertHelper.FormatDate(d1);
                DateTime endTime = d1.AddMonths(1).AddDays(-1);
                string endDate = Common.ConvertHelper.FormatDate(endTime);
                var list = personnel_BonusRepository.GetPersonnelBonusListRepository(new RB_Personnel_Bonus_Extend()
                {
                    EmployeeId = user.Id,
                    YearNum = Year,
                    MonthNum = Month
                }, isGetDetail: true);
                monthData.TotalBonusMoney = list?.Sum(qitem => qitem.CurRewardMoney + qitem.ClueNumSalary + qitem.OpenBonus) ?? 0;
                monthData.CurRewardMoney = list?.Sum(qitem => qitem.CurRewardMoney) ?? 0;
                monthData.OpenBonus = list?.Sum(qitem => qitem.OpenBonus) ?? 0;
                monthData.ClueNumSalary = list?.Sum(qitem => qitem.ClueNumSalary) ?? 0;
                monthData.GuestNum = list?.Sum(qitem => qitem.CurGuestNum) ?? 0;
                monthData.OrderCount = 0;
                monthData.ClueCount = list?.Sum(qitem=>qitem.ClueNum)??0;
                foreach (var subItem in list)
                {
                    monthData.OrderCount += subItem?.DetailList?.Count()??0;
                }
                monthData.ReachCount = list?.Where(qitem => qitem.IsReach > 0)?.Count() ?? 0;
                if (list != null && list.Count > 0)
                {
                    //历史人头提成方案
                    var hisModel = JsonHelper.DeserializeObject<CurrentMonthBonusData>(list?.FirstOrDefault()?.HisBonusData);
                    GetNextGoal(monthData.GuestNum, hisModel, out int CurrentStep,out decimal StartNum,out decimal EndNum, out string NextGoal, out decimal NextBonus);
                    monthData.CurrentStep = CurrentStep;
                    monthData.StartNum = StartNum;
                    monthData.EndNum = EndNum;
                    monthData.NextGoal = NextGoal;
                    monthData.NextBonus = NextBonus;
                }
            }
            return monthData;
        }

        /// <summary>
        /// 计算当月人头奖励数据
        /// </summary>
        /// <param name="user"></param>
        private EmpStaticItem GetCurrentMonthData(UserInfo user)
        {
            var monthData = new EmpStaticItem();
            DateTime d1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            string startDate = Common.ConvertHelper.FormatDate(d1);
            DateTime endTime = d1.AddMonths(1).AddDays(-1);
            //人头配置列表
            var planList = bonus_PlanRepository.GetBounsPlanListRepository(new RB_Bonus_PlanExtend()
            {
                Group_Id = user.Group_Id
            }, isGetDetail: true);
            if (planList != null && planList.Count > 0)
            {
                foreach (var item in planList)
                {
                    var saleList = Common.ConvertHelper.StringToList(item.SaleIds);
                    foreach (var saleId in saleList)
                    {
                        if (saleId == user.Id)
                        {
                            string endDate = Common.ConvertHelper.FormatDate(endTime);
                            var orderList = GetSaleOrderList(item, user.Group_Id,startDate,endDate, saleId, out List<RB_Order_ViewModel> allOrderList,out int IsOpenOrder);
                            monthData.GuestNum = orderList?.Where(qitem=>!item.NotUseCourseIds.Contains(qitem.CourseId.ToString())).Sum(qitem => qitem.GuestNum) ?? 0;
                            monthData.OrderCount = allOrderList?.Count() ?? 0;
                            monthData.ReachCount = item.MonthGoalMoney > (orderList?.Where(qitem=>!item.NotUseCourseIds.Contains(qitem.CourseId.ToString()))?.Sum(qitem => qitem.OrderMoney) ?? 0) ? 1 : 0;

                            //当月梯度奖励金额
                            decimal CurRewardMoney = GetStepAwardAmount(item, monthData.GuestNum);
                            //开单奖金
                            decimal OpenBonus = IsOpenOrder > 0 ? item.OpenBonus : 0;
                            //线索奖励
                            var stuModel = studentRepository.GetStudentStaticRepository(saleId.ToString(), startDate, endDate)?.FirstOrDefault();
                            decimal ClueNumSalary = stuModel?.ClueCount > 5 ? item.ClueNumSalary : 0;

                            GetCurrentGoal(monthData.GuestNum, item, out int CurrentStep,out decimal StartNum,out decimal EndNum, out string NextGoal, out decimal awardAmount);
                            monthData.CurrentStep = CurrentStep;
                            monthData.StartNum = StartNum;
                            monthData.EndNum = EndNum;
                            monthData.NextGoal = NextGoal;
                            monthData.NextBonus = awardAmount;
                            monthData.CurRewardMoney = CurRewardMoney;
                            monthData.OpenBonus = OpenBonus;
                            monthData.ClueNumSalary = ClueNumSalary;
                            monthData.TotalBonusMoney = (CurRewardMoney + OpenBonus + ClueNumSalary);
                            monthData.ClueCount = stuModel?.ClueCount ?? 0;
                            break;
                        }
                    }
                }
            }
            return monthData;
        }

        /// <summary>
        /// 人头奖励年度统计
        /// </summary>
        /// <param name="user"></param>
        /// <param name="Year"></param>
        /// <returns></returns>
        private EmpStaticItem GetYearDataModule(UserInfo user, int Year)
        {
            int CurrentYear = DateTime.Now.Year;
            EmpStaticItem yearData = new EmpStaticItem();
            var list = personnel_BonusRepository.GetPersonnelBonusListRepository(new RB_Personnel_Bonus_Extend()
            {
                EmployeeId = user.Id,
                YearNum = Year,
            }, isGetDetail: true);
            if (list != null && list.Count > 0)
            {
                yearData.TotalBonusMoney = list?.Sum(qitem => qitem.CurRewardMoney + qitem.ClueNumSalary + qitem.OpenBonus) ?? 0;
                yearData.CurRewardMoney= list?.Sum(qitem => qitem.CurRewardMoney) ?? 0;
                yearData.ClueNumSalary = list?.Sum(qitem =>  qitem.ClueNumSalary)??0;
                yearData.OpenBonus = list?.Sum(qitem => qitem.OpenBonus) ?? 0;
                yearData.GuestNum = list?.Sum(qitem => qitem.CurGuestNum) ?? 0;
                yearData.OrderCount = list?.Sum(qitem => qitem?.DetailList?.Count) ?? 0;
                yearData.ReachCount = list?.Where(qitem => qitem.IsReach == 1)?.Count() ?? 0;
                yearData.ClueCount = list?.Sum(qitem => qitem.ClueNum) ?? 0;
            }
            if (Year == CurrentYear)
            {
                //var monData = GetCurrentMonthData(user);
                //yearData.TotalBonusMoney += monData?.TotalBonusMoney ?? 0;
                //yearData.ClueNumSalary += monData?.ClueNumSalary ?? 0;
                //yearData.OpenBonus += monData?.OpenBonus ?? 0;
                //yearData.CurRewardMoney += monData?.CurRewardMoney ?? 0;
                //yearData.GuestNum += monData?.GuestNum ?? 0;
                //yearData.OrderCount += monData?.OrderCount ?? 0;
                //yearData.ReachCount += monData?.ReachCount ?? 0;
                //yearData.ClueCount += monData?.ClueCount ?? 0;
            }
            return yearData;
        }

        /// <summary>
        /// 获取下一个目标
        /// </summary>
        /// <param name="GuestNum"></param>
        /// <param name="hisData"></param>
        /// <param name="CurrentStep"></param>
        /// <param name="NextGoal"></param>
        /// <param name="awardAmount"></param>
        public void GetNextGoal(int GuestNum, CurrentMonthBonusData hisData, out int CurrentStep,out decimal StartNum,out decimal EndNum, out string NextGoal, out decimal awardAmount)
        {
            awardAmount = 0;
            NextGoal = "";
            CurrentStep = 1;
            StartNum = 0;
            EndNum = 0;
            if (hisData != null && hisData.DetailList != null && hisData.DetailList.Count > 0)
            {
                var firstStep = hisData.DetailList[0];
                if (GuestNum <= firstStep.EndNum)
                {
                    CurrentStep = 1;
                    NextGoal = string.Format("距{0}档还差{1}个", 1, firstStep.StartNum - GuestNum);
                    awardAmount = firstStep.Money;
                    StartNum = firstStep.StartNum;
                    EndNum = firstStep.EndNum;
                }
                else
                {
                    for (var i = 0; i < hisData.DetailList.Count; i++)
                    {
                        var tempNum = hisData.DetailList[i];
                        if (tempNum.StartNum <= GuestNum && GuestNum <= tempNum.EndNum)
                        {
                            StartNum = tempNum.StartNum;
                            EndNum = tempNum.EndNum;
                            if ((i + 1) < hisData.DetailList.Count)
                            {
                                CurrentStep = (i + 1);
                                awardAmount = hisData.DetailList[i + 1].Money;
                                
                                NextGoal = string.Format("距{0}档还差{1}个", (i + 1 + 1), hisData.DetailList[i + 1].StartNum - GuestNum);
                            }
                            else
                            {
                                CurrentStep = (i + 1);
                                awardAmount = tempNum.Money;
                                NextGoal = string.Format("已完成当月目标!");
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 当月人头奖励目标计算
        /// </summary>
        /// <param name="GuestNum"></param>
        /// <param name="hisData"></param>
        /// <param name="CurrentStep"></param>
        /// <param name="NextGoal"></param>
        /// <param name="awardAmount"></param>
        public void GetCurrentGoal(int GuestNum, RB_Bonus_PlanExtend hisData, out int CurrentStep,out decimal StartNum,out decimal EndNum, out string NextGoal, out decimal awardAmount)
        {
            awardAmount = 0;
            NextGoal = "";
            CurrentStep = 1;
            StartNum = 0;
            EndNum = 0;
            if (hisData != null && hisData.DetailList != null && hisData.DetailList.Count > 0)
            {
                var firstStep = hisData.DetailList[0];
                if (GuestNum <= firstStep.EndNum)
                {
                    CurrentStep = 1;
                    NextGoal = string.Format("距{0}档还差{1}个", 1, firstStep.StartNum - GuestNum);
                    awardAmount = firstStep.Money;
                    StartNum = firstStep.StartNum;
                    EndNum = firstStep.EndNum;
                }
                else
                {
                    for (var i = 0; i < hisData.DetailList.Count; i++)
                    {
                        var tempNum = hisData.DetailList[i];
                        if (tempNum.StartNum <= GuestNum && GuestNum <= tempNum.EndNum)
                        {
                            StartNum = tempNum.StartNum;
                            EndNum = tempNum.EndNum;
                            if ((i + 1) < hisData.DetailList.Count)
                            {
                                CurrentStep = (i + 1);
                                awardAmount = hisData.DetailList[i + 1].Money;
                                NextGoal = string.Format("距{0}档还差{1}个", (i + 1 + 1), hisData.DetailList[i + 1].StartNum - GuestNum);
                            }
                            else
                            {
                                CurrentStep = (i + 1);
                                awardAmount = tempNum.Money;
                                NextGoal = string.Format("已完成本月目标!");
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 员工人头奖励统计
    /// </summary>
    public class EmpStaticItem
    {
        /// <summary>
        /// 奖金
        /// </summary>
        public decimal TotalBonusMoney { get; set; }

        /// <summary>
        /// 开单奖励
        /// </summary>
        public decimal OpenBonus { get; set; }

        /// <summary>
        /// 线索奖励
        /// </summary>
        public decimal ClueNumSalary { get; set; }

        /// <summary>
        /// 人头奖励
        /// </summary>
        public decimal CurRewardMoney { get; set; }

        /// <summary>
        /// 开单数量
        /// </summary>
        public int OrderCount { get; set; }

        /// <summary>
        /// 名单人数
        /// </summary>
        public int GuestNum { get; set; }

        /// <summary>
        /// 开始人数
        /// </summary>
        public decimal StartNum { get; set; }

        /// <summary>
        /// 结束人数
        /// </summary>
        public decimal EndNum { get; set; }

        /// <summary>
        /// 是否达到月度业绩目标
        /// </summary>
        public int ReachCount { get; set; }

        /// <summary>
        /// 当前档数
        /// </summary>
        public int CurrentStep { get; set; }

        /// <summary>
        /// 线索条数
        /// </summary>
        public int ClueCount { get; set; }

        /// <summary>
        /// 下一个目标字符串
        /// </summary>
        public string NextGoal { get; set; }

        /// <summary>
        /// 下一个目标奖励
        /// </summary>
        public decimal NextBonus { get; set; }
    }

    /// <summary>
    /// 人员销售
    /// </summary>
    public class PersionOrderItem
    {
        /// <summary>
        /// 年份
        /// </summary>
        public int Year { get; set; }

        /// <summary>
        /// 月份
        /// </summary>
        public int Month { get; set; }

        /// <summary>
        /// 人数
        /// </summary>
        public int GuestNum { get; set; }

        /// <summary>
        /// 订单金额
        /// </summary>
        public decimal OrderMoney { get; set; }

        /// <summary>
        /// 课程编号
        /// </summary>
        public int CourseId { get; set; }
    }
}
