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.MarketingCenter;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Module.MarketingCenter;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Mall.WebApi.Controllers.MarketingCenter
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class IntegralController : BaseController
    {
        private IntegralModule IntegralModule = new IntegralModule();

        #region 积分设置
        /// <summary>
        /// 获取积分设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetIntegralSettingsList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Integral_Settings>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = IntegralModule.GetIntegralSettingsList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Integral_Settings();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存积分设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateIntegralSettings()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Integral_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 = IntegralModule.AddOrUpdateIntegralSettings(query);
                if (result)
                {
                    return ApiResult.Success("积分设置保存成功");
                }
                else
                {
                    return ApiResult.Failed("积分设置保存失败");
                }
            }
        }
        #endregion


        #region 积分记录

        /// <summary>
        /// 充值方案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRechargeRulesPage()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Member_Integral_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Integral_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetRechargeRecordPageList(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,
                x.Integral,
                x.Description,
                x.Remarks,
                RecordTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.Type)
            });
            return ApiResult.Success("", pagelist);
        }

        [HttpPost]
        public FileContentResult GetDistributorRemitListToExcel()
        {
            var parms = RequestParm;
            RB_Member_Integral_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Integral_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(IntegralExportEnum));
            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 = IntegralModule.GetIntegralRecordExport(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() + (item.Integral ?? 0).ToString()) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd")) { }); break;
                            case 7:
                                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 GetIntegralExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(IntegralExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        #endregion


        #region 数据统计- 积分收支
        /// <summary>
        /// 积分收支
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetIntegraStatisticslList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            Integral_Query demodel = JsonConvert.DeserializeObject<Integral_Query>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetIntegraStatisticslList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.CreateDate,
                x.Income,
                x.Expend
            });
            return ApiResult.Success("", pagelist);
        }
        /// <summary>
        /// 积分收支统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTotalIntegral()
        {
            var parms = RequestParm;
            RB_Member_Integral_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Integral_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetTotalIntegral(demodel);
            Integral_Query model = new Integral_Query();
            if (list != null && list.Any())
            {
                model.Income = list.Where(x => x.Type == Common.Enum.MarketingCenter.RecordTypeEnum.Income).Sum(x => x.Integral ?? 0).ToString();
                model.Expend = list.Where(x => x.Type == Common.Enum.MarketingCenter.RecordTypeEnum.Expend).Sum(x => x.Integral ?? 0).ToString();
            }
            return ApiResult.Success("", new { model.Income, model.Expend });
        }


        /// <summary>
        /// 积分收支信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetIntegralListToExcel()
        {
            var parms = RequestParm;
            Integral_Query demodel = JsonConvert.DeserializeObject<Integral_Query>(parms.msg.ToString());
            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 = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                       new ExcelColumn(value: "积分支出") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = IntegralModule.GetExportIntegraStatisticslList(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()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Income) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Expend) { });
                    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);
            }

        }
        #endregion
    }
}