using System;
using System.Collections.Generic;
using System.Linq;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.Finance;
using Edu.Model.ViewModel.Log;
using Edu.Model.ViewModel.Sell;
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 CustomerCommissionController : BaseController
    {
        /// <summary>
        /// 返佣存折
        /// </summary>
        private readonly CustomerCommissionModule customerCommissionModule = new CustomerCommissionModule();

        /// <summary>
        /// 财务配置
        /// </summary>
        private readonly EducationContractModule educationContractModule = new EducationContractModule();
        /// <summary>
        /// 提现
        /// </summary>
        private readonly Module.Customer.CustomerRemitModule customerRemitModule = new Module.Customer.CustomerRemitModule();

        #region 获取首页返佣
        /// <summary>
        /// 获取首页返佣统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCenterCommissionStatistics()
        {
            var userInfo = base.UserInfo;

            var Robj = customerCommissionModule.GetCenterCommissionStatistics(userInfo);
            return ApiResult.Success("", Robj);
        }
        #endregion

        #region 返佣列表

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

            var list = customerCommissionModule.GetCommissionPeriodsPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = list.Select(x => new
            {
                x.Id,
                x.BatchName,
                x.TotalMoney,
                x.CreateBy,
                CreateByName = UserReidsCache.GetUserLoginInfo(x.CreateBy)?.AccountName ?? "",
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd"),
                x.CommissionType,
                x.TotalCustomer,
                x.TotalEmployee,
                x.TotalInternal,
                x.TotalTrans,
                x.FinanceIds
            });

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

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

            var list = customerCommissionModule.GetCommissionPeriodsList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.BatchName,
                x.CommissionType
            }));
        }

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

            var list = customerCommissionModule.GetCommissionUserList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.SchoolId,
                x.SchoolName,
                x.UserName,
                x.OrderSourceType,
                x.OrderSourceId,
                x.StudentCount,
                x.CommissionMoeny
            }));
        }

        /// <summary>
        /// 返佣统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCommissionStatistics()
        {
            var userInfo = base.UserInfo;
            var pageModel = JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var dmodel = JsonHelper.DeserializeObject<RB_Order_ReturnComission_ViewModel>(RequestParm.Msg.ToString());
            dmodel.GroupId = userInfo.Group_Id;

            var list = customerCommissionModule.GetCommissionStatisticsPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            decimal TotalMoney = customerCommissionModule.GetCommissionStatistics(dmodel);
            pageModel.Count = Convert.ToInt32(count);
            pageModel.PageData = new
            {
                TotalCommission = TotalMoney,
                List = list.Select(x => new
                {
                    x.SchoolId,
                    x.SchoolName,
                    x.UserName,
                    x.OrderSourceType,
                    OrderSourceTypeName = x.OrderSourceType.ToName(),
                    x.OrderSourceId,
                    x.ClassId,
                    x.ClassName,
                    x.ClassNo,
                    x.OrderId,
                    x.Remark,
                    x.Status,
                    x.CommissionMoeny,
                    x.BatchId,
                    x.BatchName,
                    x.StuId,
                    x.StuName,
                    x.CommissionType
                })
            };
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 导出fanyong 统计 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult GetCommissionStatisticsToExcel()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Order_ReturnComission_ViewModel>(RequestParm.Msg.ToString());
            dmodel.GroupId = 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 = 25, 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 }
                }
            };
            slist.Add(header);

            try
            {
                var list = customerCommissionModule.GetCommissionStatisticsPageList(1, 1000000, out long count, dmodel);
                decimal TotalMoney = customerCommissionModule.GetCommissionStatistics(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.OrderSourceType.ToName()){ },
                            new ExcelColumn(value: item.UserName){ },
                            new ExcelColumn(value: item.ClassNo){ },
                            new ExcelColumn(value: item.ClassName){ },
                            new ExcelColumn(value: item.OrderId.ToString()){ },
                            new ExcelColumn(value: item.StuName){ },
                            new ExcelColumn(value: item.CommissionType==1?"返佣":"幸福存折"){ },
                            new ExcelColumn(value: (item.CommissionMoeny).ToString("#0.00")){ },
                            new ExcelColumn(value: item.Status==-1?"不返佣":item.Status==0?"待返佣":item.Status==1?"已返佣":"已提现"){ },
                            new ExcelColumn(value: item.BatchName){ },
                            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: TotalMoney.ToString("#0.00")){ },
                            new ExcelColumn(value: ""){ },
                            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("GetCommissionStatisticsToExcel: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }

        #endregion

        #region 同业返佣

        /// <summary>
        /// 获取同业详情 返佣同级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCustomerCommissionStat()
        {
            var userInfo = base.UserInfo;
            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());
            int OrderSourceType = parms.GetInt("OrderSourceType", 1);//来源
            int OrderSourceId = parms.GetInt("OrderSourceId", 0);//来源对应ID (内部  同行联系人  学生)
            int CategoryId = parms.GetInt("CategoryId", 0);//同行编号
            int CommissionType = parms.GetInt("CommissionType", 0);//类型
            if (OrderSourceType <= 0 || (OrderSourceId <= 0 && CategoryId <= 0) || CommissionType <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var Robj = customerCommissionModule.GetCustomerCommissionStat(OrderSourceType, OrderSourceId, CategoryId, CommissionType, userInfo);
            return ApiResult.Success("", Robj);
        }

        #endregion


        #region 批量生成返佣金额财务单据
        /// <summary>
        /// 批量生成返佣金额财务单据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetBatchFinance()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Order_ReturnComission_ViewModel>(RequestParm.Msg.ToString());
            dmodel.GroupId = userInfo.Group_Id;
            if (dmodel.BatchId <= 0)
            {
                return ApiResult.ParamIsNull("请传递期数id");
            }
            var financeConfig = educationContractModule.GetFinanceConfigList(new RB_Finance_Config_ViewModel { Group_Id = userInfo.Group_Id, Type = Common.Enum.Course.FinanceConfigTypeEnum.SellCommission }).FirstOrDefault();
            if (financeConfig == null)
            {
                financeConfig = new RB_Finance_Config_ViewModel();
            }
            var list = customerCommissionModule.GetCommissionUserList(dmodel);
            if (list == null || !list.Any(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput))
            {
                return ApiResult.Failed("暂无个人直客数据");
            }
            List<object> financeList = new List<object>();
            foreach (var item in list.Where(x => x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput).GroupBy(x => x.SchoolId))//先区分出校区
            {
                foreach (var deptItem in list.Where(x => x.SchoolId == item.Key && x.OrderSourceType == Common.Enum.User.StuCreateTypeEnum.EmployeeInput).GroupBy(x => x.UserDept))//区分出同一个校区不同部门
                {
                    var tempList = list.Where(x => x.SchoolId == item.Key && x.UserDept == deptItem.Key);
                    if (tempList != null && tempList.Any())
                    {
                        List<object> deptList = new List<object>();
                        foreach (var itemDept in tempList)
                        {
                            if (itemDept.CommissionMoeny > 0 && itemDept.UserDept > 0)
                            {
                                var deptObj = new
                                {
                                    ID = 0,
                                    UnitPrice = Math.Round((itemDept.CommissionMoeny / itemDept.StudentCount), 2, MidpointRounding.AwayFromZero),
                                    UnitPriceTo = "",
                                    Number = itemDept.StudentCount,
                                    Rate = 1,
                                    CostTypeId = financeConfig.CostTypeId,//配置信息
                                    CurrencyId = financeConfig.CurrencyId,
                                    Remark = itemDept.UserName + "的提成，学生数：" + itemDept.StudentCount + "，总提成：" + itemDept.CommissionMoeny,
                                    CostTypeName = "",//费用名称
                                    yTotalPrice = itemDept.CommissionMoeny,
                                    yTotalPriceTo = itemDept.CommissionMoeny,
                                    bTotalPrice = itemDept.CommissionMoeny,
                                    bTotalPriceTo = itemDept.CommissionMoeny,
                                    show = true,
                                    currenName = "人民币"
                                };
                                deptList.Add(deptObj);
                            }

                        }
                        var financeModel = new
                        {
                            FrID = 0,
                            OrderID = 0,
                            TemplateId = financeConfig.TempleteId,//配置信息
                            financeConfig.ClientID,//配置信息
                            ClientType = 10,//配置信息
                            RemitterName = "工资或提成（工资或提成）",//配置信息
                            AccountNumber = "虚拟-公账-公账",//配置信息
                            Type = 2,
                            RB_Branch_Id = item.Key,
                            RB_Depart_Id = deptItem.Key,
                            Money = 0,
                            PayMoney = 0,
                            Status = 1,
                            Fee = 0,
                            IsPublic = 1,//配置信息
                            IsUploadPic = 0,
                            OriginalFee = 0,
                            TradeDate = "",
                            PayDate = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            FinanceName = "",//配置信息
                            CreateDate = "",
                            EmName = userInfo.AccountName,
                            CompanyName = userInfo.SchoolName,
                            Description = "自动生成财务单据",
                            IsLeader = 1,
                            InvoiceType = 0,
                            InvoiceMoney = 0,
                            InvoiceRemark = "",
                            detailList = deptList,
                            RB_DepartName = tempList.FirstOrDefault()?.UserDeptName,
                            RB_BranchName = tempList.FirstOrDefault()?.SchoolName,
                            RelevanceFrId = "",
                            CreateBy = userInfo.Id,
                            OrderSource = 17,
                            RB_Group_Id = userInfo.Group_Id,
                            RB_CreateByName = userInfo.AccountName,
                            RB_GroupName = userInfo.GroupName,
                        };

                        financeList.Add(financeModel);

                    }
                }
            }
            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeList), Config.FinanceKey);
            var resultInfo = new
            {
                msg = sign,
            };
            System.Threading.Tasks.Task.Run(() => SetFinance(resultInfo, dmodel.BatchId));
            return ApiResult.Success("财务单据生成中，请稍后刷新查看");
        }

        /// <summary>
        /// 调用erp生成财务单据接口
        /// </summary>
        /// <param name="resultInfo"></param>
        /// <param name="BatchId"></param>
        public void SetFinance(object resultInfo, int BatchId)
        {
            string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("SellFinanceApi"), JsonHelper.Serialize(resultInfo), "");
            JObject parmsJob = JObject.Parse(apiResult);
            string resultCode = parmsJob.GetStringValue("resultCode");
            string message = parmsJob.GetStringValue("message");
            string frid = parmsJob.GetStringValue("data");

            if (resultCode == "1" && !string.IsNullOrWhiteSpace(frid))//新增记录
            {
                bool result = customerCommissionModule.UdateReturnMoneyModule(frid.Trim('"'), BatchId);

            }
        }
        #endregion



        #region 员工申请提现

        public ApiResult SetWithdrawal()
        {

            var userInfo = base.UserInfo;

            JObject parms = JObject.Parse(base.RequestParm.Msg.ToString());

            RB_Customer_Remit_Extend dmodel = JsonHelper.DeserializeObject<RB_Customer_Remit_Extend>(RequestParm.Msg.ToString());
            if (dmodel.BankAccountId == 0)
            {
                return ApiResult.Failed("请选择提现账户");
            }
            dmodel.CustomerId = userInfo.Id;
            dmodel.Type = 1;

            var model = customerCommissionModule.GetWithdrawal(userInfo);

            if (model == null || model.CanCashOutMoney <= 0)
            {
                return ApiResult.Failed("暂无提现金额");
            }

            decimal afterRemit = model.CashOutMoney + model.CanCashOutMoney;
            dmodel.AppliedMoney = model.CanCashOutMoney;
            dmodel.AuditStatus = 1;
            dmodel.GroupId = userInfo.Group_Id;

            dmodel.CreateDate = System.DateTime.Now;
            dmodel.UserType = 1;
            var restlt = customerCommissionModule.SetWithdrawalInfo(dmodel, afterRemit);
            return ApiResult.Success("提现申请成功");
        }
        #endregion
    }
}
