package alipay

import (
	"context"

	"bsm/full/module/finance/wallet/internal/config"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"
)

type AliPay struct {
	ctx    context.Context
	Client *alipay.Client
	Body   *gopay.BodyMap
}

func NewAlipay() (*AliPay, error) {
	// 初始化支付宝客户端
	//    appid：应用ID
	//    privateKey：应用私钥，支持PKCS1和PKCS8
	//    isProd：是否是正式环境
	client, err := alipay.NewClient(config.Spec.Alipay.AppID, config.Spec.Alipay.PrivateKey, config.Spec.Alipay.IsProd)
	if err != nil {
		return nil, err
	}
	// 打开Debug开关，输出日志，默认关闭
	client.DebugSwitch = gopay.DebugOn

	// 设置支付宝请求 公共参数
	client.SetLocation(alipay.LocationShanghai)       // 设置时区，不设置或出错均为默认服务器时间
	client.SetCharset(alipay.UTF8)                    // 设置字符编码，不设置默认 utf-8
	client.SetSignType(alipay.RSA2)                   // 设置签名类型，不设置默认 RSA2
	client.SetReturnUrl(config.Spec.Alipay.ReturnURL) // 设置返回URL
	client.SetNotifyUrl(config.Spec.Alipay.NotifyURL) // 设置异步通知URL

	// 自动同步验签（只支持证书模式）
	// 传入 alipayCertPublicKey_RSA2.crt 内容
	client.AutoVerifySign([]byte(config.Spec.Alipay.PublicKeyRsa2Byte))

	// 公钥证书模式
	err = client.SetCertSnByPath(config.Spec.Alipay.CertPublicKey, config.Spec.Alipay.CertRoot, config.Spec.Alipay.CertPublicKeyRsa2)
	if err != nil {
		return nil, err
	}

	return &AliPay{
		Client: client,
		// ctx:    context.Background(),
	}, nil
}

func (srv *AliPay) SetBody(body, orderNo string, amount int64) {
	srv.Body.Set("subject", config.Spec.Wallet.Name).
		Set("body", body). //finance_payment表的identity
		Set("product_code", "QUICK_WAP_WAY").
		Set("out_trade_no", orderNo).
		Set("total_amount", amount/100).
		Set("timeout_express", "60m").
		Set("quit_url", config.Spec.Alipay.QuitURL)
}

func (srv *AliPay) TradeWapPay() (string, error) {
	result, err := srv.Client.TradeWapPay(srv.ctx, *srv.Body)
	return result, err
}

func (srv *AliPay) TradeAppPay() (string, error) {
	result, err := srv.Client.TradeAppPay(srv.ctx, *srv.Body)
	return result, err
}
