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 SellCommissionController : BaseController
    {
        /// <summary>
        /// 教务奖励处理类对象
        /// </summary>
        private readonly SellCommissionModule sellCommissionModule = new SellCommissionModule();

        #region 规则配置

        /// <summary>
        /// 获取销售规则列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionRuleList()
        {
            var userInfo = base.UserInfo;
            var list = sellCommissionModule.GetSellCommissionRuleList(userInfo.Group_Id);
            decimal FirstRate = 0;
            if (list.Any()) {
                FirstRate = list.FirstOrDefault()?.FirstRate ?? 0;
            }

            return ApiResult.Success("", new
            {
                FirstRate,
                List = list.Select(x => new
                {
                    x.Id,
                    x.ClassType,
                    x.EnrollType,
                    x.SalesRate,
                    x.TeacherRate,
                    x.AssistantRate
                })
            });
        }

        /// <summary>
        /// 保存销售规则配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSellCommissionRule()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            decimal FirstRate = parms.GetDecimal("FirstRate");//首次发放比例
            if (FirstRate <= 0)
            {
                return ApiResult.ParamIsNull("请输入首次发放比例");
            }
            string list = parms.GetStringValue("List");
            if (string.IsNullOrEmpty(list))
            {
                return ApiResult.ParamIsNull("请传递比例列表");
            }
            List<RB_Sell_Commission_Rule_ViewModel> deList = JsonHelper.DeserializeObject<List<RB_Sell_Commission_Rule_ViewModel>>(list);
            if (!deList.Any())
            {
                return ApiResult.ParamIsNull("请传递比例列表");
            }
            foreach (var item in deList)
            {
                if (item.SalesRate <= 0) {
                    return ApiResult.ParamIsNull("销售比例不能小于等于0");
                }
                if (item.TeacherRate <= 0) {
                    return ApiResult.ParamIsNull("教师比例不能小于等于0");
                }
                if (item.AssistantRate < 0) {
                    return ApiResult.ParamIsNull("助教比例不能小于0");
                }
            }

            var flag = sellCommissionModule.SetSellCommissionRule(FirstRate, deList, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 提成列表

        /// <summary>
        /// 获取提成期数分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionPeriodsPageList()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Periods_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;

            var list = sellCommissionModule.GetSellCommissionPeriodsPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.Periods,
                x.SumPrice,
                x.SchooldCommission,
                x.Name,
                FrIdList = string.IsNullOrEmpty(x.Financials) ? new List<string>() : x.Financials.Split(',').ToList(),
                x.CreateBy,
                CreateByName = UserReidsCache.GetUserLoginInfo(x.CreateBy)?.AccountName ?? "",
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd")
            });

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

        /// <summary>
        /// 获取期数列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionPeriodsList() {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Periods_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;

            var list = sellCommissionModule.GetSellCommissionPeriodsList(dmodel);

            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Periods,                
                x.Name,
            }));
        }

        /// <summary>
        /// 获取提成用户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionUserList() {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Details_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            if (dmodel.PeriodId <= 0) {
                return ApiResult.ParamIsNull("请传递期数id");
            }

            var list = sellCommissionModule.GetSellCommissionUserList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.School_Id,
                x.SchoolName,
                x.Depart_Id,
                x.DeptName,
                x.UserId,
                x.UserName,
                x.StudentCount,
                x.CurrentPeriodMoney,
                x.CurrentExtraMoney,
                CommissionMoney = x.CurrentPeriodMoney + x.CurrentExtraMoney
            }));
        }

        /// <summary>
        /// 获取提成用户明细列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionUserDetailList()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Details_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            if (dmodel.PeriodId <= 0)
            {
                return ApiResult.ParamIsNull("请传递期数id");
            }

            var list = sellCommissionModule.GetSellCommissionUserDetailList_V2(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.School_Id,
                x.SchoolName,
                x.Depart_Id,
                x.DeptName,
                x.UserId,
                x.UserName,
                x.ClassId,
                x.ClassName,
                x.ClassNo,
                x.ClassType,
                x.ClassTypeName,
                x.OrderId,
                x.IssueNum,
                x.StudentCount,
                x.Periods,
                TotalCommissionMoney = x.CommissionMoney + x.OtherMoney + x.BackMoney,
                x.OtherMoney,
                x.BackMoney,
                x.GiveOutMoney,
                x.IsFirstCommission,
                x.TotalHours,
                x.TotalLearn,
                x.CurrentHours,
                x.IsContinueClass,
                x.Remark,
                x.CurrentPeriodMoney,
                x.CurrentExtraMoney,
                x.DeductionMoney,
                x.DeductionExtraMoney,
                YFMoney = x.CurrentPeriodMoney + x.CurrentExtraMoney + x.DeductionMoney + x.DeductionExtraMoney
            }));
        }

        /// <summary>
        /// 获取提成订单明细列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionForOrderList()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Details_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            if (dmodel.OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单id");
            }

            var list = sellCommissionModule.GetSellCommissionUserDetailList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.School_Id,
                x.SchoolName,
                x.Depart_Id,
                x.DeptName,
                x.UserId,
                x.UserName,
                x.ClassId,
                x.ClassName,
                x.ClassNo,
                x.ClassType,
                x.ClassTypeName,
                x.OrderId,
                x.StudentCount,
                x.Periods,
                TotalCommissionMoney = x.CommissionMoney + x.OtherMoney + x.BackMoney,
                x.OtherMoney,
                x.BackMoney,
                x.GiveOutMoney,
                x.IsFirstCommission,
                x.TotalHours,
                x.TotalLearn,
                x.CurrentHours,
                x.IsContinueClass,
                x.Remark,
                x.CurrentPeriodMoney,
                x.CurrentExtraMoney,
                x.DeductionMoney,
                x.DeductionExtraMoney,
                YFMoney = x.CurrentPeriodMoney + x.CurrentExtraMoney + x.DeductionMoney + x.DeductionExtraMoney
            }));
        }

        /// <summary>
        /// 提成统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionStatistics() {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Details_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;

            var list = sellCommissionModule.GetSellCommissionStatisticsPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            decimal TotalMoney = sellCommissionModule.GetSellCommissionStatistics(dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = new
            {
                TotalCommission = TotalMoney,
                List = list.Select(x => new
                {
                    x.School_Id,
                    x.SchoolName,
                    x.Depart_Id,
                    x.DeptName,
                    x.UserId,
                    x.UserName,
                    x.ClassId,
                    x.ClassName,
                    x.ClassNo,
                    x.ClassType,
                    x.ClassTypeName,
                    x.OrderId,
                    x.StudentCount,
                    x.Periods,
                    TotalCommissionMoney = x.CommissionMoney + x.OtherMoney + x.BackMoney,
                    x.OtherMoney,
                    x.BackMoney,
                    x.GiveOutMoney,
                    x.IsFirstCommission,
                    x.TotalHours,
                    x.TotalLearn,
                    x.CurrentHours,
                    x.IsContinueClass,
                    x.Remark,
                    x.CurrentPeriodMoney,
                    x.CurrentExtraMoney,
                    x.DeductionMoney,
                    x.DeductionExtraMoney,
                    YFMoney = x.CurrentPeriodMoney + x.CurrentExtraMoney + x.DeductionMoney + x.DeductionExtraMoney
                })
            };
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 导出提成统计 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult GetSellCommissionStatisticsToExcel() {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Sell_Commission_Details_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;
            string ExcelName = "销售提成" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            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 = 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 },
                    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 },
                    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 },
                    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 = sellCommissionModule.GetSellCommissionStatisticsPageList(1, 1000000, out long count, dmodel);
                decimal TotalMoney = sellCommissionModule.GetSellCommissionStatistics(dmodel);
                #region 组装数据
                foreach (var item in list)
                {
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value: item.SchoolName){ },
                            new ExcelColumn(value: item.DeptName){ },
                            new ExcelColumn(value: item.UserName){ },
                            new ExcelColumn(value: item.ClassNo){ },
                            new ExcelColumn(value: item.ClassName + (item.IsContinueClass == 1 ? " 续班" : "")){ },
                            new ExcelColumn(value: item.ClassTypeName){ },
                            new ExcelColumn(value: item.StudentCount.ToString()){ },
                            new ExcelColumn(value: item.OrderId.ToString()){ },
                            new ExcelColumn(value: (item.CommissionMoney + item.OtherMoney + item.BackMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.OtherMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.BackMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.GiveOutMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: item.IsFirstCommission == 1 ?"是":"否"){ },
                            new ExcelColumn(value: item.TotalHours.ToString()){ },
                            new ExcelColumn(value: item.TotalLearn.ToString()){ },
                            new ExcelColumn(value: item.CurrentHours == -1 ?"-": item.CurrentHours.ToString()){ },
                            new ExcelColumn(value: (item.CurrentPeriodMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.CurrentExtraMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.DeductionMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.DeductionExtraMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: (item.CurrentPeriodMoney + item.CurrentExtraMoney + item.DeductionMoney + item.DeductionExtraMoney).ToString("#0.00")){ },
                            new ExcelColumn(value: item.Periods){ },
                            new ExcelColumn(value: item.Remark){ },
                        },
                        ColumnHight = 30
                    };
                    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: ""){ },
                            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: ""){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: TotalMoney.ToString("#0.00")){ },
                            new ExcelColumn(value: ""){ },
                            new ExcelColumn(value: ""){ },
                        },
                    ColumnHight = 30
                };
                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 SetSellCommissionInfo() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            string Month = parms.GetStringValue("Month");//月份
            if (string.IsNullOrEmpty(Month)) {
                return ApiResult.ParamIsNull();
            }
            try
            {
                Month = Convert.ToDateTime(Month + "-01").ToString("yyyy-MM");
            }
            catch (Exception)
            {
                return ApiResult.Failed("日期格式有误");
            }

            string msg = sellCommissionModule.SetSellCommissionInfo(Month, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 验证用户离职 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserLeaveOrderCommission() {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(RequestParm.Msg.ToString());
            int UserId = parms.GetInt("UserId", 0);
            if (UserId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = sellCommissionModule.GetUserLeaveOrderCommission(UserId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success("暂无需补交订单");
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取提成可发放人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellCommissionSendEmployeeList() {
            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 = sellCommissionModule.GetSellCommissionSendEmployeeList(PeriodId, userInfo);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 设置提成发放人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSellCommissionSendEmployee() {
            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 = sellCommissionModule.SetSellCommissionSendEmployee(PeriodId, EmpIds, userInfo);
            if (msg == "")
            {
                return ApiResult.Success("");
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        #endregion


    }
}
