using System;
using System.Collections.Generic;
using System.Linq;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Log;
using Edu.Module.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Course
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class TeachingRewardsController : BaseController
    {
        /// <summary>
        /// 教务奖励处理类对象
        /// </summary>
        private readonly TeachingRewardsModule teachingRewardsModule = AOP.AOPHelper.CreateAOPObject<TeachingRewardsModule>();

        #region 基础配置

        /// <summary>
        /// 获取教务奖励列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeachingRewardsList()
        {
            var userInfo = base.UserInfo;
            RB_Teaching_Rewards_Rate_ViewModel demodel = JsonHelper.DeserializeObject<RB_Teaching_Rewards_Rate_ViewModel>(RequestParm.Msg.ToString());
            if (demodel.Type <= 0) {
                return ApiResult.ParamIsNull();
            }

            var list = teachingRewardsModule.GetTeachimgRewardsList(demodel, userInfo, out List<RB_Teaching_Rewards_Rate_ViewModel> fclist);

            return ApiResult.Success("", new
            {
                FullClassRateList = fclist.Select(x => new
                {
                    x.Id,
                    x.StartValue,
                    x.EndValue
                }),
                List = list.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
                    })
                })
            });
        }

        /// <summary>
        /// 保存教务奖励配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingRewardsInfo()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int Type = parms.GetInt("Type", 0);
            string list = parms.GetStringValue("List");
            if (string.IsNullOrEmpty(list))
            {
                return ApiResult.ParamIsNull("请传递比例列表");
            }
            List<RB_Teaching_Rewards_Rate_ViewModel> deList = JsonHelper.DeserializeObject<List<RB_Teaching_Rewards_Rate_ViewModel>>(list);
            if (deList == null || !deList.Any())
            {
                return ApiResult.ParamIsNull("请传递比例列表");
            }
            decimal xcrate = -1;
            foreach (var item in deList) {
                if (item.StartValue < 0) {
                    return ApiResult.ParamIsNull("比率不能小于0");
                }
                if (item.EndValue < 0) {
                    return ApiResult.ParamIsNull("比率不能小于0");
                }
                if (item.StartValue > item.EndValue) {
                    return ApiResult.ParamIsNull("起始值不能大于结束值");
                }
                if (item.StartValue <= xcrate){
                    return ApiResult.ParamIsNull("续学率有重复，请核实后再试");
                }
                xcrate = item.EndValue;

                if (item.FullClassList == null || !item.FullClassList.Any())
                {
                    return ApiResult.ParamIsNull("请传递满班率列表");
                }
                decimal mbrate = -1;
                foreach (var qitem in deList) {
                    if (qitem.StartValue < 0)
                    {
                        return ApiResult.ParamIsNull("比率不能小于0");
                    }
                    if (qitem.EndValue < 0)
                    {
                        return ApiResult.ParamIsNull("比率不能小于0");
                    }
                    if (qitem.StartValue > qitem.EndValue)
                    {
                        return ApiResult.ParamIsNull("起始值不能大于结束值");
                    }
                    if (qitem.StartValue <= mbrate)
                    {
                        return ApiResult.ParamIsNull("续学率有重复，请核实后再试");
                    }
                    mbrate = qitem.EndValue;
                    if (qitem.ClassMoney < 0) { return ApiResult.Failed("奖金/课时费不能小于0"); }
                    if (Type == 2 || Type == 4) {
                        if (qitem.PeopelNum < 0)
                        {
                            return ApiResult.Failed("增加带班人数不正确");
                        }
                    }
                }
            }

            var flag = teachingRewardsModule.SetTeachingRewardsInfo(Type, deList, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取教务奖励 基础
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeachingRewardsBaseInfo()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int Type = parms.GetInt("Type", 1);// 类型  1社会班   2学生班
            if (Type <= 0) {
                return ApiResult.ParamIsNull();
            }

            var model = teachingRewardsModule.GetTeachingRewardsBaseInfo(Type, userInfo);
            return ApiResult.Success("", model);
        }

        /// <summary>
        /// 保存教务奖励  基础
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingRewardsBase() {
            var userInfo = base.UserInfo;
            RB_Teaching_Rewards_Base_ViewModel demodel = JsonHelper.DeserializeObject<RB_Teaching_Rewards_Base_ViewModel>(RequestParm.Msg.ToString());
            if (demodel.Type <= 0) {
                return ApiResult.ParamIsNull();
            }

            demodel.Group_Id = userInfo.Group_Id;
            demodel.School_Id = userInfo.School_Id;
            demodel.CreateBy = userInfo.Id;
            demodel.CreateTime = DateTime.Now;
            demodel.UpdateBy = userInfo.Id;
            demodel.UpdateTime = DateTime.Now;
            bool flag = teachingRewardsModule.SetTeachingRewardsBase(demodel, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 教师奖励

        /// <summary>
        /// 教师奖励分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeachingBonusPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_Bonus_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            if (!string.IsNullOrEmpty(dmodel.Month))
            {
                dmodel.Month = Convert.ToDateTime(dmodel.Month).ToString("yyyy-MM");
            }

            var list = teachingRewardsModule.GetTeachingBonusPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.Month,
                x.Money,
                x.FinanceId,
                FrIdList = string.IsNullOrEmpty(x.FinanceId) ? new List<string>() : x.FinanceId.Split(',').ToList(),
                x.State,
                StateName = x.State.ToName(),
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                TeacherList = x.TeacherList.Select(z => new
                {
                    z.TeacherId,
                    z.TeacherName,
                    z.Money
                })
            });

            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取教师奖励明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeachingBonusDetailList()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_BonusDetail_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            if (dmodel.BonusId <= 0)
            {
                return ApiResult.ParamIsNull("请传递教师奖励id");
            }

            var list = teachingRewardsModule.GetTeachingBonusDetailList(dmodel);
            var slit = teachingRewardsModule.GetTeachingBonusStatistics(dmodel);

            return ApiResult.Success("", new
            {
                List = list.Select(x => new
                {
                    x.Id,
                    Date = x.Date.ToString("yyyyMMdd"),
                    x.TeacherId,
                    x.TeacherName,
                    x.ClassId,
                    x.ClassName,
                    x.ClassNo,
                    x.Type,
                    x.CourseHour,
                    x.DeductionHour,
                    x.UnitPrice,
                    x.CheckInNum,
                    x.Money
                }),
                Statistics = slit.Select(x => new
                {
                    x.TeacherId,
                    x.TeacherName,
                    x.UnitPrice,
                    x.CourseHour,
                    x.DCourseHour,
                    x.DeductionHour,
                    x.Money
                })
            });
        }

        /// <summary>
        /// 教师奖励明细Excel下载
        /// </summary>
        [HttpPost]
        [Obsolete]
        public FileContentResult GetTeachingBonusDetailToExcel()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_BonusDetail_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            string ExcelName = "教师奖励" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (dmodel.BonusId <= 0)
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "日期") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "老师") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "班号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "班级") { CellWidth = 25, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "基础课时") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "带班课时") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "课单价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "签到人数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "小计") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            slist.Add(header);

            try
            {
                var list = teachingRewardsModule.GetTeachingBonusDetailList(dmodel);
                var slit = teachingRewardsModule.GetTeachingBonusStatistics(dmodel);
                #region 组装数据
                foreach (var item in list)
                {
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value: item.Date.ToString("yyyyMMdd")){ },
                            new ExcelColumn(value: item.TeacherName){ },
                            new ExcelColumn(value: item.ClassNo){ },
                            new ExcelColumn(value: item.ClassName){ },
                            new ExcelColumn(value: item.Type==1?"带班":"代课"){ },
                            new ExcelColumn(value: item.DeductionHour.ToString()){ },
                            new ExcelColumn(value: item.CourseHour.ToString()){ },
                            new ExcelColumn(value: item.UnitPrice.ToString("#0.00")){ },
                            new ExcelColumn(value: item.CheckInNum.ToString()){ },
                            new ExcelColumn(value: item.Money.ToString("#0.00")){ },
                        }
                    };
                    slist.Add(datarow);
                }

                //统计
                ExcelDataSource datarows = new ExcelDataSource()
                {
                    ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                        }
                };
                slist.Add(datarows);
                datarows = new ExcelDataSource()
                {
                    ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value: "老师"){ },
                            new ExcelColumn(value: "基础课时"){ },
                            new ExcelColumn(value: "带班课时"){ },
                            new ExcelColumn(value: "代课课时"){ },
                            new ExcelColumn(value: "课时单价"){ },
                            new ExcelColumn(value: "合计"){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                        }
                };
                slist.Add(datarows);
                foreach (var item in slit)
                {
                    datarows = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value: item.TeacherName){ },
                            new ExcelColumn(value: item.DeductionHour.ToString()){ },
                            new ExcelColumn(value: item.CourseHour.ToString()){ },
                            new ExcelColumn(value: item.DCourseHour.ToString()){ },
                            new ExcelColumn(value: item.UnitPrice.ToString("#0.00")){ },
                            new ExcelColumn(value: item.Money.ToString("#0.00")){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                        }
                    };
                    slist.Add(datarows);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetTeachingBonusDetailToExcel: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 教师奖励状态设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingBonusState()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int BonusId = parms.GetInt("BonusId", 0);
            int Type = parms.GetInt("Type", 0);//类型  1确认  2取消

            if (BonusId <= 0)
            {
                return ApiResult.ParamIsNull("请传递教师奖励id");
            }
            bool flag = teachingRewardsModule.SetTeachingBonusState(BonusId, Type, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 新增教师奖励
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingBonusAdd()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_Bonus_ViewModel>(RequestParm.Msg.ToString());
            if (string.IsNullOrEmpty(dmodel.Month))
            {
                return ApiResult.ParamIsNull("请选择月份");
            }
            if (Convert.ToDateTime(dmodel.Month) >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM")))
            {
                return ApiResult.ParamIsNull("只能选择之前月份");
            }
            if (string.IsNullOrEmpty(dmodel.TeacherIds))
            {
                return ApiResult.ParamIsNull("请选择老师");
            }

            dmodel.Month = Convert.ToDateTime(dmodel.Month).ToString("yyyy-MM");
            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.School_Id = userInfo.School_Id;
            dmodel.UpdateBy = userInfo.Id;
            dmodel.UpdateTime = DateTime.Now;
            dmodel.CreateBy = userInfo.Id;
            dmodel.CreateTime = DateTime.Now;
            string msg = teachingRewardsModule.SetTeachingBonusAdd(dmodel, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 教师奖金制单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingBonusFinance()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int BonusId = parms.GetInt("BonusId", 0);
            int IsPublic = parms.GetInt("IsPublic", 0);
            int CurrencyId = parms.GetInt("CurrencyId", 0);
            if (BonusId <= 0) {
                return ApiResult.ParamIsNull();
            }
            if (CurrencyId <= 0) {
                return ApiResult.ParamIsNull();
            }

            string msg = teachingRewardsModule.SetTeachingBonusFinance(BonusId, IsPublic, CurrencyId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetBonusStateEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(BonusStateEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }
        #endregion

        #region 教师绩效

        /// <summary>
        /// 教师绩效分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeachingPerfPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_Perf_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;

            var list = teachingRewardsModule.GetTeachingPerfPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.TeacherId,
                x.TeacherIcon,
                x.TeacherName,
                x.BaseHourFee,
                x.AddHourFee,
                x.BaseStuNum,
                x.AddStuNum,
                x.ClassName,
                x.ClassPeopelNum,
                x.EndDate,
                x.ConfirmDate,
                x.FullClassRate,
                x.AvgCheckRate,
                x.ClassHours,
                x.UnitPrice,
                x.Money,
                x.FinanceId,
                x.PerfState,
                PerfStateName = x.PerfState.ToName(),
                RemarkList = x.RemarkList.Select(z => new
                {
                    z.Id,
                    z.Content,
                    CreateBy = UserReidsCache.GetUserLoginInfo(z.CreateBy)?.AccountName ?? "",
                    CreateTime = z.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                }),
                x.UpdateBy,
                UpdateByName = UserReidsCache.GetUserLoginInfo(x.UpdateBy)?.AccountName ?? "",
                UpdateTime = x.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                JJList = x.JJList.OrderBy(z => z.StartValue).Select(z=>new { 
                    z.Id,
                    z.StartValue,
                    z.EndValue,
                    FullClassList = z.FullClassList.OrderBy(y => y.StartValue).Select(y=>new { 
                        y.Id,
                        y.StartValue,
                        y.EndValue,
                        y.ClassMoney,
                        y.PeopelNum
                    })
                }),
                JJFullRate = GetFullRateList(x.JJList).Select(y=>new {
                    y.Id,
                    y.StartValue,
                    y.EndValue
                }),
                KSList = x.KSList.OrderBy(z => z.StartValue).Select(z => new {
                    z.Id,
                    z.StartValue,
                    z.EndValue,
                    FullClassList = z.FullClassList.OrderBy(y => y.StartValue).Select(y => new {
                        y.Id,
                        y.StartValue,
                        y.EndValue,
                        y.ClassMoney,
                        y.PeopelNum
                    })
                }),
                KSFullRate = GetFullRateList(x.KSList).Select(y => new {
                    y.Id,
                    y.StartValue,
                    y.EndValue
                }),
            });

            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取满班率
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<RB_Teaching_Rewards_Rate_ViewModel> GetFullRateList(List<RB_Teaching_Rewards_Rate_ViewModel> list)
        {
            if (list.Any())
            {
                return list.FirstOrDefault().FullClassList.OrderBy(x => x.StartValue).ToList();
            }
            return new List<RB_Teaching_Rewards_Rate_ViewModel>();
        }

        /// <summary>
        /// 修改备注
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingPerfRemark() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int PerfId = parms.GetInt("PerfId", 0);
            string Remark = parms.GetStringValue("Remark");
            if (PerfId <= 0) {
                return ApiResult.ParamIsNull();
            }

            bool flag = teachingRewardsModule.SetTeachingPerfRemark(PerfId, Remark, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置教师绩效状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingPerfState()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int PerfId = parms.GetInt("PerfId", 0);
            int Type = parms.GetInt("Type", 0);// 类型  1确认绩效  2不发放绩效  3恢复绩效  4撤销绩效
            if (PerfId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = teachingRewardsModule.SetTeachingPerfState(PerfId, Type, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 生成绩效
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingPerfCreate()
        {            
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int ClassId = parms.GetInt("ClassId", 0);
            if (ClassId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = teachingRewardsModule.SetTeachingPerfCreate(ClassId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 绩效一键制单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingPerfFinance()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int PerfId = parms.GetInt("PerfId", 0);
            int IsPublic = parms.GetInt("IsPublic", 0);
            int CurrencyId = parms.GetInt("CurrencyId", 0);
            if (PerfId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = teachingRewardsModule.SetTeachingPerfFinance(PerfId, IsPublic, CurrencyId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 绩效消息推送
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingPerfPush()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int PerfId = parms.GetInt("PerfId", 0);
            if (PerfId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = teachingRewardsModule.SetTeachingPerfPush(PerfId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 我的统计

        /// <summary>
        /// 获取我的教师奖励统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyTeachingBonusStatistics() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int MonthNum = parms.GetInt("MonthNum", 6);//
            if (MonthNum < 1) {
                return ApiResult.ParamIsNull();
            }

            return teachingRewardsModule.GetMyTeachingBonusStatistics(MonthNum, userInfo);
        }

        /// <summary>
        /// 获取历史课时费上涨分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyTeachingBonusHistoryPageList() {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_Perf_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.Q_IsComfirm = 1;
            dmodel.TeacherId = teachingRewardsModule.GetAccountTeacherId(userInfo.Id);
            if (dmodel.TeacherId <= 0)
            {
                return ApiResult.ParamIsNull("非教师，无法查询");
            }

            var list = teachingRewardsModule.GetMyTeachingBonusHistoryPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.BaseHourFee,
                x.AddHourFee,
                x.BaseStuNum,
                x.AddStuNum,
                x.ClassName,
                x.ConfirmDate,
                ConfirmDateStr = x.ConfirmDate.HasValue ? x.ConfirmDate.Value.ToString("yyyy-MM-dd") : "",
                x.FullClassRate,
                x.AvgCheckRate,
                x.ClassHours
            });

            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取我的教师奖励明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyTeachingBonusDetailList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_BonusDetail_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            if (string.IsNullOrEmpty(dmodel.Month))
            {
                return ApiResult.ParamIsNull("请传递期数");
            }
            dmodel.Q_BonusConfirm = 1;
            dmodel.Month = Convert.ToDateTime(dmodel.Month).ToString("yyyy-MM");
            dmodel.TeacherId = teachingRewardsModule.GetAccountTeacherId(userInfo.Id);
            if (dmodel.TeacherId <= 0)
            {
                return ApiResult.ParamIsNull("非教师，无法查询");
            }

            var list = teachingRewardsModule.GetMyTeachingBonusDetailPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            decimal TotalMoney = teachingRewardsModule.GetTeachingBonusDetailTotalMoney(dmodel);

            return ApiResult.Success("", new
            {
                List = list.Select(x => new
                {
                    x.Id,
                    Date = x.Date.ToString("yyyy-MM-dd"),
                    x.ClassId,
                    x.ClassName,
                    x.Type,
                    x.CourseHour,
                    x.UnitPrice,
                    x.CheckInNum,
                    x.Money
                }),
                TotalMoney
            });
        }

        /// <summary>
        /// 教师绩效分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyTeachingPerfPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Teaching_Perf_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.Q_IsComfirm = 1;
            dmodel.TeacherId = teachingRewardsModule.GetAccountTeacherId(userInfo.Id);
            if (dmodel.TeacherId <= 0)
            {
                return ApiResult.ParamIsNull("非教师，无法查询");
            }

            var list = teachingRewardsModule.GetTeachingPerfPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            decimal TotalMoney = teachingRewardsModule.GetMyTeachingPerfTotalMoney(dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = new { 
                List = list.Select(x => new
                {
                    x.Id,
                    x.BaseHourFee,
                    x.AddHourFee,
                    x.BaseStuNum,
                    x.AddStuNum,
                    x.ClassName,
                    x.ClassPeopelNum,
                    x.EndDate,
                    x.ConfirmDate,
                    x.FullClassRate,
                    x.AvgCheckRate,
                    x.ClassHours,
                    x.UnitPrice,
                    x.Money,
                    x.PerfState,
                    PerfStateName = x.PerfState.ToName(),
                    JJList = x.JJList.OrderBy(z => z.StartValue).Select(z => new {
                        z.Id,
                        z.StartValue,
                        z.EndValue,
                        FullClassList = z.FullClassList.OrderBy(y => y.StartValue).Select(y => new {
                            y.Id,
                            y.StartValue,
                            y.EndValue,
                            y.ClassMoney,
                            y.PeopelNum
                        })
                    }),
                    JJFullRate = GetFullRateList(x.JJList).Select(y => new {
                        y.Id,
                        y.StartValue,
                        y.EndValue
                    }),
                    KSList = x.KSList.OrderBy(z => z.StartValue).Select(z => new {
                        z.Id,
                        z.StartValue,
                        z.EndValue,
                        FullClassList = z.FullClassList.OrderBy(y => y.StartValue).Select(y => new {
                            y.Id,
                            y.StartValue,
                            y.EndValue,
                            y.ClassMoney,
                            y.PeopelNum
                        })
                    }),
                    KSFullRate = GetFullRateList(x.KSList).Select(y => new {
                        y.Id,
                        y.StartValue,
                        y.EndValue
                    }),
                }),
                TotalMoney
            };

            return ApiResult.Success("", pageModel);
        }

        #endregion

        #region 财务配置

        /// <summary>
        /// 获取列表  没用
        /// </summary>
        /// <returns></returns>
        public ApiResult GetFinanceConfigList()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int Type = parms.GetInt("Type", 0);

            var list = teachingRewardsModule.GetFinanceConfigList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = (FinanceConfigTypeEnum)Type });
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Type,
            }));
        }

        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetFinanceConfigEnumList()
        {
            var list = EnumHelper.EnumToList(typeof(FinanceConfigTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                x.Name,
                x.Id
            }));
        }

        /// <summary>
        /// 获取财务配置
        /// </summary>
        /// <returns></returns>
        public ApiResult GetFinanceConfigInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int Type = parms.GetInt("Type", 0);
            if (Type <= 0) { return ApiResult.ParamIsNull(); }

            var model = teachingRewardsModule.GetFinanceConfigInfo(Type, userInfo);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Type,
                model.CostTypeId,
                model.TempleteId
            });
        }

        /// <summary>
        /// 新增财务配置
        /// </summary>
        /// <returns></returns>
        public ApiResult SetFinanceConfigInfo()
        {
            var userInfo = base.UserInfo;
            RB_Finance_Config_ViewModel dmodel = JsonHelper.DeserializeObject<RB_Finance_Config_ViewModel>(RequestParm.Msg.ToString());
            if (dmodel.Type <= 0) {
                return ApiResult.ParamIsNull("请传递类型");
            }
            if (dmodel.CostTypeId <= 0) {
                return ApiResult.ParamIsNull("请选择费用类型");
            }
            if (dmodel.TempleteId <= 0) {
                return ApiResult.ParamIsNull("请选择流程");
            }

            dmodel.Group_Id = userInfo.Group_Id;
            dmodel.School_Id = userInfo.School_Id;
            dmodel.Status = 0;
            dmodel.CreateBy = userInfo.Id;
            dmodel.CreateTime = DateTime.Now;
            dmodel.UpdateBy = userInfo.Id;
            dmodel.UpdateTime = DateTime.Now;
            bool flag = teachingRewardsModule.SetFinanceConfigInfo(dmodel, userInfo);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        #endregion

        #region  课时费发放

        /// <summary>
        /// 获取提成可发放人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeachingRewardsSendEmployeeList()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int PeriodId = parms.GetInt("PeriodId", 0);//期数id
            if (PeriodId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var list = teachingRewardsModule.GetTeachingRewardsSendEmployeeList(PeriodId, userInfo);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 设置提成发放人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeachingRewardsSendEmployee()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int PeriodId = parms.GetInt("PeriodId", 0);//期数id
            string EmpIds = parms.GetStringValue("EmpIds");//人员列表
            if (PeriodId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (string.IsNullOrEmpty(EmpIds))
            {
                return ApiResult.ParamIsNull("请传递用户id");
            }

            string msg = teachingRewardsModule.SetTeachingRewardsSendEmployee(PeriodId, EmpIds, userInfo);
            if (msg == "")
            {
                return ApiResult.Success("");
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion
    }
}
