using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel.Util;

using CloudGaming.Code.Contract;
using CloudGaming.Code.Payment;

using HuanMeng.DotNetCore.MultiTenant;

using Microsoft.Extensions.Options;

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

namespace CloudGaming.Code.Aliyun;

/// <summary>
/// 支付宝支付
/// </summary>
/// <param name="appConfig"></param>
/// <param name="userId"></param>
public class AlipayPayment(AppConfig appConfig, int userId) : IPayment
{
    public Task<(string orderId, string order, string payNotifyUrl)> CreateOrder(int productId, string productName, decimal price, params object[] args)
    {
        if (string.IsNullOrEmpty(productName))
        {
            throw new ArgumentNullException($"产品名称不能为空！");
        }
        var priceStr = price.ToString();
        if (string.IsNullOrEmpty(priceStr))
        {
            throw new ArgumentNullException($"价格不能为空！");
        }
        var orderId = PaymentExtend.GenerateCustomString("ZFB", userId, productId, "001");
        //.SetOptions(GetConfig());
        //AsyncNotify
        //https://pay.shhuanmeng.com/api/${tenant}/zfb/${orderId}
        string sign = $"{appConfig.Identifier}{orderId}{userId}";
        sign = MD5Encryption.ComputeMD5Hash(sign);
        var notifyUrl = appConfig.Payment?.AlipayConfig?.NotifyUrl;
        if (string.IsNullOrEmpty(notifyUrl))
        {
            notifyUrl = "";
        }
        var app = appConfig.Payment?.App();
        if (app == null)
        {
            throw new Exception("支付宝配置错误");
        }
        notifyUrl = notifyUrl.Replace("${pay}", "zfb").Replace("${orderId}", orderId).Replace("${tenant}", appConfig.Identifier).Replace("${sign}", sign);
        var response = app.AsyncNotify(notifyUrl).Optional("passback_params", "PaymentType%3Dzfb").Pay(productName, orderId, priceStr);
        if (!ResponseChecker.Success(response))
        {
            throw new Exception("创建订单失败！" + response.Body);
        }
        //.PreCreate("Apple iPhone11 128G", "2234567234890", "5799.00");
        var zfbOrderId = response.Body;
        return Task.FromResult((orderId, zfbOrderId, notifyUrl));
    }


}
