using Hncore.Infrastructure.Service;
using Hncore.Pass.Sells.Domain;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hncore.Pass.Sells.Service
{
    public class CouponUserUseService : ServiceBase<CouponUserUseEntity>, IFindService
    {
        CourseContext m_DbContext;
        public CouponUserUseService(CourseContext dbContext, IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {
            m_DbContext = dbContext;
        }

        public async Task<List<CouponUserUseEntity>> GetUsedCoupon(int userId, int couponId = 0)
        {
            var ret = await this.Query(m => m.UserId == userId && (couponId == 0 || m.CouponId == couponId)).ToListAsync();
            var origins = ret.GroupBy(m => m.CouponId).Select(m =>
            {
                var usedCoupon = new CouponUserUseEntity()
                {
                    CouponCount = m.Sum(p => p.CouponCount),
                    CouponId = m.Key,
                    UserId = userId
                };
                return usedCoupon;
            });
            return origins.ToList();
        }
    }
}
