using CloudGaming.Code.Contract;
using CloudGaming.Code.Payment;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;

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

namespace CloudGaming.Code.WeChat;


/// <summary>
/// 微信支付  
/// </summary>
public class WeChatPayment(WechatTenpayClient client, WeChatConfig weChatConfig, AppConfig appConfig, int userId) : IPayment
{
    public async Task<(string orderId, string order, string payNotifyUrl)> CreateOrder(int productId, string productName, decimal price, params object[] args)
    {
        //var orderId = GenerateTimestampIdWithOffset();
        var orderId = PaymentExtend.GenerateCustomString("WX", userId, productId, "001");
        //var client = new WechatTenpayClient(wechatTenpayClientOptions);
        /* 以 JSAPI 统一下单接口为例 */
        string sign = $"{appConfig.Identifier}{orderId}{userId}";
        sign = MD5Encryption.ComputeMD5Hash(sign);
        var notifyUrl = weChatConfig.NotifyUrl.Replace("${pay}", "wx").Replace("${orderId}", orderId).Replace("${tenant}", appConfig.Identifier).Replace("${sign}", sign);

        var request = new CreatePayTransactionAppRequest()
        {
            OutTradeNumber = orderId,
            AppId = weChatConfig.AppId,
            Description = productName,
            ExpireTime = DateTimeOffset.Now.AddMinutes(20),
            NotifyUrl = notifyUrl,
            Amount = new CreatePayTransactionJsapiRequest.Types.Amount()
            {
                Total = (int)(price * 100)
            },
        };

        var response = await client.ExecuteCreatePayTransactionAppAsync(request);
        if (response.IsSuccessful())
        {
            var paramMap = client.GenerateParametersForAppPayRequest(request.AppId, response.PrepayId);
            //Console.WriteLine("PrepayId：" + response.PrepayId);
            return new(orderId, JsonConvert.SerializeObject(paramMap), notifyUrl);
        }
        throw new Exception("微信下单失败");
    }
}
