using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Common.Enum.MarketingCenter;
using Mall.Common.Plugin;
using Mall.Model.Entity.MarketingCenter;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Extend.User;
using Mall.Module.MarketingCenter;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.MarketingCenter
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class RechargeController : BaseController
    {
        private RechargeModule rechargeModule = new RechargeModule();


        #region 充值规则设置
        /// <summary>
        /// 充值方案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRechargeRulesPage()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Recharge_Rules_Extend demodel = JsonConvert.DeserializeObject<RB_Recharge_Rules_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = rechargeModule.GetRechargeRulesPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.GiveIntegral,
                x.GiveMoney,
                x.Money,
                x.Name
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetRechargeRules()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Recharge_Rules_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = rechargeModule.GetRechargeRulesList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Recharge_Rules_Extend();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存充值方案
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateRechargeRules()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Recharge_Rules_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入充值方案");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.Name))
                {
                    return ApiResult.Failed("请输入充值名称");
                }
                if (query.Money == 0)
                {
                    return ApiResult.Failed("请输入充值金额");
                }

                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = rechargeModule.AddOrUpdateRechargeRules(query);
                if (result)
                {
                    return ApiResult.Success("充值方案保存成功");
                }
                else
                {
                    return ApiResult.Failed("充值方案保存失败");
                }
            }
        }

        /// <summary>
        /// 删除充值方案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelRules()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = rechargeModule.DelRechargeRules(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion

        #region 充值设置
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRechargeSettingsList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Recharge_Settings>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = rechargeModule.GetRechargeSettingsList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Recharge_Settings();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存充值方案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateRechargeSettings()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Recharge_Settings>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入充值设置");
            }
            else
            {
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = rechargeModule.AddOrUpdateRechargeSettings(query);
                if (result)
                {
                    return ApiResult.Success("充值设置保存成功");
                }
                else
                {
                    return ApiResult.Failed("充值设置保存失败");
                }
            }
        }
        #endregion


        #region 余额收支

        /// <summary>
        /// 余额收支列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberBalancePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Member_Balance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Balance_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = rechargeModule.GetMemberBalancePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                CreateDate = x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                x.MemberName,
                Balance = x.Balance ?? 0,
                x.Description,
                x.Remarks,
                RecordTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.Type)
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 余额收支导出
        /// </summary>
        [HttpPost]
        public FileContentResult GetDistributorRemitListToExcel()
        {
            var parms = RequestParm;
            RB_Member_Balance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Balance_Extend>(parms.msg.ToString());
            string ExcelName = "余额收支" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(BalanceExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = rechargeModule.GetMemberBalanceExport(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.PlatformType.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.UserId.ToString()) { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.MemberName ?? "") { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Moblie).ToString()) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Type.GetEnumName()) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Balance ?? 0).ToString()) { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd")) { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Description) { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

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

        }



        /// <summary>
        /// 获取余额收支下载枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetBalanceExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(BalanceExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        #endregion


        #region 余额自定义设置
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRechargeCustomList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Recharge_Custom>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = rechargeModule.GetRechargeCustomList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Recharge_Custom();
                oldLogisticsModel.BalanceName = "余额";
                oldLogisticsModel.RechareName = "充值金额";
                oldLogisticsModel.RechareExplain = "充值说明";
                oldLogisticsModel.BtnFillet = 40;
                oldLogisticsModel.BtnName = "立即充值";
                oldLogisticsModel.BackgroundColor = "#FF4544";
                oldLogisticsModel.TextColor = "#FFFFFF";
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存充值方案
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateRechargeCustom()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Recharge_Custom>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入自定义设置");
            }
            else
            {
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = rechargeModule.AddOrUpdateRechargeCustom(query);
                if (result)
                {
                    return ApiResult.Success("自定义设置保存成功");
                }
                else
                {
                    return ApiResult.Failed("自定义设置保存失败");
                }
            }
        }
        #endregion
    }
}