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.User;
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;
using Newtonsoft.Json.Linq;

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



        #region 卡券

        [HttpPost]
        public ApiResult GetCouponPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Coupon_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetCouponPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Name,
                x.HeXiao,
                x.CouponIco,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IndateType,
                x.IndateDay,
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            }); ;
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCouponDetail()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = IntegralModule.GetCouponList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Coupon_Extend();
                oldLogisticsModel.IndateType = Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon;
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存物流信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Coupon_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 (string.IsNullOrWhiteSpace(query.CouponIco))
                {
                    return ApiResult.Failed("请输入卡券图标");
                }
                if (query.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                {
                    if (query.IndateDay == 0)
                    {
                        return ApiResult.Failed("请输入有效期天数");
                    }
                }
                else
                {
                    if (!query.StartDate.HasValue || !query.EndDate.HasValue)
                    {
                        return ApiResult.Failed("开始日期或结束日期必填");
                    }
                    if (query.StartDate > query.EndDate)
                    {
                        return ApiResult.Failed("开始日期必须小于结束日期");
                    }
                }
                if (query.HeXiao == 0)
                {
                    return ApiResult.Failed("请输入核销总次数");
                }

                if (query.TotalNum == 0)
                {
                    return ApiResult.Failed("请输入可发放数量");
                }

                if (string.IsNullOrWhiteSpace(query.Describe))
                {
                    return ApiResult.Failed("请输入卡券描述");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = IntegralModule.AddOrUpdateCoupon(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 = IntegralModule.DelCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion

        #region 优惠券

        [HttpPost]
        public ApiResult GetDiscountCouponPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_DiscountCoupon_Extend demodel = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetDiscountCouponPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Name,
                x.MinConsumePrice,
                x.MaxDiscountsPrice,
                x.DiscountsPrice,
                UseTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.UseType),
                x.CouponType,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IndateType,
                x.IndateDay,
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.TotalNum,
                ResidueNum = x.ReceiveNum,
                x.PickupCenter
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDiscountCouponDetail()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = IntegralModule.GetDiscountCouponList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_DiscountCoupon_Extend();
                oldLogisticsModel.IndateType = Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon;
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.MemberLevel))
            {
                oldLogisticsModel.MemberLevelList = JsonConvert.DeserializeObject<List<int>>(oldLogisticsModel.MemberLevel).ToArray();
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateDiscountCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_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.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                {
                    if (query.IndateDay == 0)
                    {
                        return ApiResult.Failed("请输入有效期天数");
                    }
                }
                else
                {
                    if (!query.StartDate.HasValue || !query.EndDate.HasValue)
                    {
                        return ApiResult.Failed("开始日期或结束日期必填");
                    }
                    if (query.StartDate > query.EndDate)
                    {
                        return ApiResult.Failed("开始日期必须小于结束日期");
                    }
                }

                if (query.CouponType == CouponTypeEnum.Discount)
                {
                    if (query.DiscountsPrice > 10)
                    {
                        return ApiResult.Failed("折扣率的值必须不大于10");
                    }
                }


                if (query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category || query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)
                {
                    if (query.ProductList == null || !query.ProductList.Any())
                    {
                        return ApiResult.Failed(query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category ? "请选择商品类别" : "请选择商品");
                    }
                }
                if (query.TotalNum == 0)
                {
                    return ApiResult.Failed("请输入可发放数量");
                }

                if (string.IsNullOrWhiteSpace(query.Describe))
                {
                    return ApiResult.Failed("请输入卡券描述");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                if (query.MemberLevelList != null && query.MemberLevelList.Length > 0)
                {
                    query.MemberLevel = JsonConvert.SerializeObject(query.MemberLevelList);
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = IntegralModule.AddOrUpdateDiscountCoupon(query);
                if (result)
                {
                    return ApiResult.Success("优惠券信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("优惠券信息保存失败");
                }
            }
        }

        /// <summary>
        /// 删除优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = IntegralModule.DelDiscountCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 加入领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdatePickupType()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = IntegralModule.UpdatePickupType(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success("操作成功");
            }
            else
            {
                return ApiResult.Failed("操作失败");
            }
        }


        /// <summary>
        /// 发放优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入卡券信息");
            }
            else
            {
                var oldLogisticsModel = IntegralModule.GetDiscountCouponList(query).FirstOrDefault();
                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("优惠券信息不存在，请核实后再操作");
                }
                if (string.IsNullOrWhiteSpace(query.UserIds))
                {
                    return ApiResult.Failed("请选择发放对象");
                }
                List<RB_Member_DiscountCoupon_Extend> list = new List<RB_Member_DiscountCoupon_Extend>();
                for (int i = 0; i < query.GrantNum; i++)
                {
                    foreach (var item in query.UserIds.Split(","))
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            RB_Member_DiscountCoupon_Extend memberCoupon = new RB_Member_DiscountCoupon_Extend();
                            memberCoupon.Id = 0;
                            memberCoupon.UserId = Convert.ToInt32(item);
                            memberCoupon.Description = oldLogisticsModel.Describe;
                            memberCoupon.CreateDate = System.DateTime.Now;
                            memberCoupon.TenantId = oldLogisticsModel.TenantId;
                            memberCoupon.MallBaseId = oldLogisticsModel.MallBaseId;
                            memberCoupon.Remarks = "";
                            memberCoupon.CouponId = oldLogisticsModel.ID;
                            if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                            {
                                memberCoupon.StartDate = System.DateTime.Now;
                                memberCoupon.EndDate = memberCoupon.StartDate.Value.AddDays(oldLogisticsModel.IndateDay);
                            }
                            else
                            {
                                memberCoupon.StartDate = oldLogisticsModel.StartDate;
                                memberCoupon.EndDate = oldLogisticsModel.EndDate;
                            }
                            list.Add(memberCoupon);
                        }
                    }
                }
                if (oldLogisticsModel.TotalNum != -1)
                {
                    //if ((oldLogisticsModel.TotalNum - oldLogisticsModel.ReceiveNum) < list.Count())
                    //{
                    //    return ApiResult.Failed("优惠券剩余" + (oldLogisticsModel.TotalNum - oldLogisticsModel.ReceiveNum) + "张");
                    //}
                    if (oldLogisticsModel.TotalNum < list.Count())
                    {
                        return ApiResult.Failed("优惠券剩余" + oldLogisticsModel.TotalNum + "张");
                    }
                }
                bool result = IntegralModule.GrantCoupon(list, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("优惠券信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("优惠券信息保存失败");
                }
            }
        }




        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllDiscountCouponList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = IntegralModule.GetAllDiscountCouponList(query);
            return ApiResult.Success("", oldLogisticsModel);
        }




        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCouponPageListByMemberId()
        {
            var req = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_DiscountCoupon_Extend demodel = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(req.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            var list = IntegralModule.GetMemberDisCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.MinConsumePrice,
                x.MaxDiscountsPrice,
                x.DiscountsPrice,
                x.CouponType,
                x.ID,
                x.MemberCouponId,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                UseTypeStr = ((int)x.UseType == 3 || (int)x.UseType == 4) ? x.UseType.GetEnumName() : (x.ProductList != null && x.ProductList.Any() ? string.Join("、", x.ProductList.Select(x => x.Relevance)) : ""),
                x.UseType,
                x.ProductList,
                x.PickupCenter,
                x.UseState,
                x.GetType
            });
            return ApiResult.Success("", pagelist);
        }





        /// <summary>
        /// 删除用户优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMemberCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("MemberCouponId", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = IntegralModule.DelMemberCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion


        #region 自动发放优惠券
        /// <summary>
        /// 自动发放优惠券列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSelfMotionPageLis()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Coupon_SelfMotion_Extend demodel = JsonConvert.DeserializeObject<RB_Coupon_SelfMotion_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetSelfMotionPageLis(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.GrantNum,
                x.DiscountCouponName,
                TriggerTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.TriggerType)

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


        /// <summary>
        /// 获取自动发放优惠券详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GettRepositoryList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Coupon_SelfMotion_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = IntegralModule.GettRepositoryList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Coupon_SelfMotion_Extend();
            }
            else
            {
                if (oldLogisticsModel.IsAll == 1)
                {
                    oldLogisticsModel.UserList = new List<RB_Coupon_SelfMotionMember_Extend>();
                    oldLogisticsModel.UserList = IntegralModule.GetSelfMotionMemberList(new RB_Coupon_SelfMotionMember_Extend { TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId, SelfMotionId = oldLogisticsModel.ID });
                }

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


        /// <summary>
        /// 保存自动发放优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateSelfMotion()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Coupon_SelfMotion_Extend>(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;
                }
                if (query.IsAll == 1 && (query.UserList == null || !query.UserList.Any()))
                {
                    return ApiResult.Failed("请选择领取人信息");
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = IntegralModule.AddOrUpdateSelfMotion(query);
                if (result)
                {
                    return ApiResult.Success("自动发放优惠券保存成功");
                }
                else
                {
                    return ApiResult.Failed("自动发放优惠券保存失败");
                }
            }
        }

        /// <summary>
        /// 删除自动发放优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountSelfMotion()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = IntegralModule.DelDiscountSelfMotion(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取触发事件枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTriggerTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(TriggerTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #endregion

        #region  发放统计
        /// <summary>
        /// 积分收支
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCouponStatisticslList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            MemberCoupon_Query demodel = JsonConvert.DeserializeObject<MemberCoupon_Query>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetCouponStatisticslList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.CreateDate,
                x.IsSued,
                x.UnUsed,
                x.Used,
                x.Voksi,
                x.Name
            });
            return ApiResult.Success("", pagelist);
        }
        /// <summary>
        /// 积分收支统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTotalCoupon()
        {
            var parms = RequestParm;
            RB_Member_DiscountCoupon_Extend demodel = JsonConvert.DeserializeObject<RB_Member_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetTotalIntegral(demodel);
            MemberCoupon_Query model = new MemberCoupon_Query();
            if (list != null && list.Any())
            {
                model.IsSued = list.Count().ToString();
                model.UnUsed = list.Where(x => x.UseState == 0).Count().ToString();
                model.Used = list.Where(x => x.UseState == 1).Count().ToString();
                model.Voksi = list.Where(x => x.UseState == 0 && x.EndDate < System.DateTime.Now).Count().ToString();
            }
            return ApiResult.Success("", new { model.IsSued, model.UnUsed, model.Used, model.Voksi });
        }


        /// <summary>
        /// 积分收支信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetCouponListToExcel()
        {
            var parms = RequestParm;
            MemberCoupon_Query demodel = JsonConvert.DeserializeObject<MemberCoupon_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 },
                       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.GetExportCouponStatisticslList(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.Name) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.IsSued) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Used) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UnUsed) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Voksi) { });
                    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

        #region 使用记录

        /// <summary>
        /// 使用记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUseCouponList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Member_DiscountCoupon_Extend demodel = JsonConvert.DeserializeObject<RB_Member_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = IntegralModule.GetUseCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Photo,
                x.OrderCreateDate,
                x.OrderId,
                x.Name,
                x.AliasName,
                x.MinConsumePrice,
                CouponTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.CouponType),
                x.CouponType,
                x.DiscountsPrice,
                x.UseState
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion
    }
}