using System;
using System.Collections.Generic;
using System.Linq;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.MarketingCenter;
using Mall.Module.Product;
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 AppletCouponController : BaseController
    {
        private CouponModule couponModule = new CouponModule();
        private ProductModule productModule = new ProductModule();

        /// <summary>
        /// 获取用户未使用的优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoUseCouponList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            //if (userInfo == null)
            //{
            //    userInfo.TenantId = 1;
            //    userInfo.MallBaseId = 1;
            //    userInfo.UserId = 3;
            //}
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            var list = couponModule.GetNoUseCouponList(query);

            //获取优惠券对应的商品，或者分类
            List<RB_Product_Category_Extend> categotyList = new List<RB_Product_Category_Extend>();

            List<RB_DiscountCoupon_Product_Extend> productList = new List<RB_DiscountCoupon_Product_Extend>();

            string Ids = "";
            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
            {
                productList.AddRange(item.ProductList);
                item.CategoryIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                categotyList = productModule.GetCategoryListModule(new Model.Extend.Product.RB_Product_Category_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CategoryIds = Ids });
            }

            if (categotyList == null || !categotyList.Any())
            {
                categotyList = new List<RB_Product_Category_Extend>();
            }



            List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();

            productList = new List<RB_DiscountCoupon_Product_Extend>();

            Ids = "";

            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
            {
                productList.AddRange(item.ProductList);
                item.GoodsIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }

            if (!string.IsNullOrWhiteSpace(Ids))
            {
                goodsList = productModule.GetProductGoodsList(new RB_Goods_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, GoodsIds = Ids });
            }
            if (goodsList == null || !goodsList.Any())
            {
                goodsList = new List<RB_Goods_Extend>();
            }

            int isBestId = 0;
            decimal maxDiscountsPrice = 0;
            foreach (var item in list)
            {
                if (item.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount)
                {
                    if (item.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category)//
                    {

                        foreach (var itemProduct in query.ProductList)
                        {
                            List<int> allGoodsClass = new List<int>();
                            allGoodsClass.AddRange(itemProduct.GoodsClassId.ToList());
                            //分类
                            var goodsClassList = allGoodsClass.GroupBy(x => x);
                            if (item.ProductList != null && item.ProductList.Any())
                            {
                                foreach (var resultItem in item.ProductList)
                                {
                                    if (goodsClassList.Any(x => x.Key == resultItem.ProductId))
                                    {
                                        decimal tempPrice = Math.Round(itemProduct.GoodsPrice * (10 - item.DiscountsPrice) / 10, 2, MidpointRounding.AwayFromZero);
                                        if (item.MaxDiscountsPrice > 0 && item.MaxDiscountsPrice < tempPrice)
                                        {
                                            if (maxDiscountsPrice < item.MaxDiscountsPrice)
                                            {
                                                maxDiscountsPrice = item.DiscountsPrice;
                                                isBestId = item.MemberCouponId;
                                            }
                                        }
                                        else
                                        {
                                            if (maxDiscountsPrice < tempPrice)
                                            {
                                                maxDiscountsPrice = tempPrice;
                                                isBestId = item.MemberCouponId;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (item.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)
                    {
                        foreach (var itemProduct in query.ProductList)
                        {
                            List<int> goodsClassList = new List<int>();
                            goodsClassList.Add(itemProduct.ProductId);
                            if (item.ProductList != null && item.ProductList.Any())
                            {
                                foreach (var resultItem in item.ProductList)
                                {
                                    if (goodsClassList.Any(x => x == resultItem.ProductId))
                                    {
                                        decimal tempPrice = Math.Round(itemProduct.GoodsPrice * (10 - item.DiscountsPrice) / 10, 2, MidpointRounding.AwayFromZero);
                                        if (item.MaxDiscountsPrice > 0 && item.MaxDiscountsPrice < tempPrice)
                                        {
                                            if (maxDiscountsPrice < item.MaxDiscountsPrice)
                                            {
                                                maxDiscountsPrice = item.DiscountsPrice;
                                                isBestId = item.MemberCouponId;
                                            }
                                        }
                                        else
                                        {
                                            if (maxDiscountsPrice < tempPrice)
                                            {
                                                maxDiscountsPrice = tempPrice;
                                                isBestId = item.MemberCouponId;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (item.UseType == Common.Enum.MarketingCenter.UseTypeEnum.All)
                    {
                        foreach (var itemProduct in query.ProductList)
                        {
                            if (itemProduct.GoodsPrice >= item.MinConsumePrice)
                            {
                                decimal tempPrice = Math.Round(itemProduct.GoodsPrice * (10 - item.DiscountsPrice) / 10, 2, MidpointRounding.AwayFromZero);
                                if (item.MaxDiscountsPrice > 0 && item.MaxDiscountsPrice < tempPrice)
                                {
                                    if (maxDiscountsPrice < item.MaxDiscountsPrice)
                                    {
                                        maxDiscountsPrice = item.DiscountsPrice;
                                        isBestId = item.MemberCouponId;
                                    }
                                }
                                else
                                {
                                    if (maxDiscountsPrice < tempPrice)
                                    {
                                        maxDiscountsPrice = tempPrice;
                                        isBestId = item.MemberCouponId;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (maxDiscountsPrice < item.DiscountsPrice)
                    {
                        maxDiscountsPrice = item.DiscountsPrice;
                        isBestId = item.MemberCouponId;
                    }
                }
            }


            var result = list.Select(x => new
            {
                isBest = x.MemberCouponId == isBestId ? 1 : 0,
                id = x.MemberCouponId,
                mall_id = userInfo.MallBaseId,
                user_id = userInfo.UserId,
                coupon_id = x.ID,
                sub_price = x.DiscountsPrice,
                discount = x.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount ? x.DiscountsPrice : 10,
                coupon_min_price = x.MinConsumePrice,
                type = (int)x.CouponType,
                start_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                is_use = 0,
                is_delete = 0,
                created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                deleted_at = "0000-00-00 00:00:00",
                receive_type = "",
                discount_limit = x.MaxDiscountsPrice,
                coupon_data = new
                {
                    id = x.ID,
                    mall_id = userInfo.MallBaseId,
                    name = x.Name,
                    type = (int)x.CouponType,
                    discount = x.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount ? x.DiscountsPrice : 10,
                    pic_url = "",
                    desc = "",
                    min_price = x.MinConsumePrice,
                    sub_price = x.DiscountsPrice,
                    total_count = x.TotalNum + x.ReceiveNum,
                    sort = x.Sort,
                    expire_type = x.IndateType,
                    expire_day = x.IndateDay,
                    begin_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    appoint_type = (int)x.UseType,
                    rule = x.Describe,
                    is_member = x.OnlyMember,
                    is_delete = 0,
                    deleted_at = "0000-00-00 00:00:00",
                    created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    discount_limit = x.MaxDiscountsPrice,
                    car = categotyList.Where(y => x.CategoryIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        mch_id = 0,
                        parent_id = y.ParentId,
                        name = y.Name,
                        pic_url = y.AdvertisingImagePath,
                        sort = y.Sort,
                        big_pic_url = y.BigIconPath,
                        advert_pic = y.AdvertisingImage,
                        advert_url = y.AdvertisingImagePath,
                        status = y.Status,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                        is_show = y.IsShow,
                        advert_open_type = "",
                        advert_params = ""
                    }),
                    goods = goodsList.Where(y => x.GoodsIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        name = y.Name,
                        original_price = y.OriginalPrice,
                        cost_price = y.CostPrice,
                        detail = y.GoodsDetails,
                        cover_pic = y.CoverImage,
                        pic_url = "",
                        video_url = y.VideoAddress,
                        unit = y.Unit,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                    }),
                },
                x.Name,
                x.Describe,
                x.MinConsumePrice,
                x.CouponType,
                x.MaxDiscountsPrice,
                x.UseType
            });
            return ApiResult.Success("", result);

        }


        #region 储值卡

        /// <summary>
        ///  储值卡购买中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDepositPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Deposit_Extend demodel = JsonConvert.DeserializeObject<RB_Deposit_Extend>(req.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.PickupCenter = 1;
            var list = couponModule.GetDepositPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.ID,
                x.CouponIco,
                x.DepositPrice,
                x.IndateDay,
                x.SalePrice
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        ///  个人储值卡中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDepositBuyPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Member_DepositBuy_Extend demodel = JsonConvert.DeserializeObject<RB_Member_DepositBuy_Extend>(req.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Status = 1;
            demodel.SendStatus = -1;
            var list = couponModule.GetDepositBuyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.SendStatus,
                x.DepositId,
                x.DepositPrice,
                x.SurplusPrice,
                EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd") : "",
                SendTime = x.SendTime.HasValue ? x.SendTime.Value.ToString("yyyy-MM-dd") : "",
                x.Id,
                x.IndateDay,
                x.OrderNo,
                x.RechargeType,
                x.SalePrice,
                x.UserId,
                x.CouponIco
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        ///  个人储值卡流水
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDepositBalancePageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Member_DepositBalance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_DepositBalance_Extend>(req.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Status = 0;
            var list = couponModule.GetDepositBalancePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.DepositPrice,
                x.Balance,
                x.CouponIco,
                x.Type,
                x.MergeType,
                x.Surplus,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Id,
                x.SalePrice,
                x.UserId,
                x.Remarks
            });
            return ApiResult.Success("", pagelist);
        }





        /// <summary>
        /// 储值卡合并
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMergeDeposit()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string Ids = parmsJob.GetStringValue("Ids");

            var depositList = couponModule.GetDepositBuyList(new Model.Extend.User.RB_Member_DepositBuy_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, Ids = Ids, UserId = userInfo.UserId, SendStatus = -1, Status = -1 });

            foreach (var item in depositList)
            {
                if (item.Status == 0)
                {
                    return ApiResult.Failed(item.Name + "储值卡未支付，不能合并");
                }
                if (item.SendStatus != 0)
                {
                    return ApiResult.Failed(item.Name + "储值卡已赠送/分享中，不能合并");
                }
                if (item.SurplusPrice <= 0)
                {
                    return ApiResult.Failed(item.Name + "储值卡剩余余额为0，不能合并");
                }
                if (item.EndTime.HasValue && item.EndTime.Value < System.DateTime.Now)
                {
                    return ApiResult.Failed(item.Name + "储值卡已过期");
                }
            }
            if (depositList.Count <= 1)
            {
                return ApiResult.Failed("单张储值卡不能合并");
            }
            var firstModel = depositList.OrderByDescending(x => x.EndTime).FirstOrDefault();
            List<Model.Entity.User.RB_Member_DepositBalance> depositMergeList = new List<Model.Entity.User.RB_Member_DepositBalance>();
            List<RB_Member_DepositBuy_Extend> depositBuyList = new List<RB_Member_DepositBuy_Extend>();
            Model.Entity.User.RB_Member_DepositBalance mergeIncomeModel = new Model.Entity.User.RB_Member_DepositBalance()
            {
                Id = 0,
                OldDepositBuyId = firstModel.Id,
                NewDepositBuyId = 0,
                UserId = firstModel.UserId,
                Name = firstModel.Name,
                CouponIco = firstModel.CouponIco,
                SalePrice = firstModel.SalePrice,
                DepositPrice = firstModel.DepositPrice,
                MergeType = 1,
                CreateDate = System.DateTime.Now,
                Status = 0,
                TenantId = userInfo.TenantId,
                MallBaseId = userInfo.MallBaseId,
                Balance = firstModel.SurplusPrice,
                Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                Remarks = "储值卡合并"
            };
            foreach (var item in depositList.Where(x => x.Id != firstModel.Id))
            {
                firstModel.SurplusPrice += item.SurplusPrice;

                Model.Entity.User.RB_Member_DepositBalance mergeModel = new Model.Entity.User.RB_Member_DepositBalance()
                {
                    Id = 0,
                    OldDepositBuyId = item.Id,
                    NewDepositBuyId = firstModel.Id,
                    UserId = item.UserId,
                    Name = item.Name,
                    CouponIco = item.CouponIco,
                    SalePrice = item.SalePrice,
                    DepositPrice = item.DepositPrice,
                    MergeType = 1,
                    CreateDate = System.DateTime.Now,
                    Status = 0,
                    TenantId = userInfo.TenantId,
                    MallBaseId = userInfo.MallBaseId,
                    Balance = item.SurplusPrice,
                    Surplus = 0,
                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                    Remarks = "储值卡合并，合并后的储值卡id：" + firstModel.Id
                };
                item.SurplusPrice = 0;
                item.Remarks = "储值卡合并，合并后的储值卡id：" + firstModel.Id;
                depositMergeList.Add(mergeModel);
                depositBuyList.Add(item);
            }
            depositBuyList.Add(firstModel);
            mergeIncomeModel.Surplus = firstModel.SurplusPrice;
            depositMergeList.Add(mergeIncomeModel);
            bool result = couponModule.MergeDeposit(depositBuyList, depositMergeList);
            if (result)
            {
                return ApiResult.Success("储值卡合并成功");
            }
            else
            {
                return ApiResult.Failed("储值卡合并失败");
            }
        }



        /// <summary>
        /// 判断储值卡是否可以分享
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGiveDeposit()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            //判断当前的储值卡是否可以被分享
            var depositModel = couponModule.GetDepositBuyList(new Model.Extend.User.RB_Member_DepositBuy_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, Id = Id, UserId = userInfo.UserId, SendStatus = -1, Status = 1 }).FirstOrDefault();
            if (depositModel == null || depositModel.Id == 0)
            {
                return ApiResult.Failed("储值卡不存在");
            }
            else if (depositModel.SendStatus == 1)
            {
                return ApiResult.Failed("储值卡已赠送他人");
            }
            else
            {
                //if (depositModel.DepositPrice != depositModel.SurplusPrice)
                //{
                //    return ApiResult.Failed("已使用的储值卡不能赠送");
                //}
                var depositBalanceList = couponModule.GetDepositBalanceList(new RB_Member_DepositBalance_Extend { MallBaseId = userInfo.MallBaseId, OldDepositBuyId = depositModel.Id, TenantId = userInfo.TenantId, UserId = userInfo.UserId, Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend, MergeType = 3 });

                if (depositBalanceList != null && depositBalanceList.Any())
                {
                    return ApiResult.Failed("已使用的储值卡不能赠送");
                }
                //更新储值卡的状态
                if (depositModel.SendStatus == 0)
                {
                    bool result = couponModule.UpdateSendStatus(depositModel);
                    if (result)
                    {
                        return ApiResult.Success("");
                    }
                    else
                    {
                        return ApiResult.Failed("储值卡暂不支持分享，请稍后再试");
                    }
                }
                else
                {
                    return ApiResult.Success("");
                }
            }
        }


        /// <summary>
        /// 领取储值卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetReceiveDeposit()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            var depositModel = couponModule.GetDepositBuyList(new Model.Extend.User.RB_Member_DepositBuy_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, Id = Id, SendStatus = -1, Status = 1 }).FirstOrDefault();
            if (depositModel == null || depositModel.Id == 0)
            {
                return ApiResult.Failed("储值卡不存在");
            }
            else if (depositModel.SendStatus == 1)
            {
                return ApiResult.Failed("慢人一步，储值卡已被别人领取");
            }
            if (depositModel.UserId == userInfo.UserId)
            {
                return ApiResult.Failed("自己不能领取自己的储值卡");
            }
            if (depositModel.SendStatus == 2)
            {
                if (depositModel.SendTime.HasValue && depositModel.SendTime > System.DateTime.Now)
                {
                    List<Model.Entity.User.RB_Member_DepositBalance> depositMergeList = new List<Model.Entity.User.RB_Member_DepositBalance>();

                    var newDepositModel = new RB_Member_DepositBuy_Extend()
                    {
                        Status = depositModel.Status,
                        TenantId = depositModel.TenantId,
                        MallBaseId = depositModel.MallBaseId,
                        OrderNo = depositModel.OrderNo,
                        Name = depositModel.Name,
                        CouponIco = depositModel.CouponIco,
                        SalePrice = depositModel.SalePrice,
                        DepositPrice = depositModel.DepositPrice,
                        SurplusPrice = depositModel.SurplusPrice,
                        IndateDay = depositModel.IndateDay,
                        OrderSource = depositModel.OrderSource,
                        DepositId = depositModel.DepositId,
                        PayWay = depositModel.PayWay,
                        Remarks = "领取储值卡",
                        PayTime = depositModel.PayTime,
                        Out_Trade_No = depositModel.Out_Trade_No,
                        Transaction_Id = depositModel.Transaction_Id
                    };
                    newDepositModel.Id = 0;
                    newDepositModel.CreateDate = System.DateTime.Now;
                    newDepositModel.EndTime = newDepositModel.CreateDate.Value.AddDays(newDepositModel.IndateDay);
                    newDepositModel.UserId = userInfo.UserId;
                    newDepositModel.RechargeType = 2;
                    newDepositModel.SendStatus = 0;
                    newDepositModel.SendTime = null;

                    var oldUserInfo = CacheManager.User.UserReidsCache.GetAppletUserLoginInfo(depositModel.UserId);
                    Model.Entity.User.RB_Member_DepositBalance mergeModel = new Model.Entity.User.RB_Member_DepositBalance()
                    {
                        Id = 0,
                        OldDepositBuyId = depositModel.Id,
                        NewDepositBuyId = 0,
                        UserId = userInfo.UserId,
                        Name = depositModel.Name,
                        CouponIco = depositModel.CouponIco,
                        SalePrice = depositModel.SalePrice,
                        DepositPrice = depositModel.DepositPrice,
                        MergeType = 2,
                        CreateDate = System.DateTime.Now,
                        Status = 0,
                        Balance = 0,
                        Surplus = depositModel.DepositPrice,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        TenantId = userInfo.TenantId,
                        MallBaseId = userInfo.MallBaseId,
                        Remarks = "用户:" + oldUserInfo?.Name + "将储值卡赠送给您",
                    };
                    depositMergeList.Add(mergeModel);
                    Model.Entity.User.RB_Member_DepositBalance oldDergeModel = new Model.Entity.User.RB_Member_DepositBalance()
                    {
                        Id = 0,
                        OldDepositBuyId = depositModel.Id,
                        NewDepositBuyId = 0,
                        UserId = depositModel.UserId,
                        Name = depositModel.Name,
                        CouponIco = depositModel.CouponIco,
                        SalePrice = depositModel.SalePrice,
                        DepositPrice = depositModel.DepositPrice,
                        MergeType = 2,
                        CreateDate = System.DateTime.Now,
                        Status = 0,
                        Balance = depositModel.DepositPrice,
                        Surplus = 0,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                        TenantId = userInfo.TenantId,
                        MallBaseId = userInfo.MallBaseId,
                        Remarks = "储值卡赠送给了" + userInfo.Name 
                    };
                    depositMergeList.Add(oldDergeModel);
                    bool flag = couponModule.ReceiveDeposit(depositModel, newDepositModel, depositMergeList);
                    if (flag)
                    {
                        return ApiResult.Success("储值卡领取成功");
                    }
                    else
                    {
                        return ApiResult.Failed("储值卡领取失败");
                    }
                }
                else
                {
                    return ApiResult.Failed("储值卡领取时间已过，请赠送人再次分享");
                }
            }

            return ApiResult.Success("储值卡领取失败");
        }


        /// <summary>
        /// 获取用户购买的储值卡（剩余金额>0）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoUseDeposit()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var depositList = couponModule.GetDepositBuyList(new Model.Extend.User.RB_Member_DepositBuy_Extend { TenantId = userInfo.TenantId, UserId = userInfo.UserId, IsOver = 1, MallBaseId = userInfo.MallBaseId, SendStatus = 0, Status = 1 });
            var result = depositList.Where(x => x.SurplusPrice > 0).Select(x => new { x.Id, x.SurplusPrice, x.Name, x.CouponIco, EndTime = x.EndTime.HasValue ? x.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", });
            return ApiResult.Success("", result);
        }


        /// <summary>
        /// 获取用户购买的储值卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllUseDeposit()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var depositList = couponModule.GetDepositBuyList(new Model.Extend.User.RB_Member_DepositBuy_Extend { TenantId = userInfo.TenantId, UserId = userInfo.UserId, MallBaseId = userInfo.MallBaseId, SendStatus = -1, Status = 1 });
            var result = new
            {
                DepositNum = (depositList != null && depositList.Any()) ? depositList.Count() : 0,
                DepositPrice = (depositList != null && depositList.Any()) ? depositList.Sum(x => x.DepositPrice) : 0,
                SurplusPrice = (depositList != null && depositList.Any()) ? depositList.Sum(x => x.SurplusPrice) : 0,
            };
            return ApiResult.Success("", result);
        }


        #endregion
    }
}