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.Response.Product;
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using UserService = Hncore.Pass.Vpn.Service.UserService;

namespace Hncore.Pass.Vpn.Controllers
{
    [ApiVersion("1.0")]
    [Route("api/course/v{version:apiVersion}/product/[action]")]
    public class ProductController : HncoreControllerBase
    {
        private ProductService m_ProductService;
        private UserService m_UserService;
        private ProductPackageService m_ProductPackageService;
        private ProductUserPriceService m_ProductUserPriceService;
        public ProductController(UserService _UserService,ProductService _ProductServic, ProductPackageService _ProductPackageService, ProductUserPriceService m_ProductUserPriceService)
        {
            m_ProductService = _ProductServic;
            m_ProductPackageService = _ProductPackageService;
            m_UserService = _UserService;
            this.m_ProductUserPriceService = m_ProductUserPriceService;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody]ProductEntity request)
        {
            request.TenantId = this.Request.GetManageUserInfo().TenantId;
            await m_ProductService.Add(request);
            return Success();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Put([FromBody]ProductEntity request)
        {
            var entity = await m_ProductService.GetById(request.Id);
            entity.Name = request.Name;
            entity.Profile = request.Profile;
            entity.Image = request.Image;
            entity.RefundDayPrice = request.RefundDayPrice;
            entity.DayLimitPrice = request.DayLimitPrice;
            await m_ProductService.Update(entity);
            return Success();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> PutConfig([FromBody]ProductEntity request)
        {
            var entity = await m_ProductService.GetById(request.Id);
            entity.Account = request.Account;
            entity.Pwd = request.Pwd;
            entity.BaseUrl = request.BaseUrl;
            entity.Token = "";
            await m_ProductService.Update(entity);
            return Success();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> PutSoft([FromBody]ProductEntity request)
        {
            var entity = await m_ProductService.GetById(request.Id);
            entity.PcClientDownloadUrl = request.PcClientDownloadUrl;
            entity.SimulatorDownloadUrl = request.SimulatorDownloadUrl;
            entity.DroidDownloadUrl = request.DroidDownloadUrl;
            entity.IosDownloadUrl = request.IosDownloadUrl;
            await m_ProductService.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_ProductService.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_ProductService.GetById(id);
            return Success(data);
        }

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

        [HttpGet,AllowAnonymous]
        public async Task<ApiResult> OpenPage([FromQuery]PageRequestBase request)
        {
            // Expression<Func<ProductEntity, bool>> expr = m => 1 == 1;
            // if (request.KeyWord.Has())
            // {
            //     expr = expr.And(m => m.Name.Contains(request.KeyWord));
            // }
            // var ret = await m_ProductService.PageAsc(request.PageIndex, request.PageSize, expr, true,m=>m.Sort);
            // var data = ret.ToApiResult();
            return null;
        }

        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> ProductWithPackage()
        {
            var respList = await m_ProductService.ProductWithPackage();
            return Success(respList);
        }


        [HttpGet]
        public async Task<ApiResult> ProductUserPrice(int userId)
        {
            var ret = await this.m_ProductUserPriceService.GetPackageUserPrice(userId);           
            return Success(ret);
        }

        [HttpPost]
        public async Task<ApiResult> SetProductLine([FromQuery]int id)
        {
            var productEntity = await m_ProductService.GetById(id);
            if (productEntity == null)
            {
                return Error("产品不存在");
            }
            productEntity.Status = productEntity.OnLine == 0 ? 1 : 0;
            await m_ProductService.Update(productEntity);

            return Success(productEntity.Status);
        }

        [HttpPost]
        public async Task<ApiResult> SetPackageLine([FromQuery]int id)
        {
            var packageEntity = await m_ProductPackageService.GetById(id);
            if (packageEntity == null)
            {
                return Error("套餐不存在");
            }
            packageEntity.Status = packageEntity.Status == 0 ? 1 : 0;
            await m_ProductPackageService.Update(packageEntity);

            return Success(packageEntity.Status);
        }

        [HttpPost]
        public async Task<ApiResult> SetUserPriceStatus([FromQuery]int id)
        {
            var userPriceEntity = await m_ProductUserPriceService.GetById(id);
            if (userPriceEntity == null)
            {
                return Error("请设置会员价");
            }
            var userEntity = await m_UserService.Query(m => m.Id==userPriceEntity.UserId).FirstOrDefaultAsync();
            userEntity.discount_id = -1;
            await m_UserService.Update(userEntity);

            userPriceEntity.Status = userPriceEntity.Status == 0 ? 1 : 0;
            await m_ProductUserPriceService.Update(userPriceEntity);
            return Success(userPriceEntity.Status);
        }


        [HttpPost]
        public async Task<ApiResult> PutPackage([FromBody]ProductPackageEntity request)
        {
            var packageEntity = await m_ProductPackageService.GetById(request.Id);
            if (packageEntity == null)
            {
                return Error("套餐不存在");
            }
            packageEntity.LinePrice = request.LinePrice;
            packageEntity.MinPrice = request.MinPrice;
            packageEntity.Name = request.Name;
            packageEntity.Price = request.Price;
            packageEntity.Profile = request.Profile;
            packageEntity.Title = request.Title;            
            await m_ProductPackageService.Update(packageEntity);
            return Success(packageEntity);
        }


        [HttpPost]
        public async Task<ApiResult> PutUserPrice([FromBody]PutUserPriceRequest request)
        {
            var userPriceEntity = await m_ProductUserPriceService.Query(m => m.PackageId == request.PackageId && m.UserId == request.UserId).FirstOrDefaultAsync();
            var userEntity = await m_UserService.Query(m => m.Id==request.UserId).FirstOrDefaultAsync();
            userEntity.discount_id = -1;
            await m_UserService.Update(userEntity);
            var price = request.UserPrice;
            var packageEntity =await m_ProductPackageService.GetById(request.PackageId);
          //  var product = await m_ProductService.GetById(packageEntity.ProductId);
            if (request.UserPrice < packageEntity.MinPrice && packageEntity.MinPrice > 0)
            {
                return Error($"不能低于最低限额[{ packageEntity.MinPrice}]");
            }

            var productEntity = await m_ProductService.GetById(packageEntity.ProductId);

            if (productEntity.DayLimitPrice>0&&request.RefundDayPrice < productEntity.DayLimitPrice)
            {
                return Error($"退款单价不能低于[{ productEntity.DayLimitPrice}]");
            }

            //toto
            if (userPriceEntity == null)
            {
                userPriceEntity =new ProductUserPriceEntity()
                {
                    PackageId = request.PackageId,
                    ProductId = request.ProductId,
                    UserId = request.UserId,
                    UserPrice = request.UserPrice,
                    Status = 1,
                    DeleteTag = 0,
                    Remark=request.Remark,
                    RefundDayPrice= request.RefundDayPrice
                };
               await m_ProductUserPriceService.Add(userPriceEntity);
            }
            else
            {               
                userPriceEntity.UserPrice = request.UserPrice;
                userPriceEntity.RefundDayPrice = request.RefundDayPrice;
                userPriceEntity.Remark = request.Remark;
                await m_ProductUserPriceService.Update(userPriceEntity);
            }          
            return Success(1);
        }
    }
}
