using CloudGaming.Code.DataAccess;
using CloudGaming.Code.Payment;
using CloudGaming.DtoModel.Account.User;
using CloudGaming.DtoModel.Mall;

using HuanMeng.DotNetCore.Redis;

using Microsoft.EntityFrameworkCore.Storage;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudGaming.Code.Mall;


/// <summary>
/// 订单数据
/// </summary>
public class OrderBLL : CloudGamingBase
{
    public OrderBLL(IServiceProvider serviceProvider) : base(serviceProvider)
    {
    }

    /// <summary>
    /// 创建订单
    /// </summary>
    /// <param name="paymentMethod"></param>
    /// <param name="productId"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    /// <exception cref="NullReferenceException"></exception>
    /// <exception cref="Exception"></exception>
    public async Task<IntentOrderDto> CreateOrder(string paymentMethod, string productId)
    {
        if (_UserId == 0)
        {
            throw new ArgumentNullException("未登录");
        }
        if (string.IsNullOrEmpty(productId))
        {
            throw new ArgumentNullException("产品不能为空");
        }

        var products = Cache.ProductCacheList;
        var product = products.FirstOrDefault(it => it.ProductId == productId);
        if (product == null)
        {
            throw new NullReferenceException("未找到所属产品");
        }
        var redisLock = $"lock:payment:{_UserId}:{productId}";
        if (!RedisCache.StringSetLock(redisLock, "", 5))
        {
            throw new ArgumentNullException("重复创建订单");
        }

        //productEntityCache.get
        IntentOrderDto intentOrderDto = null;
        //创建订单
        try
        {
            var ip = HttpContextAccessor.HttpContext.GetClientIpAddress();
            var price = product.Price;
            var payment = PaymentExtend.GetPayment(paymentMethod, this);
            if (UserInfo.IsTest)
            {
                price = (decimal)0.01;
            }
            (var orderId, var order, var payNotifyUrl) = await payment.CreateOrder(product.Id, product.ProductName, price, product, ip);
            var t = product.ToIntentOrder(paymentMethod, orderId, AppRequestInfo.Channel);
            t.UserId = _UserId;
            t.Channel = AppRequestInfo.Channel;
            if (payNotifyUrl != null && payNotifyUrl.Length > 200)
            {
                payNotifyUrl = payNotifyUrl.Substring(0, 200);
            }
            t.Notes = payNotifyUrl;
            await Dao.DaoUser.Context.AddAsync(t);
            await Dao.DaoUser.Context.SaveChangesAsync();
            intentOrderDto = new IntentOrderDto()
            {
                OrderId = orderId,
                Payment = order
            };
            RedisCache.KeyDelete(redisLock);
        }
        catch (Exception ex)
        {
            RedisCache.KeyDelete(redisLock);
            throw new Exception("创建订单失败");
        }

        return intentOrderDto;
    }

    /// <summary>
    /// 获取订单状态
    /// </summary>
    /// <param name="orderId"></param>
    /// <returns></returns>
    public async Task<BaseResponse<bool>> GetOrderRewardsInfo(string orderId)
    {
        var tips = await Dao.DaoUser.Context.T_User_OrderItems.Where(it => it.OrderId == orderId).Select(it => it.RewardTips).FirstOrDefaultAsync();
        if (string.IsNullOrEmpty(tips))
        {
            return new BaseResponse<bool>(ResponseCode.Success, "", false);
        }
        return new BaseResponse<bool>(ResponseCode.Success, tips, true);
    }
}
