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

namespace Edu.WebApi.Controllers.Finance
{
    /// <summary>
    /// 教育活动接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class ActivityController : BaseController
    {
        /// <summary>
        /// 活动处理类对象
        /// </summary>
        private readonly ActivityModule activityModule = new ActivityModule();

        #region 活动配置
        /// <summary>
        /// 获取活动配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivityConfigInfo() {
            var userInfo = base.UserInfo;

            var model = activityModule.GetActivityConfigModel(new RB_Activity_Config_ViewModel() { Group_Id = userInfo.Group_Id });
            return ApiResult.Success("", new
            {
                model.Id,
                model.Type,
                model.CommissionMoney,
                model.UpdateBy,
                UpdateByName = Cache.User.UserReidsCache.GetUserLoginInfo(model.UpdateBy)?.AccountName ?? "",
                UpdateTime = model.UpdateTime.ToString("yyyy-MM-dd HH:mm")
            });
        }

        /// <summary>
        /// 新增/修改 活动配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetActivityConfig() {
            var userInfo = base.UserInfo;
            RB_Activity_Config_ViewModel demdoel = JsonHelper.DeserializeObject<RB_Activity_Config_ViewModel>(RequestParm.Msg.ToString());
            if (demdoel.CommissionMoney <= 0) {
                return ApiResult.ParamIsNull("请输入提成比例/金额");
            }
            demdoel.Group_Id = userInfo.Group_Id;
            demdoel.Status = 0;
            demdoel.CreateBy = userInfo.Id;
            demdoel.CreateTime = DateTime.Now;
            demdoel.UpdateBy = userInfo.Id;
            demdoel.UpdateTime = DateTime.Now;

            string msg = activityModule.SetActivityConfig(demdoel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 活动提成

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

            var list = activityModule.GetActivityCommissionPeriodsPageList(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.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 GetActivityCommissionPeriodsList()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Activity_Periods_ViewModel>(RequestParm.Msg.ToString());
            dmodel.Group_Id = userInfo.Group_Id;

            var list = activityModule.GetActivityCommissionPeriodsList(dmodel);

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

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

            var list = activityModule.GetActivityCommissionUserList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.School_Id,
                x.SchoolName,
                x.Depart_Id,
                x.DeptName,
                x.UserId,
                x.UserName,
                x.CommissionMoney
            }));
        }

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

            var list = activityModule.GetActivityCommissionUserDetailList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.School_Id,
                x.SchoolName,
                x.Depart_Id,
                x.DeptName,
                x.UserId,
                x.UserName,
                x.ActivityId,
                x.ActivityName,
                ActivityTime = x.ActivityTime.ToString("yyyy-MM-dd"),
                x.OrderId,
                x.Periods,
                x.CommissionMoney,
                x.Remark,
                x.DSUserId,
                x.DSUserName,
            }));
        }

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

            var list = activityModule.GetActivityCommissionUserDetailList(dmodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.School_Id,
                x.SchoolName,
                x.Depart_Id,
                x.DeptName,
                x.UserId,
                x.UserName,
                x.ActivityId,
                x.ActivityName,
                ActivityTime = x.ActivityTime.ToString("yyyy-MM-dd"),
                x.OrderId,
                x.Periods,
                x.CommissionMoney,
                x.Remark,
                x.DSUserId,
                x.DSUserName,
            }));
        }

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

            var list = activityModule.GetActivityCommissionStatisticsPageList(pageModel.PageIndex, pageModel.PageSize, out long count, dmodel);
            decimal TotalMoney = activityModule.GetActivityCommissionStatistics(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.ActivityId,
                    x.ActivityName,
                    ActivityTime = x.ActivityTime.ToString("yyyy-MM-dd"),
                    x.OrderId,
                    x.Periods,
                    x.CommissionMoney,
                    x.Remark,
                    x.DSUserId,
                    x.DSUserName,
                })
            };
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 导出提成统计 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public FileContentResult GetActivityCommissionStatisticsToExcel()
        {
            var userInfo = base.UserInfo;
            var dmodel = JsonHelper.DeserializeObject<RB_Activity_PeriodsDetail_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 }
                }
            };
            slist.Add(header);

            try
            {
                var list = activityModule.GetActivityCommissionStatisticsPageList(1, 1000000, out long count, dmodel);
                decimal TotalMoney = activityModule.GetActivityCommissionStatistics(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.OrderId.ToString()){ },
                            new ExcelColumn(value: item.ActivityName){ },
                            new ExcelColumn(value: item.ActivityTime.ToString("yyyy-MM-dd")){ },
                            new ExcelColumn(value: item.DSUserName){ },
                            new ExcelColumn(value: (item.CommissionMoney).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: 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 GetActivityCommissionSendEmployeeList()
        {
            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 = activityModule.GetActivityCommissionSendEmployeeList(PeriodId, userInfo);
            return ApiResult.Success("", list);
        }

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

        #endregion
    }
}
