using Hncore.Infrastructure.Service;
using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Response.Product;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using Hncore.Infrastructure.Extension;
using System.Linq;
namespace Hncore.Pass.Vpn.Service
{
    public partial class ProductPriceDiscountService : ServiceBase<ProductPriceDiscountEntity>, IFindService
    {
        CourseContext m_DbContext;
        ProductService m_ProductService;
        ProductPackageService m_ProductPackageService;
        public ProductPriceDiscountService(CourseContext dbContext
            , ProductService _ProductService
            , ProductPackageService _ProductPackageService
            , IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {
            m_DbContext = dbContext;
            m_ProductService = _ProductService;
            m_ProductPackageService = _ProductPackageService;
        }

        public async Task<List<ProductWithPriceDiscountResponse>> GetPriceDiscount(int schemeId)
        {
            var products = await m_ProductService.Query(true).OrderBy(m=>m.Sort).ToListAsync();

            var packages = m_ProductPackageService.Query(true);
            var priceDiscount = this.Query(m => m.SchemeId == schemeId);
            var ret = from pakcage in packages
                      join uDiscount in priceDiscount on pakcage.Id equals uDiscount.PackageId into temp
                      from uDiscount in temp.DefaultIfEmpty()
                      select new PackagePriceDiscount()
                      {
                          Package = pakcage,
                          PriceDiscount = uDiscount ?? new ProductPriceDiscountEntity()
                      };
            var packgesPrice = await ret.ToListAsync();

            List<ProductWithPriceDiscountResponse> respList = new List<ProductWithPriceDiscountResponse>();
            products.ForEach(p =>
            {
                var resp = new ProductWithPriceDiscountResponse();
                resp.Product = p.MapTo<ProductResponse>();
                resp.PackageDiscounts = packgesPrice.Where(m => m.Package.ProductId == p.Id).ToList();
                respList.Add(resp);
            });
            return respList;
        }
    }
}
