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

namespace Edu.Module.Course
{
    /// <summary>
    /// 教务奖励处理类
    /// </summary>
    public class 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_AccountRepository accountRepository = new RB_AccountRepository();
        /// <summary>
        /// 财务配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();


        #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 Model.Entity.Course.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 Model.Entity.Course.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 Model.Entity.Course.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 });

                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
                        });
                    }
                }
            }
            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_Time_ViewModel> timeList = new List<RB_Class_Time_ViewModel>();
            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>();
            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 });
                //查询签到数据
                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 });
            }
            var trans = teaching_BonusDetailRepository.DbTransaction;
            try
            {
                decimal TotalMoney = 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 = minute / configModel.BasicMinutes; // 未达到一课时时间  算不算一课时
                    //查询课单价
                    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 Model.Entity.Course.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 = dmodel.School_Id,
                        Status = 0,
                        TeacherId = item.TeacherId,
                        Type = item.TeacherId == item.Teacher_Id ? 1 : 2,
                        UnitPrice = unitPrice,
                        UpdateBy = dmodel.UpdateBy,
                        UpdateTime = DateTime.Now
                    }, trans);
                    TotalMoney += ksNum * unitPrice;
                }
                #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 qblist = blist.Where(x => x.TeacherId == item).OrderBy(x => x.UnitPrice).ThenBy(x => x.Date).ToList();
                        int BasicHours = configModel.BasicHours;
                        foreach (var qitem in qblist)
                        {
                            int 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);
        }



        #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 Model.Entity.Course.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 ksNum = TotalClassMin / configModel.BasicMinutes; // 未达到一课时时间  不算一课时

            //满班率
            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 Model.Entity.Course.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
    }
}
