using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Bonus;
using Edu.Model.ViewModel.Sell;
using Edu.Module.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Edu.WebApi.Controllers.Bonus
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class BonusController : BaseController
    {
        /// <summary>
        /// 获取课程顾问、市场达标奖金配置处理类对象
        /// </summary>
        private readonly BonusConfigModule bonusConfigModule = new BonusConfigModule();

        /// <summary>
        /// 员工人头奖励仓储层对象
        /// </summary>
        private readonly EmployeeBonusModule employeeBonusModule = AOP.AOPHelper.CreateAOPObject<EmployeeBonusModule>();

        #region 人头奖励配置
        /// <summary>
        /// 获取课程顾问、市场达标奖金配置分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetBounsPlanPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Bonus_PlanExtend()
            {
                PlanName = base.ParmJObj.GetStringValue("PlanName"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = bonusConfigModule.GetBounsPlanPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                string CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                result.Add(new
                {
                    item.Id,
                    item.PlanName,
                    item.BasicSalary,
                    item.OpenBonus,
                    item.WorkAgeSalary,
                    item.ClueNumSalary,
                    item.SaleIds,
                    item.UseCourseIds,
                    item.NotUseCourseIds,
                    CreateByName,
                    item.PlanType,
                    item.PlanTypeStr,
                    CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                    item.DetailList,
                    item.SaleList,
                    item.UseCourseList,
                    item.NotUseCourseList,
                    item.MonthGoalMoney,
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 新增修改课程顾问、市场达标奖金配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetBounsPlan()
        {
            var query = new RB_Bonus_PlanExtend()
            {
                Id = base.ParmJObj.GetInt("Id"),
                PlanType = base.ParmJObj.GetInt("PlanType"),
                PlanName = base.ParmJObj.GetStringValue("PlanName"),
                BasicSalary = base.ParmJObj.GetDecimal("BasicSalary"),
                OpenBonus = base.ParmJObj.GetDecimal("OpenBonus"),
                WorkAgeSalary = base.ParmJObj.GetDecimal("WorkAgeSalary"),
                ClueNumSalary = base.ParmJObj.GetDecimal("ClueNumSalary"),
                SaleIds = base.ParmJObj.GetStringValue("SaleIds"),
                UseCourseIds = base.ParmJObj.GetStringValue("UseCourseIds"),
                NotUseCourseIds = base.ParmJObj.GetStringValue("NotUseCourseIds"),
                MonthGoalMoney = base.ParmJObj.GetDecimal("MonthGoalMoney"),
            };
            query.CreateBy = base.UserInfo.Id;
            query.UpdateBy = base.UserInfo.Id;
            query.CreateTime = DateTime.Now;
            query.UpdateTime = DateTime.Now;
            query.Group_Id = base.UserInfo.Group_Id;
            query.Status = Common.Enum.DateStateEnum.Normal;
            query.DetailList = new List<RB_Bouns_PlanDetail_Extend>();
            string detailList = base.ParmJObj.GetStringValue("DetailList");
            if (!string.IsNullOrEmpty(detailList))
            {
                JArray jarray = JArray.Parse(detailList);
                if (jarray != null && jarray.Count > 0)
                {
                    foreach (var jItem in jarray)
                    {
                        JObject jobj = JObject.Parse(jItem.ToString());
                        query.DetailList.Add(new RB_Bouns_PlanDetail_Extend()
                        {
                            DetailId = jobj.GetInt("DetailId"),
                            PlanId = jobj.GetInt("PlanId"),
                            StartNum = jobj.GetDecimal("StartNum"),
                            EndNum = jobj.GetDecimal("EndNum"),
                            Money = jobj.GetDecimal("Money"),
                        });
                    }
                }
            }
            bool flag = bonusConfigModule.SetBonusPlanModule(query);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 根据编号获取课程顾问、市场达标奖金配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetBonusPlan()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var model = bonusConfigModule.GetBonusPlanModule(Id);
            return ApiResult.Success(data: model);
        }


        /// <summary>
        /// 根据编号删除课程顾问、市场达标奖金配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveBonusPlan()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var flag = bonusConfigModule.RemoveBonusPlanModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion

        #region  员工人头奖励

        /// <summary>
        /// 生成员工人头奖励
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CreateEmpBonus()
        {
            var userInfo = base.UserInfo;
            var startDate = base.ParmJObj.GetStringValue("StartDate");
            bool flag= employeeBonusModule.CreateEmployeeBonusModule(userInfo, out string message, startDate);
            return flag ? ApiResult.Success() : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 订单金额发生改变
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEmployeeBounsIssue()
        {
            //订单改变
            var Ids = base.ParmJObj.GetStringValue("Ids");
            bool flag = employeeBonusModule.SetEmployeeBounsIsIssueModule(Ids);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 订单金额发生改变
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ChangeOrder()
        {
            //订单改变
            var OrderId = base.ParmJObj.GetInt("OrderId");
            employeeBonusModule.ChangeEmployeeBonusModule(OrderId);
            return ApiResult.Success();
        }

        /// <summary>
        /// 获取人头奖励分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPersonnelPeriodPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Personnel_Period_Extend()
            {
                
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = employeeBonusModule.GetPersonnelPeriodPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                string CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                result.Add(new
                {
                    item.Id,
                    item.Name,
                    item.Periods,
                    item.SumPrice,
                    item.Remark,
                    CreateByName,
                    item.Financials,
                    CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                    item.BonusList,
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取员工期数提成明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPersonnelPeriodDetails()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Personnel_Bonus_Extend()
            {
                PeriodId = base.ParmJObj.GetInt("PeriodId")
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = employeeBonusModule.GetPersonnelBonusPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                string EmployeeName = UserReidsCache.GetUserLoginInfo(item.EmployeeId)?.AccountName ?? "";
                string CreateByName= UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                result.Add(new
                {
                    item.Id,
                    item.PeriodId,
                    item.PlanId,
                    item.PlanType,
                    item.YearNum,
                    item.MonthNum,
                    item.EmployeeId,
                    EmployeeName,
                    item.CurGuestNum,
                    item.CurRewardMoney,
                    item.CurOrderMoney,
                    item.DeductionMoney,
                    item.FinishDeductionMoney,
                    item.CreateBy,
                    CreateByName,
                    CreateTime=Common.ConvertHelper.FormatTime(item.CreateTime),
                    item.IsReach,
                    IsReachStr= item.IsReach==1?"已达标":"未达标",
                    item.OpenBonus,
                    item.ClueNumSalary,
                    item.BeforeMoney,
                    item.DetailList,
                    item.DeductionList,
                    item.BonusLogList,
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }
        #endregion
    }
}
