using Hncore.Infrastructure.EntitiesExtension;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Request.Product;
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Hncore.Pass.Vpn.Controllers
{
    [ApiVersion("1.0")]
    [Route("api/course/v{version:apiVersion}/scheme/[action]")]
    public class ProductSchemeController : HncoreControllerBase
    {
        private ProductService m_ProductService;
        private ProductPackageService m_ProductPackageService;
        private ProductUserPriceService m_ProductUserPriceService;
        private ProductPriceSchemeService m_PriceSchemeService;
        private ProductPriceDiscountService m_PriceDiscountService;
        public ProductSchemeController(ProductService _ProductServic
            , ProductPackageService _ProductPackageService
            , ProductUserPriceService _ProductUserPriceService
            ,ProductPriceSchemeService _PriceSchemeService
            ,ProductPriceDiscountService _PriceDiscountService
            )
        {
            m_ProductService = _ProductServic;
            m_ProductPackageService = _ProductPackageService;
            m_ProductUserPriceService = _ProductUserPriceService;
            m_PriceSchemeService = _PriceSchemeService;
            m_PriceDiscountService = _PriceDiscountService;

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody]ProductPriceSchemeEntity request)
        {           
            await m_PriceSchemeService.Add(request);
            return Success();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Put([FromBody]ProductPriceSchemeEntity request)
        {
            var entity = await m_PriceSchemeService.GetById(request.Id);
            entity.Name = request.Name;
            entity.Remark = request.Remark;           
            entity.discount = request.discount;           
            entity.UpdateTime = DateTime.Now;          
            await m_PriceSchemeService.Update(entity);
            return Success();
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Delete([FromQuery]int id)
        {
            var flag = await m_PriceSchemeService.DeleteById(id);
            if (flag)
                return Success();
            else
                return Error("删除失败");
        }


        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> Get([FromQuery]int id)
        {
            var data = await m_PriceSchemeService.GetById(id);
            return Success(data);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> Page([FromQuery]PageRequestBase request)
        {
            Expression<Func<ProductPriceSchemeEntity, bool>> expr = m => 1 == 1;
            if (request.KeyWord.Has())
            {
                expr = expr.And(m => m.Name.Contains(request.KeyWord));
            }
            var ret = await m_PriceSchemeService.Page(request.PageIndex, request.PageSize, expr,true);
            var data = ret.ToApiResult();
            return data;
        }


        [HttpGet]
        public async Task<ApiResult> GetProductDiscount(int id)
        {
            var ret = await this.m_PriceDiscountService.GetPriceDiscount(id);           
            return Success(ret);
        }


        [HttpPost]
        public async Task<ApiResult> PutProductDiscount([FromBody]ProductPriceDiscountEntity request)
        {
            var priceDiscountEntity = await m_PriceDiscountService.Query(m => m.PackageId == request.PackageId && m.SchemeId == request.SchemeId).FirstOrDefaultAsync();

            if (priceDiscountEntity == null)
            {
                await m_PriceDiscountService.Add(request);
            }
            else
            {
                priceDiscountEntity.BuyPriceDiscount = request.BuyPriceDiscount;
                priceDiscountEntity.RefundDayPriceDiscount = request.RefundDayPriceDiscount;
                await m_PriceDiscountService.Update(priceDiscountEntity);
            }
            return Success(1);
        }

        [HttpPost]
        public async Task<ApiResult> SetUserDiscount([FromBody] SetUserDiscountRequest request)
        {
            var priceDiscountEntitys = await m_PriceDiscountService.Query(m => m.SchemeId == request.SchemeId).ToListAsync();
            var schemaEntity = await m_PriceSchemeService.GetById(request.SchemeId);
            var produccts = await m_ProductService.GetAll(true);
            var packages = await m_ProductPackageService.GetAll(true);

            var userPrices = await m_ProductUserPriceService.GetPackageUserPrice(request.UserId);
            foreach (var item in priceDiscountEntitys)
            {
                var product = produccts.FirstOrDefault(m => m.Id == item.ProductId);
                var package = packages.FirstOrDefault(m => m.Id == item.PackageId);
                var userPakcagePrices = userPrices.FirstOrDefault(m => m.Product.Id == item.ProductId)?.PackageUserPrices;
                var userPrice = userPakcagePrices?.FirstOrDefault(uPrice => uPrice.Package.Id == item.PackageId && uPrice.UserPrice.UserId == request.UserId)?.UserPrice;
                if (userPrice != null && userPrice.Id > 0)
                {
                    userPrice.Status = 1;
                    userPrice.UserPrice = item.BuyPriceDiscount / 100m * package.LinePrice;
                    userPrice.RefundDayPrice = item.RefundDayPriceDiscount / 100m * product.RefundDayPrice;
                    userPrice.Remark = schemaEntity.Name;
                    userPrice.UserPrice = Math.Max(userPrice.UserPrice, package.MinPrice);
                    userPrice.RefundDayPrice = Math.Max(userPrice.RefundDayPrice.Value, product.DayLimitPrice.Value);
                    await m_ProductUserPriceService.Update(userPrice);
                }
                else
                {
                    userPrice = new ProductUserPriceEntity()
                    {
                        PackageId = item.PackageId,
                        ProductId = item.ProductId,
                        Status = 1,
                        Remark = schemaEntity.Name,
                        TenantId = 0,
                        UserId = request.UserId,
                        UserPrice = item.BuyPriceDiscount / 100m * package.LinePrice,
                        RefundDayPrice = item.RefundDayPriceDiscount / 100m * product.RefundDayPrice,
                    };
                    userPrice.UserPrice = Math.Max(userPrice.UserPrice, package.MinPrice);
                    userPrice.RefundDayPrice = Math.Max(userPrice.RefundDayPrice.Value, product.DayLimitPrice.Value);
                    await m_ProductUserPriceService.Add(userPrice);
                }
            }
            return Success(1);
        }
    }
}
