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.Reserve;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Finance;
using Edu.Repository.Grade;
using Edu.Repository.Log;
using Edu.Repository.Sell;
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 TeachingRewardsModule
    {
        /// <summary>
        /// 奖励
        /// </summary>
        private readonly RB_Teaching_RewardsRepository teaching_RewardsRepository = new RB_Teaching_RewardsRepository();
        /// <summary>
        /// 概率范围
        /// </summary>
        private readonly RB_Teaching_Rewards_RateRepository teaching_Rewards_RateRepository = new RB_Teaching_Rewards_RateRepository();
        /// <summary>
        /// 基础
        /// </summary>
        private readonly RB_Teaching_Rewards_BaseRepository teaching_Rewards_BaseRepository = new RB_Teaching_Rewards_BaseRepository();
        /// <summary>
        /// 用户日志
        /// </summary>
        private readonly RB_User_ChangeLogRepository changeLogRepository = new RB_User_ChangeLogRepository();
        /// <summary>
        /// 教师奖励
        /// </summary>
        private readonly RB_Teaching_BonusRepository teaching_BonusRepository = new RB_Teaching_BonusRepository();
        /// <summary>
        /// 教师奖励明细
        /// </summary>
        private readonly RB_Teaching_BonusDetailRepository teaching_BonusDetailRepository = new RB_Teaching_BonusDetailRepository();
        /// <summary>
        /// 教师
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();
        /// <summary>
        /// 上课计划
        /// </summary>
        private readonly RB_Class_PlanRepository class_PlanRepository = new RB_Class_PlanRepository();
        /// <summary>
        /// 上课时间
        /// </summary>
        private readonly RB_Class_TimeRepository class_TimeRepository = new RB_Class_TimeRepository();
        /// <summary>
        /// 班级基础配置
        /// </summary>
        private readonly RB_Class_ConfigRepository class_ConfigRepository = new RB_Class_ConfigRepository();
        /// <summary>
        /// 班级类型
        /// </summary>
        private readonly RB_Class_TypeRepository class_TypeRepository = new RB_Class_TypeRepository();
        /// <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_ClientBankAccountRepository clientBankAccountRepository = new RB_ClientBankAccountRepository();
        /// <summary>
        /// 教师绩效
        /// </summary>
        private readonly RB_Teaching_PerfRepository teaching_PerfRepository = new RB_Teaching_PerfRepository();
        /// <summary>
        /// 教师绩效备注
        /// </summary>
        private readonly RB_Teaching_PerfRemarkRepository teaching_PerfRemarkRepository = new RB_Teaching_PerfRemarkRepository();
        /// <summary>
        /// 集团
        /// </summary>
        private readonly RB_GroupRepository groupRepository = new RB_GroupRepository();
        /// <summary>
        /// 校区
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();
        /// <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_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();
        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();
        /// <summary>
        /// 投稿提成规则
        /// </summary>
        private readonly RB_TeaCon_Commission_RuleRepository teaCon_Commission_RuleRepository = new RB_TeaCon_Commission_RuleRepository();
        /// <summary>
        /// 投稿提成期数
        /// </summary>
        private readonly RB_TeaCon_Commission_PeriodsRepository teaCon_Commission_PeriodsRepository = new RB_TeaCon_Commission_PeriodsRepository();
        /// <summary>
        /// 投稿提成明细
        /// </summary>
        private readonly RB_TeaCon_Commission_DetailsRepository teaCon_Commission_DetailsRepository = new RB_TeaCon_Commission_DetailsRepository();
        /// <summary>
        /// 投稿信息
        /// </summary>
        private readonly Repository.WeChat.RB_Contribute_InfoRepository contribute_InfoRepository = new Repository.WeChat.RB_Contribute_InfoRepository();
        /// <summary>
        /// 试听课程
        /// </summary>
        private readonly RB_TrialLessonRepository trialLessonRepository = new RB_TrialLessonRepository();
        /// <summary>
        /// 试听班级
        /// </summary>
        private readonly Repository.Reserve.RB_Reserve_ClassRepository reserve_ClassRepository = new Repository.Reserve.RB_Reserve_ClassRepository();



        #region 教务配置
        /// <summary>
        /// 获取教务奖励列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public List<RB_Teaching_Rewards_Rate_ViewModel> GetTeachimgRewardsList(RB_Teaching_Rewards_Rate_ViewModel demodel, UserInfo userInfo, out List<RB_Teaching_Rewards_Rate_ViewModel> fclist)
        {
            var rlist = teaching_Rewards_RateRepository.GetList(new RB_Teaching_Rewards_Rate_ViewModel() { Group_Id = userInfo.Group_Id, Type = demodel.Type });
            var relist = rlist.Where(x => x.RateType == 2).OrderBy(x => x.StartValue).ToList();
            fclist = rlist.Where(x => x.RateType == 1).OrderBy(x => x.StartValue).ToList();
            var vlist = new List<RB_Teaching_Rewards_ViewModel>();
            if (relist.Any())
            {
                string TackClassRateIds = string.Join(",", relist.Select(x => x.Id));
                vlist = teaching_RewardsRepository.GetList(new RB_Teaching_Rewards_ViewModel() { TackClassRateIds = TackClassRateIds });
            }
            foreach (var item in relist)
            {
                var clist = new List<RB_Teaching_Rewards_Rate_ViewModel>();
                foreach (var qitem in fclist)
                {
                    var vmodel = vlist.Where(x => x.FullClassRateId == qitem.Id && x.TackClassRateId == item.Id).FirstOrDefault();
                    clist.Add(new RB_Teaching_Rewards_Rate_ViewModel()
                    {
                        Id = qitem.Id,
                        StartValue = qitem.StartValue,
                        EndValue = qitem.EndValue,
                        ClassMoney = vmodel?.Money ?? 0,
                        PeopelNum = vmodel?.PeopelNum ?? 0
                    });
                }
                item.FullClassList = clist;
            }
            return relist;
        }

        /// <summary>
        /// 保存教务奖励配置
        /// </summary>
        /// <param name="type"></param>
        /// <param name="deList"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetTeachingRewardsInfo(int type, List<RB_Teaching_Rewards_Rate_ViewModel> deList, UserInfo userInfo)
        {
            var rlist = teaching_Rewards_RateRepository.GetList(new RB_Teaching_Rewards_Rate_ViewModel() { Group_Id = userInfo.Group_Id, Type = type });
            try
            {
                if (rlist.Any())
                {
                    //直接全删了  重新新增
                    var xblist = rlist.Where(x => x.RateType == 2).OrderBy(x => x.StartValue).ToList();
                    string TackClassRateIds = string.Join(",", xblist.Select(x => x.Id));
                    var vlist = teaching_RewardsRepository.GetList(new RB_Teaching_Rewards_ViewModel() { TackClassRateIds = TackClassRateIds });
                    teaching_RewardsRepository.DeleteBatch(vlist);
                    teaching_Rewards_RateRepository.DeleteBatch(rlist);
                }
                var FullClassList = deList.FirstOrDefault().FullClassList;
                //先新增满班率
                foreach (var item in FullClassList)
                {
                    int Id = teaching_Rewards_RateRepository.Insert(new RB_Teaching_Rewards_Rate()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        EndValue = item.EndValue,
                        Group_Id = userInfo.Group_Id,
                        RateType = 1,
                        School_Id = userInfo.School_Id,
                        StartValue = item.StartValue,
                        Type = type
                    });
                    item.Id = Id;
                }
                foreach (var item in deList)
                {
                    //新增续班率
                    int Id = teaching_Rewards_RateRepository.Insert(new RB_Teaching_Rewards_Rate()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        EndValue = item.EndValue,
                        Group_Id = userInfo.Group_Id,
                        RateType = 2,
                        School_Id = userInfo.School_Id,
                        StartValue = item.StartValue,
                        Type = type
                    });

                    foreach (var qitem in item.FullClassList)
                    {
                        //获取 满班率id 
                        int mId = FullClassList.Where(x => x.StartValue == qitem.StartValue && x.EndValue == qitem.EndValue).FirstOrDefault()?.Id ?? 0;
                        if (mId > 0)
                        {
                            teaching_RewardsRepository.Insert(new RB_Teaching_Rewards()
                            {
                                Id = 0,
                                FullClassRateId = mId,
                                TackClassRateId = Id,
                                Money = qitem.ClassMoney,
                                PeopelNum = qitem.PeopelNum
                            });
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetTeachingRewardsInfo");
                return false;
            }
        }


        /// <summary>
        /// 保存教务奖励  基础
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetTeachingRewardsBase(RB_Teaching_Rewards_Base_ViewModel demodel, UserInfo userInfo)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Rewards_Base_ViewModel.BasicMoney),demodel.BasicMoney},
                    { nameof(RB_Teaching_Rewards_Base_ViewModel.BasicHour),demodel.BasicHour},
                    { nameof(RB_Teaching_Rewards_Base_ViewModel.ClassTypeIds),demodel.ClassTypeIds},
                    { nameof(RB_Teaching_Rewards_Base_ViewModel.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_Teaching_Rewards_Base_ViewModel.UpdateTime),demodel.UpdateTime}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Teaching_Rewards_Base_ViewModel.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                var flag = teaching_Rewards_BaseRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "更新教务奖励-基础",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                return flag;
            }
            else
            {
                var list = teaching_Rewards_BaseRepository.GetList(new RB_Teaching_Rewards_Base_ViewModel() { Group_Id = userInfo.Group_Id, Type = demodel.Type });
                if (list.Any())
                {
                    return false;
                }
                int Id = teaching_Rewards_BaseRepository.Insert(demodel);
                if (Id > 0)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "新增教务奖励-基础",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                return Id > 0;
            }
        }

        /// <summary>
        /// 获取教务奖励基础
        /// </summary>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetTeachingRewardsBaseInfo(int type, UserInfo userInfo)
        {
            var model = teaching_Rewards_BaseRepository.GetList(new RB_Teaching_Rewards_Base_ViewModel() { Group_Id = userInfo.Group_Id, Type = type }).FirstOrDefault();
            return new
            {
                Id = model?.Id ?? 0,
                BasicMoney = model?.BasicMoney ?? 0,
                ClassTypeIds = model?.ClassTypeIds ?? "",
                ClassTypeIdList = JsonHelper.DeserializeObject<List<int>>("[" + (model?.ClassTypeIds ?? "") + "]"),
                BasicHour = model?.BasicHour ?? 0
            };
        }
        #endregion

        #region 教师奖励

        /// <summary>
        /// 获取讲师奖励分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_Bonus_ViewModel> GetTeachingBonusPageList(int pageIndex, int pageSize, out long count, RB_Teaching_Bonus_ViewModel dmodel)
        {
            var list = teaching_BonusRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                string bonusIds = string.Join(",", list.Select(x => x.Id));
                //获取所有的明细
                var dlist = teaching_BonusDetailRepository.GetList(new RB_Teaching_BonusDetail_ViewModel() { Group_Id = dmodel.Group_Id, BonusIds = bonusIds });
                //获取所有的教师
                string teacherIds = string.Join(",", list.Select(x => x.TeacherIds));
                var tlist = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel() { Group_Id = dmodel.Group_Id, QTIds = teacherIds, IsQLeave = 1 });
                //查询财务单据
                var financeList = financeRepository.GetListSingle(new RB_Finance_Extend() { RB_Group_Id = dmodel.Group_Id, FinanceType = 2, OtherType = 26, ReFinanceIds = bonusIds, IsSelectNormal = 1 });
                foreach (var item in list)
                {
                    item.TeacherList = new List<RB_Teaching_BonusDetail_ViewModel>();
                    string[] teacherIdArr = item.TeacherIds.Split(",");
                    foreach (var qitem in teacherIdArr)
                    {
                        int teacherId = Convert.ToInt32(qitem);
                        string teacherName = tlist.Where(x => x.TId == teacherId).FirstOrDefault()?.TeacherName ?? "";
                        //教师累计奖励金额
                        decimal money = dlist.Where(x => x.BonusId == item.Id && x.TeacherId == teacherId).Sum(x => x.Money);
                        item.TeacherList.Add(new RB_Teaching_BonusDetail_ViewModel()
                        {
                            TeacherId = teacherId,
                            TeacherName = teacherName,
                            Money = money
                        });
                        //财务单据
                        var flist = financeList.Where(x => x.ReFinanceId == item.Id).Select(x => x.FrID);
                        if (flist.Any())
                        {
                            item.FinanceId = string.Join(",", flist);
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取教师奖励明细列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_BonusDetail_ViewModel> GetTeachingBonusDetailList(RB_Teaching_BonusDetail_ViewModel dmodel)
        {
            var list = teaching_BonusDetailRepository.GetTeachingBonusDetailList(dmodel);
            return list;
        }

        /// <summary>
        /// 获取我的教师奖励
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_BonusDetail_ViewModel> GetMyTeachingBonusDetailPageList(int pageIndex, int pageSize, out long count, RB_Teaching_BonusDetail_ViewModel dmodel)
        {
            var list = teaching_BonusDetailRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            return list;
        }

        /// <summary>
        /// 获取累积金额
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetTeachingBonusDetailTotalMoney(RB_Teaching_BonusDetail_ViewModel dmodel)
        {
            return teaching_BonusDetailRepository.GetTeachingBonusDetailTotalMoney(dmodel);
        }

        /// <summary>
        /// 获取教师奖励统计
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_BonusDetail_ViewModel> GetTeachingBonusStatistics(RB_Teaching_BonusDetail_ViewModel dmodel)
        {
            var list = teaching_BonusDetailRepository.GetTeachingBonusStatistics(dmodel);
            return list;
        }

        /// <summary>
        /// 设置教师降临id
        /// </summary>
        /// <param name="bonusId"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetTeachingBonusState(int bonusId, int type, UserInfo userInfo)
        {
            var model = teaching_BonusRepository.GetEntity(bonusId);
            if (model == null) { return false; }
            string LogContent = "";
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Teaching_Bonus_ViewModel.UpdateBy),userInfo.Id},
                { nameof(RB_Teaching_Bonus_ViewModel.UpdateTime),DateTime.Now}
            };
            if (type == 1)
            {
                LogContent = "教务奖励确认";
                if (model.State != BonusStateEnum.Wait)
                {
                    return false;
                }
                keyValues.Add(nameof(RB_Teaching_Bonus_ViewModel.State), BonusStateEnum.Confirmed);
            }
            else if (type == 2)
            {
                LogContent = "教务奖励取消";
                if (model.State != BonusStateEnum.Wait && model.State != BonusStateEnum.Confirmed)
                {
                    return false;
                }
                keyValues.Add(nameof(RB_Teaching_Bonus_ViewModel.State), BonusStateEnum.Cancel);
            }
            else { return false; }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Teaching_Bonus_ViewModel.Id),
                      FiledValue=bonusId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = teaching_BonusRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 1,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = LogContent,
                    School_Id = userInfo.School_Id,
                    SourceId = 0
                });
            }
            return flag;
        }

        /// <summary>
        /// 新增教师奖励
        /// </summary>
        /// <param name="dmodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetTeachingBonusAdd(RB_Teaching_Bonus_ViewModel dmodel, UserInfo userInfo)
        {
            //验证当月教师是否已存在奖励
            var tlist = teaching_BonusRepository.GetList(new RB_Teaching_Bonus_ViewModel() { Group_Id = userInfo.Group_Id, Month = Convert.ToDateTime(dmodel.Month).ToString("yyyy-MM") }).Where(x => x.State != BonusStateEnum.Cancel).ToList();
            if (tlist.Any())
            {
                string[] teacherArr = dmodel.TeacherIds.Split(',');
                foreach (var item in tlist)
                {
                    foreach (var qitem in teacherArr)
                    {
                        if (("," + item.TeacherIds + ",").Contains("," + qitem + ","))
                        {
                            return "教师 " + (teacherRepository.GetEntity(qitem)?.TeacherName ?? "") + "【" + qitem + "】" + "已存在当月奖励";
                        }
                    }
                }
            }
            //基础配置
            var configModel = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = userInfo.Group_Id });
            if (configModel == null || configModel.BasicHourFee <= 0 || configModel.BasicMinutes <= 0) { return "未配置课时费基础设置"; }
            #region 首先创建个主表数据
            dmodel.State = BonusStateEnum.Create;
            int bonusId = teaching_BonusRepository.Insert(dmodel);
            #endregion

            //查询当月 老师对应所有的课程
            string StartTime = dmodel.Month + "-01";
            string EndTime = Convert.ToDateTime(dmodel.Month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            var plist = class_PlanRepository.GetClassPlanList_V2(new RB_Class_Plan_ViewModel() { Group_Id = userInfo.Group_Id, Q_TeacherIds = dmodel.TeacherIds, StartTime = StartTime, EndTime = EndTime });
            //查询所有课程的上课时间
            List<RB_Class_Type_ViewModel> typeList = new List<RB_Class_Type_ViewModel>();
            List<RB_Class_Check_ViewModel> checkList = new List<RB_Class_Check_ViewModel>();
            List<RB_Teacher_ViewModel> teacherList = new List<RB_Teacher_ViewModel>();
            List<RB_Teaching_BonusDetail_ViewModel> DateList = new List<RB_Teaching_BonusDetail_ViewModel>();
            if (plist.Any())
            {
                string pids = string.Join(",", plist.Select(x => x.ClassPlanId));
                string classTypeIds = string.Join(",", plist.Select(x => x.ClassType).Distinct());
                typeList = class_TypeRepository.GetClassTypeListRepository(new RB_Class_Type_ViewModel() { Group_Id = userInfo.Group_Id, Q_CTypeIds = classTypeIds });
                //查询签到数据
                string classIds = string.Join(",", plist.Select(x => x.ClassId).Distinct());
                checkList = class_CheckRepository.GetClassCheckStatistics(new RB_Class_Check_ViewModel() { Group_Id = userInfo.Group_Id, Q_ClassIds = classIds, StartDate = StartTime, EndDate = EndTime });
                //查询教师列表
                string teacherIds = string.Join(",", plist.Select(x => x.TeacherId).Distinct());
                teacherList = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel() { QTIds = teacherIds, IsQLeave = 1 });

                //根据学生签到表  查询
                var list = class_CheckRepository.GetTeacherConsumptionHoursDetialList(teacherIds, -1, 0, StartTime, EndTime, userInfo.Group_Id);
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        //上课课时
                        decimal KSNum = item.CurrentDeductionHours;//使用签到表的课时
                        if (item.ClassId == 18) { KSNum = 0; }//18班级暂不算课时

                        var typeModel = typeList.Where(x => x.CTypeId == item.ClassType).FirstOrDefault();

                        decimal unitPrice = configModel.BasicHourFee + (typeModel?.AddHourFee ?? 0) + (item?.BaseHourFee ?? 0);
                        //课时费  需要每个班级  单独计算  因为 班级有附加费用
                        decimal KSMoney = KSNum * unitPrice;

                        DateList.Add(new RB_Teaching_BonusDetail_ViewModel
                        {
                            Date = item.ClassDate,
                            TimeBucket = item.StartDate + "~" + item.EndDate,
                            TeacherId = item.TeacherId,
                            TeacherName = item.TeacherName,
                            ClassId = item.ClassId,
                            ClassName = item.ClassName,
                            CouseId = item.CouseId,
                            CourseName = item.CourseName,
                            KSNum = KSNum,
                            UnitPrice = unitPrice,
                            Money = KSMoney
                        });
                    }
                }
            }

            #region 试听课

            List<RB_Teaching_BonusDetail_ViewModel> stDateList = new List<RB_Teaching_BonusDetail_ViewModel>();
            var stlist = reserve_ClassRepository.GetClassReserveList(new RB_Reserve_Class_Extend() { Group_Id = userInfo.Group_Id, TeacherIds = dmodel.TeacherIds, ClassTime = StartTime, EndTime = EndTime });
            if (stlist.Any()) {
                //每次试听课 算一个课时
                foreach (var item in stlist) {
                    stDateList.Add(new RB_Teaching_BonusDetail_ViewModel()
                    {
                        BonusId = bonusId,
                        CheckInNum = item.CheckNum,
                        ClassId = item.ReserveClassId,
                        CourseHour = 1,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Date = item.ClassDate,
                        Group_Id = dmodel.Group_Id,
                        Id = 0,
                        Money = item.ClassHourFee,
                        School_Id = item.School_Id,
                        Status = 0,
                        TeacherId = item.TeacherId,
                        Type = 1,
                        UnitPrice = item.ClassHourFee,
                        UpdateBy = dmodel.UpdateBy,
                        UpdateTime = DateTime.Now,
                        CouseClassify = 2
                    });
                }
            }

            #endregion

            var trans = teaching_BonusDetailRepository.DbTransaction;
            try
            {
                decimal TotalMoney = 0;
                //基础课
                foreach (var item in plist)
                {
                    var dateqList = DateList.Where(x => x.TeacherId == item.TeacherId && x.ClassId == item.ClassId && x.Date == item.ClassDate).ToList();
                    //查询课时
                    decimal ksNum = dateqList.Sum(x => x.KSNum); 
                    //查询课单价
                    var typeModel = typeList.Where(x => x.CTypeId == item.ClassType).FirstOrDefault();
                    var teacherModel = teacherList.Where(x => x.TId == item.TeacherId).FirstOrDefault();
                    decimal unitPrice = configModel.BasicHourFee + (typeModel?.AddHourFee ?? 0) + (teacherModel?.BaseHourFee ?? 0);
                    //签到人数
                    var checkModel = checkList.Where(x => x.ClassId == item.ClassId && x.ClassDate == item.ClassDate).FirstOrDefault();

                    teaching_BonusDetailRepository.Insert(new RB_Teaching_BonusDetail()
                    {
                        BonusId = bonusId,
                        CheckInNum = checkModel?.CheckNum ?? 0,
                        ClassId = item.ClassId,
                        CourseHour = ksNum,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Date = item.ClassDate,
                        Group_Id = dmodel.Group_Id,
                        Id = 0,
                        Money = ksNum * unitPrice,
                        School_Id = item.School_Id,
                        Status = 0,
                        TeacherId = item.TeacherId,
                        Type = item.TeacherId == item.Teacher_Id ? 1 : 2,
                        UnitPrice = unitPrice,
                        UpdateBy = dmodel.UpdateBy,
                        UpdateTime = DateTime.Now,
                        CouseClassify = 1
                    }, trans);
                    TotalMoney += ksNum * unitPrice;
                }
                //试听课
                foreach (var item in stDateList) {
                    teaching_BonusDetailRepository.Insert(item, trans);
                    TotalMoney += item.Money;
                }

                #region 更新状态为待确认
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Bonus_ViewModel.State), BonusStateEnum.Wait},
                    { nameof(RB_Teaching_Bonus_ViewModel.Money), TotalMoney}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Teaching_Bonus_ViewModel.Id),
                          FiledValue=bonusId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_BonusRepository.Update(keyValues, wheres, trans);
                #endregion
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "生成教师奖励【" + dmodel.Month + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                teaching_BonusDetailRepository.DBSession.Commit();
                #region 基础课时处理
                decimal DeductionMoney = 0;
                if (configModel.BasicHours > 0)
                {
                    var blist = teaching_BonusDetailRepository.GetList(new RB_Teaching_BonusDetail_ViewModel() { Group_Id = userInfo.Group_Id, BonusId = bonusId });
                    //遍历所有老师
                    List<int> TeacherIdList = blist.Select(x => x.TeacherId).Distinct().ToList();
                    foreach (var item in TeacherIdList)
                    {
                        var teacherModel = teacherList.Where(x => x.TId == item).FirstOrDefault();
                        if (teacherModel == null) {
                            continue;
                        }
                        if (!(teacherModel.BaseHoursEnabled == 1 && Convert.ToDateTime(dmodel.Month) >= Convert.ToDateTime(teacherModel.EnableTime))){
                            continue;
                        }
                        var qblist = blist.Where(x => x.TeacherId == item).OrderBy(x => x.Date).ThenBy(x => x.UnitPrice).ToList();
                        decimal BasicHours = configModel.BasicHours;
                        foreach (var qitem in qblist)
                        {
                            decimal CourseHour = 0, DeductionHour = 0;
                            if (BasicHours > qitem.CourseHour)
                            {
                                DeductionHour = qitem.CourseHour;
                                BasicHours -= qitem.CourseHour;
                                DeductionMoney += qitem.CourseHour * qitem.UnitPrice;
                            }
                            else
                            {
                                DeductionHour = BasicHours;
                                CourseHour = qitem.CourseHour - BasicHours;
                                DeductionMoney += BasicHours * qitem.UnitPrice;
                                BasicHours = 0;
                            }
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Teaching_BonusDetail_ViewModel.CourseHour),CourseHour},
                                { nameof(RB_Teaching_BonusDetail_ViewModel.DeductionHour),DeductionHour},
                                { nameof(RB_Teaching_BonusDetail_ViewModel.Money),CourseHour * qitem.UnitPrice}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Teaching_BonusDetail_ViewModel.Id),
                                      FiledValue=qitem.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            teaching_BonusDetailRepository.Update(keyValues1, wheres1);
                            if (BasicHours <= 0)
                            {
                                break;
                            }
                        }
                    }

                    #region 更新总金额
                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                        { nameof(RB_Teaching_Bonus_ViewModel.Money), TotalMoney - DeductionMoney}
                    };
                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Teaching_Bonus_ViewModel.Id),
                              FiledValue=bonusId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    teaching_BonusRepository.Update(keyValues2, wheres2);
                    #endregion
                }
                #endregion
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetTeachingBonusAdd");
                teaching_BonusDetailRepository.DBSession.Rollback();
                #region 取消创建的奖励
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Bonus_ViewModel.State), BonusStateEnum.Cancel}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Teaching_Bonus_ViewModel.Id),
                          FiledValue=bonusId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                teaching_BonusRepository.Update(keyValues, wheres);
                #endregion
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 生成财务单据
        /// </summary>
        /// <param name="bonusId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetTeachingBonusFinance(int bonusId, int IsPublic, int CurrencyId, UserInfo userInfo)
        {
            var tmodel = teaching_BonusRepository.GetEntity(bonusId);
            if (tmodel == null) { return "教师奖励不存在"; }
            if (tmodel.State != BonusStateEnum.Confirmed) { return "奖金状态不正确"; }
            if (!string.IsNullOrEmpty(tmodel.FinanceId)) { return "已制单，无法再次生成单据"; }
            var fcmodel = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = FinanceConfigTypeEnum.ClassFees }).FirstOrDefault();
            if (fcmodel == null) { return "未配置制单流程"; }

            var list = teaching_BonusDetailRepository.GetTeachingBonusStatistics(new RB_Teaching_BonusDetail_ViewModel() { Group_Id = userInfo.Group_Id, BonusId = bonusId });

            string msg = "";
            //查询出所有需要发提成的人
            List<int> EmpList = list.Select(x => x.TeacherId).Distinct().ToList();
            if (!EmpList.Any()) { return "暂无老师有可发放的提成金额"; }
            //根据教师ids 查询 账号ids
            var teachList = teacherRepository.GetTeacherList(string.Join(",", EmpList));
            //查询所有的账户信息  不存在的需要提示
            var banklist = clientBankAccountRepository.GetList(new RB_ClientBankAccount_Extend() { RB_Group_Id = userInfo.Group_Id, Type = Common.Enum.Finance.ClientTypeEnum.Employee, ObjIdStr = string.Join(",", teachList.Select(x => x.AccountId)) });
            foreach (var item in teachList)
            {
                if (!banklist.Where(x => x.ObjID == item.AccountId).Any())
                {
                    msg += (UserReidsCache.GetUserLoginInfo(item.AccountId)?.AccountName ?? "") + "未查询到员工银行账户信息;";
                }
            }
            if (msg != "")
            {
                return msg + "请核实后再试!";
            }

            string Frids = "";
            foreach (var item in EmpList)
            {
                var tlist = list.Where(x => x.TeacherId == item).ToList();
                var teacherModel = teachList.Where(x => x.TId == item).FirstOrDefault();
                #region 新增财务单据
                //银行账户
                var clientModel = banklist.Where(x => x.ObjID == teacherModel.AccountId).FirstOrDefault();
                var detailList = new List<object> { };
                decimal TotalMoney = 0;
                foreach (var qitem in tlist)
                {
                    detailList.Add(new
                    {
                        fcmodel.CostTypeId,
                        Number = (qitem.CourseHour + qitem.DCourseHour),
                        OriginalMoney = qitem.Money,
                        qitem.UnitPrice,
                        Remark = "带班" + qitem.CourseHour + "课时，代课" + qitem.DCourseHour + "课程，基础" + qitem.DeductionHour + "课时"
                    });
                    TotalMoney += qitem.Money;
                }

                string Remark = tmodel.Month + "月，" + teacherModel.TeacherName + "教师课时费";
                var financeObj = new
                {
                    IsPublic,
                    ClientType = (int)Common.Enum.Finance.ClientTypeEnum.Employee,
                    ClientID = clientModel.ID,
                    CurrencyId,
                    WBMoney = TotalMoney,
                    PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    TemplateId = fcmodel.TempleteId,
                    OrderSource = 17,
                    OtherType = 26,
                    ReFinanceId = bonusId,
                    Remark,
                    detailList,
                    CreateBy = userInfo.Id,
                    RB_Branch_Id = teacherModel.School_Id,
                    RB_Depart_Id = teacherModel.Dept_Id,
                    RB_Group_Id = userInfo.Group_Id,
                    RB_CreateByName = userInfo.AccountName,
                    RB_DepartName = teacherModel.DeptName,
                    RB_BranchName = teacherModel.SName,
                    RB_GroupName = userInfo.GroupName,
                    FinanceType = 2
                };
                string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.ReadConfigKey("FinanceKey"));
                var resultInfo = new
                {
                    msg = sign
                };

                string apiResult = HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
                JObject parmsJob = JObject.Parse(apiResult);
                string resultCode = parmsJob.GetStringValue("resultCode");
                int frid = parmsJob.GetInt("data", 0);

                if (resultCode == "1" && frid > 0)
                {
                    Frids += frid + ",";
                }
                else
                {
                    string message = parmsJob.GetStringValue("message");
                    LogHelper.Write("SetTeachingBonusFinance:" + message);
                    msg += (teacherModel.TeacherName) + "创建财务单据失败;";
                }
                #endregion
            }
            if (Frids != "")
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Bonus_ViewModel.FinanceId),Frids[0..^1]}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Teaching_Bonus_ViewModel.Id),
                          FiledValue=bonusId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_BonusRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "生成教师奖励财务单据【" + tmodel.Id + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
            }
            return msg;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_BonusDetail_ViewModel> GetBonusDetailList(RB_Teaching_BonusDetail_ViewModel demodel)
        {
            return teaching_BonusDetailRepository.GetList(demodel);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_BonusDetail_ViewModel> GetListByTeacherId(RB_Teaching_BonusDetail_ViewModel demodel)
        {
            return teaching_BonusDetailRepository.GetListByTeacherId(demodel);
        }


        /// <summary>
        /// 新增教师奖励
        /// </summary>
        /// <param name="dmodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public List<RB_Teaching_BonusDetail_ViewModel> GetEstimateTeachingBonusAdd(RB_Teaching_Bonus_ViewModel dmodel, UserInfo userInfo)
        {
            //验证当月教师是否已存在奖励
            var tlist = teaching_BonusRepository.GetList(new RB_Teaching_Bonus_ViewModel() { Group_Id = userInfo.Group_Id, Month = Convert.ToDateTime(dmodel.Month).ToString("yyyy-MM") }).Where(x => x.State != BonusStateEnum.Cancel).ToList();
            if (tlist.Any())
            {
                string[] teacherArr = dmodel.TeacherIds.Split(',');
                foreach (var item in tlist)
                {
                    foreach (var qitem in teacherArr)
                    {
                        if (("," + item.TeacherIds + ",").Contains("," + qitem + ","))
                        {
                            return new List<RB_Teaching_BonusDetail_ViewModel>();
                        }
                    }
                }
            }
            //基础配置
            var configModel = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = userInfo.Group_Id });
            if (configModel == null || configModel.BasicHourFee <= 0 || configModel.BasicMinutes <= 0) { return new List<RB_Teaching_BonusDetail_ViewModel>(); }
           

            //查询当月 老师对应所有的课程
            string StartTime = dmodel.Month + "-01";
            string EndTime = Convert.ToDateTime(dmodel.Month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            var plist = class_PlanRepository.GetClassPlanList_V2(new RB_Class_Plan_ViewModel() { Group_Id = userInfo.Group_Id, Q_TeacherIds = dmodel.TeacherIds, StartTime = StartTime, EndTime = EndTime });
            //查询所有课程的上课时间
            List<RB_Class_Type_ViewModel> typeList = new List<RB_Class_Type_ViewModel>();
            List<RB_Class_Check_ViewModel> checkList = new List<RB_Class_Check_ViewModel>();
            List<RB_Teacher_ViewModel> teacherList = new List<RB_Teacher_ViewModel>();
            List<RB_Teaching_BonusDetail_ViewModel> DateList = new List<RB_Teaching_BonusDetail_ViewModel>();
            List<RB_Teaching_BonusDetail_ViewModel> resultdetailList = new List<RB_Teaching_BonusDetail_ViewModel>();
            if (plist.Any())
            {
                string pids = string.Join(",", plist.Select(x => x.ClassPlanId));
                string classTypeIds = string.Join(",", plist.Select(x => x.ClassType).Distinct());
                typeList = class_TypeRepository.GetClassTypeListRepository(new RB_Class_Type_ViewModel() { Group_Id = userInfo.Group_Id, Q_CTypeIds = classTypeIds });
                //查询签到数据
                string classIds = string.Join(",", plist.Select(x => x.ClassId).Distinct());
                checkList = class_CheckRepository.GetClassCheckStatistics(new RB_Class_Check_ViewModel() { Group_Id = userInfo.Group_Id, Q_ClassIds = classIds, StartDate = StartTime, EndDate = EndTime });
                //查询教师列表
                string teacherIds = string.Join(",", plist.Select(x => x.TeacherId).Distinct());
                teacherList = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel() { QTIds = teacherIds, IsQLeave = 1 });

                //根据学生签到表  查询
                var list = class_CheckRepository.GetTeacherConsumptionHoursDetialList(teacherIds, -1, 0, StartTime, EndTime, userInfo.Group_Id);
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        //上课课时
                        decimal KSNum = item.CurrentDeductionHours;//使用签到表的课时

                        var typeModel = typeList.Where(x => x.CTypeId == item.ClassType).FirstOrDefault();

                        decimal unitPrice = configModel.BasicHourFee + (typeModel?.AddHourFee ?? 0) + (item?.BaseHourFee ?? 0);
                        //课时费  需要每个班级  单独计算  因为 班级有附加费用
                        decimal KSMoney = KSNum * unitPrice;

                        DateList.Add(new RB_Teaching_BonusDetail_ViewModel
                        {
                            Date = item.ClassDate,
                            TimeBucket = item.StartDate + "~" + item.EndDate,
                            TeacherId = item.TeacherId,
                            TeacherName = item.TeacherName,
                            ClassId = item.ClassId,
                            ClassName = item.ClassName,
                            CouseId = item.CouseId,
                            CourseName = item.CourseName,
                            KSNum = KSNum,
                            UnitPrice = unitPrice,
                            Money = KSMoney
                        });
                    }
                }
            }
           
            try
            {
                
                foreach (var item in plist)
                {
                    var dateqList = DateList.Where(x => x.TeacherId == item.TeacherId && x.Date == item.ClassDate).ToList();
                    //查询课时
                    decimal ksNum = dateqList.Sum(x => x.KSNum);
                    //查询课单价
                    var typeModel = typeList.Where(x => x.CTypeId == item.ClassType).FirstOrDefault();
                    var teacherModel = teacherList.Where(x => x.TId == item.TeacherId).FirstOrDefault();
                    decimal unitPrice = configModel.BasicHourFee + (typeModel?.AddHourFee ?? 0) + (teacherModel?.BaseHourFee ?? 0);
                    //签到人数
                    var checkModel = checkList.Where(x => x.ClassId == item.ClassId && x.ClassDate == item.ClassDate).FirstOrDefault();

                    resultdetailList.Add(new RB_Teaching_BonusDetail_ViewModel()
                    {
                        BonusId = 0,
                        CheckInNum = checkModel?.CheckNum ?? 0,
                        ClassId = item.ClassId,
                        CourseHour = ksNum,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Date = item.ClassDate,
                        Group_Id = dmodel.Group_Id,
                        Id = 0,
                        Money = ksNum * unitPrice,
                        School_Id = dmodel.School_Id,
                        Status = 0,
                        TeacherId = item.TeacherId,
                        Type = item.TeacherId == item.Teacher_Id ? 1 : 2,
                        UnitPrice = unitPrice,
                        UpdateBy = dmodel.UpdateBy,
                        UpdateTime = DateTime.Now
                    });
                }
                return resultdetailList;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "GetEstimateTeachingBonusAdd");
                return new List<RB_Teaching_BonusDetail_ViewModel> ();
            }
        }



        /// <summary>
        /// 确认老师课时费
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateSureTeachingBonusDetail(int TeacherId, int Id)
        {
            IDictionary<string, object> fileds = new Dictionary<string, object>
                {
                    { nameof(RB_Teaching_BonusDetail_ViewModel.SureStatus), 1 },

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

        }
        #endregion

        #region 教师绩效

        /// <summary>
        /// 获取教师绩效分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_Perf_ViewModel> GetTeachingPerfPageList(int pageIndex, int pageSize, out long count, RB_Teaching_Perf_ViewModel dmodel)
        {
            var list = teaching_PerfRepository.GetPageList(pageIndex, pageSize, out count, demodel: dmodel);
            if (list.Any())
            {
                string perfIds = string.Join(",", list.Select(x => x.Id));
                var rlist = teaching_PerfRemarkRepository.GetList(new RB_Teaching_PerfRemark_ViewModel() { PerfIds = perfIds });

                foreach (var item in list)
                {
                    item.RemarkList = rlist.Where(x => x.PerfId == item.Id).ToList();

                    item.JJList = new List<RB_Teaching_Rewards_Rate_ViewModel>();
                    if (!string.IsNullOrEmpty(item.BonusJson))
                    {
                        item.JJList = JsonHelper.DeserializeObject<List<RB_Teaching_Rewards_Rate_ViewModel>>(item.BonusJson);
                    }
                    item.KSList = new List<RB_Teaching_Rewards_Rate_ViewModel>();
                    if (!string.IsNullOrEmpty(item.ClassFeeJson))
                    {
                        item.KSList = JsonHelper.DeserializeObject<List<RB_Teaching_Rewards_Rate_ViewModel>>(item.ClassFeeJson);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取课时费上涨历史记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_Perf_ViewModel> GetMyTeachingBonusHistoryPageList(int pageIndex, int pageSize, out long count, RB_Teaching_Perf_ViewModel dmodel)
        {
            var list = teaching_PerfRepository.GetPageList(pageIndex, pageSize, out count, demodel: dmodel);
            return list;
        }

        /// <summary>
        /// 获取累积金额
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetMyTeachingPerfTotalMoney(RB_Teaching_Perf_ViewModel dmodel)
        {
            return teaching_PerfRepository.GetMyTeachingPerfTotalMoney(dmodel);
        }

        /// <summary>
        /// 设置教师绩效备注
        /// </summary>
        /// <param name="perfId"></param>
        /// <param name="remark"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetTeachingPerfRemark(int perfId, string remark, UserInfo userInfo)
        {
            //查询最后一次的备注
            var model = teaching_PerfRemarkRepository.GetLastRemark(perfId);
            if (model == null || model.Content != remark)
            {
                bool flag = teaching_PerfRemarkRepository.Insert(new RB_Teaching_PerfRemark()
                {
                    Id = 0,
                    Content = remark,
                    PerfId = perfId,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now
                }) > 0;
                return flag;
            }
            else
            {
                return true;
            }
        }        

        /// <summary>
        /// 修改绩效状态
        /// </summary>
        /// <param name="perfId"></param>
        /// <param name="type">类型  1确认绩效  2不发放绩效  3恢复绩效  4撤销绩效</param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetTeachingPerfState(int perfId, int type, UserInfo userInfo)
        {
            var perfModel = teaching_PerfRepository.GetEntity(perfId);
            if (perfModel == null || perfModel.Status != 0) { return "绩效不存在"; }
            if (type == 1)
            {
                if (perfModel.PerfState != PerfStateEnum.Wait)
                {
                    return "状态不正确";
                }
                var teacherModel = teacherRepository.GetEntity(perfModel.TeacherId);
                if (teacherModel == null) { return "教师不存在"; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Perf_ViewModel.PerfState),PerfStateEnum.Confirmed},
                    { nameof(RB_Teaching_Perf_ViewModel.ConfirmDate),DateTime.Now},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper (){
                         FiledName=nameof(RB_Teaching_Perf_ViewModel.Id),
                          FiledValue=perfId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_PerfRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //更新教师课时费  更新带班人数
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Teacher_ViewModel.BaseHourFee),teacherModel.BaseHourFee + perfModel.AddHourFee},
                        { nameof(RB_Teacher_ViewModel.BaseStuNum),teacherModel.BaseStuNum + perfModel.AddStuNum}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Teacher_ViewModel.TId),
                              FiledValue=teacherModel.TId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    teacherRepository.Update(keyValues1, wheres1);

                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "设置教师绩效 =>发放绩效【" + perfId + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else if (type == 2)
            {
                if (perfModel.PerfState != PerfStateEnum.Wait)
                {
                    return "状态不正确";
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Perf_ViewModel.PerfState),PerfStateEnum.Cancel},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper (){
                         FiledName=nameof(RB_Teaching_Perf_ViewModel.Id),
                          FiledValue=perfId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_PerfRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "设置教师绩效 =>不发放绩效【" + perfId + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else if (type == 3)
            {
                if (perfModel.PerfState != PerfStateEnum.Cancel)
                {
                    return "状态不正确";
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Perf_ViewModel.PerfState),PerfStateEnum.Wait},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper (){
                         FiledName=nameof(RB_Teaching_Perf_ViewModel.Id),
                          FiledValue=perfId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_PerfRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "设置教师绩效 =>恢复绩效【" + perfId + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else if (type == 4)
            {
                if (perfModel.PerfState != PerfStateEnum.Confirmed)
                {
                    return "状态不正确";
                }
                if (perfModel.FinanceId > 0)
                {
                    return "已存在财务单据，无法撤回";
                }
                var teacherModel = teacherRepository.GetEntity(perfModel.TeacherId);
                if (teacherModel == null) { return "教师不存在"; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Perf_ViewModel.PerfState),PerfStateEnum.Wait},
                    { nameof(RB_Teaching_Perf_ViewModel.ConfirmDate),null},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_Teaching_Perf_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper (){
                         FiledName=nameof(RB_Teaching_Perf_ViewModel.Id),
                          FiledValue=perfId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_PerfRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //更新教师课时费  更新带班人数
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Teacher_ViewModel.BaseHourFee),teacherModel.BaseHourFee - perfModel.AddHourFee},
                        { nameof(RB_Teacher_ViewModel.BaseStuNum),teacherModel.BaseStuNum - perfModel.AddStuNum}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Teacher_ViewModel.TId),
                              FiledValue=teacherModel.TId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    teacherRepository.Update(keyValues1, wheres1);

                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "设置教师绩效 =>撤销绩效【" + perfId + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// 生成绩效
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public string SetTeachingPerfCreate(int classId, RB_Class_ViewModel classModel = null)
        {
            if (classModel == null)
            {
                classModel = classRepository.GetEntity<RB_Class_ViewModel>(classId);
            }
            else
            {
                classId = classModel.ClassId;
            }
            if (classModel.Status == DateStateEnum.Delete) { return "班级不存在"; }
            if (classModel.ClassStatus != ClassStatusEnum.EndClass) { return "班级状态不正确"; }

            //基础配置
            var configModel = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = classModel.Group_Id });
            if (configModel == null || configModel.BasicHourFee <= 0 || configModel.BasicMinutes <= 0) { return "未配置课时费基础设置"; }
            //获取班级类型
            var list = teaching_Rewards_BaseRepository.GetList(new RB_Teaching_Rewards_Base_ViewModel() { Group_Id = classModel.Group_Id });
            var baseModel = list.Where(x => ("," + x.ClassTypeIds + ",").Contains("," + classModel.ClassType + ",")).FirstOrDefault();
            if (baseModel == null) { return "班级类型未匹配到"; }
            var typeModel = class_TypeRepository.GetEntity(classModel.ClassType);

            //获取奖金  课时费 比例
            var JJRate = teaching_Rewards_RateRepository.GetList(new RB_Teaching_Rewards_Rate_ViewModel() { Group_Id = classModel.Group_Id, Type = baseModel.Type == 1 ? 1 : 3 });
            var KSRate = teaching_Rewards_RateRepository.GetList(new RB_Teaching_Rewards_Rate_ViewModel() { Group_Id = classModel.Group_Id, Type = baseModel.Type == 1 ? 2 : 4 });
            if (!JJRate.Any()) { return "奖金未配置"; }
            if (!KSRate.Any()) { return "课时费未配置"; }
            //获取比例值
            var JJrelist = JJRate.Where(x => x.RateType == 2).ToList();
            var JJfclist = JJRate.Where(x => x.RateType == 1).ToList();
            var KSrelist = KSRate.Where(x => x.RateType == 2).ToList();
            var KSfclist = KSRate.Where(x => x.RateType == 1).ToList();
            string TackClassRateIds = string.Join(",", JJrelist.Select(x => x.Id));
            string TackClassRateIds1 = string.Join(",", KSrelist.Select(x => x.Id));
            var ValueList = teaching_RewardsRepository.GetList(new RB_Teaching_Rewards_ViewModel() { TackClassRateIds = (TackClassRateIds + "," + TackClassRateIds1) });
            foreach (var item in JJrelist)
            {
                var clist = new List<RB_Teaching_Rewards_Rate_ViewModel>();
                foreach (var qitem in JJfclist)
                {
                    var vmodel = ValueList.Where(x => x.FullClassRateId == qitem.Id && x.TackClassRateId == item.Id).FirstOrDefault();
                    clist.Add(new RB_Teaching_Rewards_Rate_ViewModel()
                    {
                        Id = qitem.Id,
                        StartValue = qitem.StartValue,
                        EndValue = qitem.EndValue,
                        ClassMoney = vmodel?.Money ?? 0,
                        PeopelNum = vmodel?.PeopelNum ?? 0
                    });
                }
                item.FullClassList = clist;
            }
            foreach (var item in KSrelist)
            {
                var clist = new List<RB_Teaching_Rewards_Rate_ViewModel>();
                foreach (var qitem in KSfclist)
                {
                    var vmodel = ValueList.Where(x => x.FullClassRateId == qitem.Id && x.TackClassRateId == item.Id).FirstOrDefault();
                    clist.Add(new RB_Teaching_Rewards_Rate_ViewModel()
                    {
                        Id = qitem.Id,
                        StartValue = qitem.StartValue,
                        EndValue = qitem.EndValue,
                        ClassMoney = vmodel?.Money ?? 0,
                        PeopelNum = vmodel?.PeopelNum ?? 0
                    });
                }
                item.FullClassList = clist;
            }

            //教师信息
            var teachModel = teacherRepository.GetEntity(classModel.Teacher_Id);
            //班级总人数
            int TotalPeopleNum = class_CheckRepository.GetClassToalPeopleNum(classId, classModel.Group_Id);
            //班级课时总分钟数
            int TotalClassMin = class_PlanRepository.GetClassTotalMinute(classId, classModel.Group_Id);
            //总课时
            int ClassHourMinute = configModel.BasicMinutes;//课时分钟数
            if (classModel.ClassHourMinute > 0) { ClassHourMinute = classModel.ClassHourMinute; }
            int ksNum = TotalClassMin / ClassHourMinute; // 未达到一课时时间  不算一课时

            //满班率
            decimal FullClassRate = 0;
            if (teachModel.BaseStuNum > 0)
            {
                FullClassRate = Math.Round(Convert.ToDecimal(TotalPeopleNum) / teachModel.BaseStuNum, 2, MidpointRounding.AwayFromZero) * 100;
            }

            //班级平均上课率
            decimal AvgTakeClassRate = class_CheckRepository.GetClassAvgTakeClassRate(classId, classModel.Group_Id) * 100;

            //查询奖金金额
            decimal UnitPrice = 0;
            var jjModel = JJrelist.Where(x => x.StartValue <= AvgTakeClassRate && AvgTakeClassRate <= x.EndValue).FirstOrDefault();
            if (jjModel != null)
            {
                UnitPrice = jjModel.FullClassList.Where(x => x.StartValue <= FullClassRate && FullClassRate <= x.EndValue).FirstOrDefault()?.ClassMoney ?? 0;
            }
            //查询 增加课时费  带班人数
            decimal ClassMoney = 0;
            int StuNum = 0;
            var ksModel = KSrelist.Where(x => x.StartValue <= AvgTakeClassRate && AvgTakeClassRate <= x.EndValue).FirstOrDefault();
            if (ksModel != null)
            {
                var ks2Model = ksModel.FullClassList.Where(x => x.StartValue <= FullClassRate && FullClassRate <= x.EndValue).FirstOrDefault();
                ClassMoney = ks2Model?.ClassMoney ?? 0;
                StuNum = ks2Model?.PeopelNum ?? 0;
            }

            int perfId = teaching_PerfRepository.Insert(new RB_Teaching_Perf()
            {
                Id = 0,
                AddHourFee = ClassMoney,
                AddStuNum = StuNum,
                AvgCheckRate = AvgTakeClassRate,
                BaseHourFee = configModel.BasicHourFee + (typeModel?.AddHourFee ?? 0) + (teachModel?.BaseHourFee ?? 0),
                BaseStuNum = teachModel?.BaseStuNum ?? 0,
                ClassHours = ksNum,
                ClassId = classModel.ClassId,
                ClassPeopelNum = TotalPeopleNum,
                ConfirmDate = null,
                CreateBy = 0,
                CreateTime = DateTime.Now,
                EndDate = classModel.EndClassDate,
                FinanceId = 0,
                FullClassRate = FullClassRate,
                Group_Id = classModel.Group_Id,
                Money = UnitPrice * ksNum,
                PerfState = PerfStateEnum.Wait,
                School_Id = classModel.School_Id,
                Status = 0,
                TeacherId = classModel.Teacher_Id,
                UnitPrice = UnitPrice,
                UpdateBy = 0,
                UpdateTime = DateTime.Now,
                BonusJson = JsonHelper.Serialize(JJrelist.Select(x => new
                {
                    x.Id,
                    x.StartValue,
                    x.EndValue,
                    FullClassList = x.FullClassList.Select(z => new
                    {
                        z.Id,
                        z.StartValue,
                        z.EndValue,
                        z.ClassMoney,
                        z.PeopelNum
                    })
                })),
                ClassFeeJson = JsonHelper.Serialize(KSrelist.Select(x => new
                {
                    x.Id,
                    x.StartValue,
                    x.EndValue,
                    FullClassList = x.FullClassList.Select(z => new
                    {
                        z.Id,
                        z.StartValue,
                        z.EndValue,
                        z.ClassMoney,
                        z.PeopelNum
                    })
                }))
            });
            return "";
        }

        /// <summary>
        /// 获取集团列表
        /// </summary>
        /// <returns></returns>
        public List<RB_Group_ViewModel> GetGroupList()
        {
            return groupRepository.GetGroupListRepository(new RB_Group_ViewModel() { });
        }

        /// <summary>
        /// 获取可生成绩效的班级
        /// </summary>
        /// <param name="GroupId"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetTeachingPerfClassList(int GroupId)
        {
            return classRepository.GetTeachingPerfClassList(GroupId);
        }

        /// <summary>
        /// 绩效制单
        /// </summary>
        /// <param name="perfId"></param>
        /// <param name="isPublic"></param>
        /// <param name="currencyId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetTeachingPerfFinance(int perfId, int IsPublic, int CurrencyId, UserInfo userInfo)
        {
            var tmodel = teaching_PerfRepository.GetEntity(perfId);
            if (tmodel == null) { return "教师绩效不存在"; }
            if (tmodel.PerfState != PerfStateEnum.Confirmed) { return "未确认无法制单"; }
            if (tmodel.FinanceId > 0) { return "财务单据已存在，无法再次制单"; }
            var fcmodel = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = FinanceConfigTypeEnum.Perf }).FirstOrDefault();
            if (fcmodel == null) { return "未配置制单流程"; }

            string msg = "";
            var teacherModel = teacherRepository.GetTeacherList(tmodel.TeacherId.ToString()).FirstOrDefault();
            if (teacherModel == null)
            {
                return "教师不存在";
            }
            #region 新增财务单据
            //银行账户
            var clientModel = clientBankAccountRepository.GetList(new RB_ClientBankAccount_Extend() { RB_Group_Id = userInfo.Group_Id, Type = Common.Enum.Finance.ClientTypeEnum.Employee, ObjIdStr = teacherModel.AccountId.ToString() }).FirstOrDefault();
            if (clientModel == null)
            {
                return "教师未添加账户信息";
            }
            var detailList = new List<object>
            {
                new
                {
                    fcmodel.CostTypeId,
                    Number = tmodel.ClassHours,
                    OriginalMoney = tmodel.Money,
                    tmodel.UnitPrice,
                    Remark = "满班率：" + tmodel.FullClassRate + "%，平均上课率：" + tmodel.AvgCheckRate + "%，累计课时：" + tmodel.ClassHours
                }
            };
            var classModel = classRepository.GetEntity(tmodel.ClassId);
            string Remark = teacherModel.TeacherName + "教师【" + (classModel?.ClassName ?? "") + "】绩效";
            var financeObj = new
            {
                IsPublic,
                ClientType = (int)Common.Enum.Finance.ClientTypeEnum.Employee,
                ClientID = clientModel.ID,
                CurrencyId,
                WBMoney = tmodel.Money,
                PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                TemplateId = fcmodel.TempleteId,
                OrderSource = 17,
                OtherType = 27,
                ReFinanceId = perfId,
                Remark,
                detailList,
                CreateBy = userInfo.Id,
                RB_Branch_Id = teacherModel.School_Id,
                RB_Depart_Id = teacherModel.Dept_Id,
                RB_Group_Id = userInfo.Group_Id,
                RB_CreateByName = userInfo.AccountName,
                RB_DepartName = teacherModel.DeptName,
                RB_BranchName = teacherModel.SName,
                RB_GroupName = userInfo.GroupName,
                FinanceType = 2
            };
            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.ReadConfigKey("FinanceKey"));
            var resultInfo = new
            {
                msg = sign
            };

            string apiResult = HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
            JObject parmsJob = JObject.Parse(apiResult);
            string resultCode = parmsJob.GetStringValue("resultCode");
            int frid = parmsJob.GetInt("data", 0);

            if (resultCode == "1" && frid > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Teaching_Perf_ViewModel.FinanceId),frid}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Teaching_Perf_ViewModel.Id),
                          FiledValue=tmodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = teaching_PerfRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "生成教师绩效财务单据【" + tmodel.Id + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
            }
            else
            {
                string message = parmsJob.GetStringValue("message");
                LogHelper.Write("SetTeachingBonusFinance:" + message);
                msg += (teacherModel.TeacherName) + "创建财务单据失败;";
            }
            #endregion
            return msg;
        }

        /// <summary>
        /// 发送绩效通知
        /// </summary>
        /// <param name="perfId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetTeachingPerfPush(int perfId, UserInfo userInfo)
        {
            var perfModel = teaching_PerfRepository.GetEntity(perfId);
            if (perfModel == null || perfModel.Status != 0) { return "绩效不存在"; }
            if (perfModel.PerfState != PerfStateEnum.Confirmed) { return "绩效状态不正确"; }

            var teacherModel = teacherRepository.GetTeacherList(perfModel.TeacherId.ToString()).FirstOrDefault();
            if (teacherModel == null)
            {
                return "教师不存在";
            }
            //给教师发送通知

            //写入日志
            changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
            {
                Id = 0,
                Type = 1,
                CreateBy = userInfo.Id,
                CreateTime = DateTime.Now,
                Group_Id = userInfo.Group_Id,
                LogContent = "发送教师绩效通知【" + perfId + "】",
                School_Id = userInfo.School_Id,
                SourceId = 0
            });

            return "";
        }



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Teaching_Perf_ViewModel> GetTeachingPerfList(RB_Teaching_Perf_ViewModel demodel)
        {
            return teaching_PerfRepository.GetList(demodel);
        }

        #endregion

        #region 我的统计

        /// <summary>
        /// 获取教师id
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public int GetAccountTeacherId(int accountId) {
            var accountModel = accountRepository.GetEntity(accountId);
            if (accountModel.AccountType != Common.Enum.User.AccountTypeEnum.Teacher) { return 0; }
            return accountModel.AccountId;
        }

        /// <summary>
        /// 获取教师课时费统计
        /// </summary>
        /// <param name="monthNum"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public ApiResult GetMyTeachingBonusStatistics(int monthNum, UserInfo userInfo)
        {
            //查询教师信息
            var accountModel = accountRepository.GetEntity(userInfo.Id);
            if (accountModel.AccountType != Common.Enum.User.AccountTypeEnum.Teacher) { return ApiResult.Failed("不是教师端，无法查询"); }
            var teacherModel = teacherRepository.GetEntity(accountModel.AccountId);
            if (teacherModel == null) { return ApiResult.Failed("教师不存在"); }
            //基础配置
            var configModel = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = userInfo.Group_Id });
            decimal unitPrice = (configModel?.BasicHourFee ?? 0) + (teacherModel?.BaseHourFee ?? 0);//当前课时单价 （不包括班级挑动）

            //提成总金额
            decimal TotalMoney = teaching_BonusDetailRepository.GetTeachingBonusTotalMoney(teacherModel.TId, userInfo.Group_Id);
            //课时费确认的最后一个月
            string LastlyMonth = teaching_BonusDetailRepository.GetTeachingBonusLastlyMonth(teacherModel.TId, userInfo.Group_Id);

            //获取最近几月的走势图
            List<string> MList = new List<string>();
            for (var i = 1; i <= monthNum; i++) {
                MList.Add(DateTime.Now.AddMonths(0 - i).ToString("yyyy-MM"));
            }
            string monthStr = "'" + string.Join("','", MList) + "'";
            var LastlyChart = teaching_BonusRepository.GetTeachingBonusLastlyChart(teacherModel.TId, userInfo.Group_Id, monthStr);
            //获取当月趋势
            string StartTime = DateTime.Now.ToString("yyyy-MM") + "-01";
            string EndTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM") + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            var plist = class_PlanRepository.GetClassPlanList_V2(new RB_Class_Plan_ViewModel() { Group_Id = userInfo.Group_Id, Q_TeacherIds = teacherModel.TId.ToString(), StartTime = StartTime, EndTime = EndTime });
            //查询所有课程的上课时间
            List<RB_Class_Time_ViewModel> timeList = new List<RB_Class_Time_ViewModel>();
            List<RB_Class_Type_ViewModel> typeList = new List<RB_Class_Type_ViewModel>();
            if (plist.Any())
            {
                string pids = string.Join(",", plist.Select(x => x.ClassPlanId));
                timeList = class_TimeRepository.GetClassTimeListRepository(new RB_Class_Time_ViewModel() { Group_Id = userInfo.Group_Id, QClassPlanIds = pids });

                string classTypeIds = string.Join(",", plist.Select(x => x.ClassType).Distinct());
                typeList = class_TypeRepository.GetClassTypeListRepository(new RB_Class_Type_ViewModel() { Group_Id = userInfo.Group_Id, Q_CTypeIds = classTypeIds });
            }
            decimal NowMonthMoney = 0;
            foreach (var item in plist)
            {
                //查询课时
                var ctimelist = timeList.Where(x => x.ClassPlanId == item.ClassPlanId).ToList();
                int minute = 0;
                string nowTime = DateTime.Now.ToString("yyyy-MM-dd");
                foreach (var qitem in ctimelist)
                {
                    var ts = Convert.ToDateTime(nowTime + " " + qitem.EndTime) - Convert.ToDateTime(nowTime + " " + qitem.StartTime);
                    minute += (int)ts.TotalMinutes;
                }
                int ksNum = (configModel?.BasicMinutes ?? 0) == 0 ? 0 : minute / configModel.BasicMinutes; // 未达到一课时时间  算不算一课时
                                                               //查询课单价
                var typeModel = typeList.Where(x => x.CTypeId == item.ClassType).FirstOrDefault();
                decimal unitPrice1 = configModel.BasicHourFee + (typeModel?.AddHourFee ?? 0) + (teacherModel?.BaseHourFee ?? 0);
                NowMonthMoney += ksNum * unitPrice1;
            }

            List<RB_Teaching_Bonus_ViewModel> LastlyChartList = new List<RB_Teaching_Bonus_ViewModel>() {
                new RB_Teaching_Bonus_ViewModel(){
                     Month = DateTime.Now.ToString("yyyy-MM"),
                     Money = NowMonthMoney
                }
            };
            foreach (var item in MList) {
                var chartModel = LastlyChart.Where(x => x.Month == item).FirstOrDefault();
                if (chartModel == null)
                {
                    LastlyChartList.Add(new RB_Teaching_Bonus_ViewModel()
                    {
                        Month = item,
                        Money = 0
                    });
                }
                else {
                    LastlyChartList.Add(chartModel);
                }
            }

            return ApiResult.Success("", new
            {
                TotalMoney,
                UnitPrice = unitPrice,
                teacherModel.BaseStuNum,
                LastlyMonth,
                LastlyChartList = LastlyChartList.Select(x => new
                {
                    x.Month,
                    x.Money
                })
            });
        }

        #endregion

        #region 财务配置

        /// <summary>
        /// 获取财务配置列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Finance_Config_ViewModel> GetFinanceConfigList(RB_Finance_Config_ViewModel dmodel)
        {
            return finance_ConfigRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取财务配置
        /// </summary>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public RB_Finance_Config_ViewModel GetFinanceConfigInfo(int type, UserInfo userInfo)
        {
            var model = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = (FinanceConfigTypeEnum)type }).FirstOrDefault();
            if (model == null) {
                model = new RB_Finance_Config_ViewModel() { Id = 0 };
            }
            return model;
        }

        /// <summary>
        /// 设置财务配置
        /// </summary>
        /// <param name="dmodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetFinanceConfigInfo(RB_Finance_Config_ViewModel dmodel, UserInfo userInfo)
        {
            if (dmodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Finance_Config_ViewModel.CostTypeId),dmodel.CostTypeId},
                    { nameof(RB_Finance_Config_ViewModel.TempleteId),dmodel.TempleteId},
                    { nameof(RB_Finance_Config_ViewModel.UpdateBy),dmodel.UpdateBy},
                    { nameof(RB_Finance_Config_ViewModel.UpdateTime),dmodel.UpdateTime}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Finance_Config_ViewModel.Id),
                          FiledValue=dmodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return finance_ConfigRepository.Update(keyValues, wheres);
            }
            else {
                var model = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = dmodel.Type }).FirstOrDefault();
                if (model != null)
                {
                    return false;
                }
                return finance_ConfigRepository.Insert(dmodel) > 0;
            }
        }
        #endregion


        #region 课时费发放

        /// <summary>
        /// 获取课时费发放人员情况
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetTeachingRewardsSendEmployeeList(int periodId, UserInfo userInfo)
        {
            var model = teaching_BonusRepository.GetEntity<RB_Teaching_Bonus_ViewModel>(periodId);
            if (model == null) { return "周期不存在"; }
            List<int> EmpIdList = new List<int>();
            List<string> EmpTIdList = new List<string>();
            if (!string.IsNullOrEmpty(model.EmpIds))
            {
                if (model.Id >= 40)
                {
                    EmpTIdList = JsonHelper.DeserializeObject<List<string>>(model.EmpIds);
                }
                else
                {
                    EmpIdList = JsonHelper.DeserializeObject<List<int>>("[" + model.EmpIds + "]");
                }
            }


            string bonusIds = periodId.ToString();
            //获取所有的明细
            var dlist = teaching_BonusDetailRepository.GetList(new RB_Teaching_BonusDetail_ViewModel() { Group_Id = userInfo.Group_Id, BonusIds = bonusIds });
            //获取所有的教师
            string teacherIds = model.TeacherIds;
            var tlist = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel() { Group_Id = userInfo.Group_Id, QTIds = teacherIds, IsQLeave = 1 });

            List<object> RList = new List<object>();
            //查询所有校区
            var schoolList = dlist.Select(x => x.School_Id).Distinct().ToList();
            if (!schoolList.Any()) { return RList; }
            var slist = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { Group_Id = userInfo.Group_Id, QSIds = string.Join(",", schoolList) });
            foreach (var sitem in slist)
            {
                string[] teacherIdArr = model.TeacherIds.Split(",");
                foreach (var qitem in teacherIdArr)
                {
                    int teacherId = Convert.ToInt32(qitem);
                    string teacherName = tlist.Where(x => x.TId == teacherId).FirstOrDefault()?.TeacherName ?? "";
                    //教师累计奖励金额
                    decimal money = dlist.Where(x => x.TeacherId == teacherId && x.School_Id == sitem.SId).Sum(x => x.Money);
                    if (money > 0)
                    {
                        RList.Add(new
                        {
                            TSId = sitem.SId + "-" + teacherId,
                            SchoolId = sitem.SId,
                            SchoolName = sitem.SName,
                            TeacherId = teacherId,
                            TeacherName = teacherName,
                            Money = money,
                            IsGiveOut = model.Id >= 40 ? (EmpTIdList.Contains(sitem.SId + "-" + teacherId) ? 1 : 2) : (EmpIdList.Contains(teacherId) ? 1 : 2)
                        });
                    }
                }
            }
            return RList;
        }

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

        #endregion

        #region 投稿提成

        /// <summary>
        /// 获取投稿提成配置
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_TeaCon_Commission_Rule_ViewModel GetTeacherContributeConfig(int group_Id)
        {
            return teaCon_Commission_RuleRepository.GetList(new RB_TeaCon_Commission_Rule_ViewModel() { Group_Id = group_Id }).FirstOrDefault();
        }

        /// <summary>
        /// 保存投稿提成配置
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetTeacherContributeConfig(RB_TeaCon_Commission_Rule_ViewModel demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_TeaCon_Commission_Rule_ViewModel.Money), demodel.Money},
                    { nameof(RB_TeaCon_Commission_Rule_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_TeaCon_Commission_Rule_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_TeaCon_Commission_Rule_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum = OperatorEnum.Equal
                    }
                };
                bool flag = teaCon_Commission_RuleRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                bool flag = teaCon_Commission_RuleRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 获取投稿提成分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_TeaCon_Commission_Periods_ViewModel> GetTeaConCommissionPeriodsPageList(int pageIndex, int pageSize, out long count, RB_TeaCon_Commission_Periods_ViewModel dmodel)
        {
            var list = teaCon_Commission_PeriodsRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询财务单据
                string periodsIds = string.Join(",", list.Select(x => x.Id));
                var financeList = financeRepository.GetListSingle(new RB_Finance_Extend() { RB_Group_Id = dmodel.Group_Id, FinanceType = 2, OtherType = 47, ReFinanceIds = periodsIds, 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);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取投稿提成列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_TeaCon_Commission_Periods_ViewModel> GetTeaConCommissionPeriodsList(RB_TeaCon_Commission_Periods_ViewModel dmodel)
        {
            return teaCon_Commission_PeriodsRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取投稿用户提成列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_TeaCon_Commission_Details_ViewModel> GetTeaConCommissionUserList(RB_TeaCon_Commission_Details_ViewModel dmodel)
        {
            var list = teaCon_Commission_DetailsRepository.GetTeaConCommissionUserList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.TeacherId).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.TeacherId).FirstOrDefault();
                    item.TeacherName = 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 List<RB_TeaCon_Commission_Details_ViewModel> GetTeaConCommissionUserDetailList(RB_TeaCon_Commission_Details_ViewModel dmodel)
        {
            var list = teaCon_Commission_DetailsRepository.GetList(dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.TeacherId).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 conIds = string.Join(",", list.Select(x => x.ContributeId));
                var clist = contribute_InfoRepository.GetList(new Model.ViewModel.WeChat.RB_Contribute_Info_ViewModel() { Group_Id = dmodel.Group_Id, Q_ContributeIds = conIds });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.TeacherId).FirstOrDefault();
                    item.TeacherName = 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 ?? "";

                    var cmodel = clist.Where(x => x.Id == item.ContributeId).FirstOrDefault();
                    item.ContributeTitle = cmodel?.Title ?? "";
                    item.ContributeType = cmodel?.Type.ToName() ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取提成统计分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_TeaCon_Commission_Details_ViewModel> GetTeaConCommissionStatisticsPageList(int pageIndex, int pageSize, out long count, RB_TeaCon_Commission_Details_ViewModel dmodel)
        {
            var list = teaCon_Commission_DetailsRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                //查询用户 部门 校区
                string userIds = string.Join(",", list.Select(x => x.TeacherId).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 conIds = string.Join(",", list.Select(x => x.ContributeId));
                var clist = contribute_InfoRepository.GetList(new Model.ViewModel.WeChat.RB_Contribute_Info_ViewModel() { Group_Id = dmodel.Group_Id, Q_ContributeIds = conIds });

                foreach (var item in list)
                {
                    var umodel = ulist.Where(x => x.Id == item.TeacherId).FirstOrDefault();
                    item.TeacherName = 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 ?? "";

                    var cmodel = clist.Where(x => x.Id == item.ContributeId).FirstOrDefault();
                    item.ContributeTitle = cmodel?.Title ?? "";
                    item.ContributeType = cmodel?.Type.ToName() ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取累积金额
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public decimal GetTeaConCommissionStatistics(RB_TeaCon_Commission_Details_ViewModel dmodel)
        {
            return teaCon_Commission_DetailsRepository.GetTeaConCommissionStatistics(dmodel);
        }

        /// <summary>
        /// 创建投稿提成
        /// </summary>
        /// <param name="month"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetTeaConCommissionInfo(string month, UserInfo userInfo)
        {
            //首先查询该月是否已创建
            var plist = teaCon_Commission_PeriodsRepository.GetList(new RB_TeaCon_Commission_Periods_ViewModel() { Group_Id = userInfo.Group_Id, Periods = month });
            if (plist.Any())
            {
                return "当月提成已创建";
            }
            string EDate = Convert.ToDateTime(month + "-01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            var contributeList = contribute_InfoRepository.GetCanSendCommissionList(userInfo.Group_Id, EDate);
            if (contributeList.Any())
            {
                #region 基础数据
                //查询规则列表
                var ruleModel = teaCon_Commission_RuleRepository.GetList(new RB_TeaCon_Commission_Rule_ViewModel() { Group_Id = userInfo.Group_Id }).FirstOrDefault();
                if (ruleModel == null || ruleModel.Status == 1)
                {
                    return "未设置投稿提成配置";
                }
                //查询所有的人员
                var userIds = string.Join(",", contributeList.Select(x => x.CreateBy).Distinct());
                var UserList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = userIds });
                #endregion

                #region 开始创建
                var trans = teaCon_Commission_PeriodsRepository.DbTransaction;
                try
                {
                    int PeriodsId = teaCon_Commission_PeriodsRepository.Insert(new RB_TeaCon_Commission_Periods()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Financials = "",
                        Group_Id = userInfo.Group_Id,
                        Name = month + "期提成",
                        Periods = month,
                        SumPrice = 0
                    }, trans);
                    if (PeriodsId > 0)
                    {
                        decimal SumPrice = 0;
                        foreach (var item in contributeList)
                        {
                            var empModel = UserList.Where(x => x.Id == item.CreateBy).FirstOrDefault();
                            teaCon_Commission_DetailsRepository.Insert(new RB_TeaCon_Commission_Details_ViewModel()
                            {
                                Id = 0,
                                TeacherId = item.CreateBy,
                                ContributeId = item.Id,
                                PeriodId = PeriodsId,
                                Periods = item.PublishDate.Value.ToString("yyyy-MM"),
                                CommissionMoney = ruleModel.Money,
                                Depart_Id = empModel?.Dept_Id ?? 0,
                                School_Id = empModel?.School_Id ?? 0,
                                Group_Id = userInfo.Group_Id,
                                Remark = ""
                            }, trans);
                            SumPrice += ruleModel.Money;

                            #region 投稿更新
                            //查询这些投稿 更新为已发放提成
                            foreach (var ditem in contributeList)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(Model.ViewModel.WeChat.RB_Contribute_Info_ViewModel.CommissionMoney),ruleModel.Money},
                                    { nameof(Model.ViewModel.WeChat.RB_Contribute_Info_ViewModel.IsSendCommission),1}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(Model.ViewModel.WeChat.RB_Contribute_Info_ViewModel.Id),
                                          FiledValue=ditem.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                contribute_InfoRepository.Update(keyValues1, wheres1, trans);
                            }
                            #endregion
                        }

                        #region 更新累计应发                        
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Sell_Commission_Periods.SumPrice),SumPrice}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Sell_Commission_Periods.Id),
                                  FiledValue=PeriodsId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        teaCon_Commission_PeriodsRepository.Update(keyValues, wheres, trans);
                        #endregion
                    }
                    teaCon_Commission_PeriodsRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetTeaConCommissionInfo");
                    teaCon_Commission_PeriodsRepository.DBSession.Rollback();
                    return "出错了，请联系管理员";
                }
                #endregion
            }
            else {
                return "当月暂无可发放提成";
            }
            return "";
        }

        /// <summary>
        /// 获取提成可发放人员列表
        /// </summary>
        /// <param name="periodId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetTeaConCommissionSendEmployeeList(int periodId, UserInfo userInfo)
        {
            var model = teaCon_Commission_PeriodsRepository.GetEntity(periodId);
            if (model == null) { return "周期不存在"; }
            List<int> EmpIdList = new List<int>();
            if (!string.IsNullOrEmpty(model.EmpIds))
            {
                EmpIdList = JsonHelper.DeserializeObject<List<int>>("[" + model.EmpIds + "]");
            }
            var list = GetTeaConCommissionUserList(new RB_TeaCon_Commission_Details_ViewModel() { Group_Id = userInfo.Group_Id, PeriodId = periodId });
            return ApiResult.Success("", list.Select(x => new
            {
                x.TeacherId,
                x.TeacherName,
                x.CommissionMoney,
                IsGiveOut = EmpIdList.Contains(x.TeacherId) ? 1 : 2
            }));
        }

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

        #endregion
    }
}
