package service

import (
	"context"
	"fmt"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"log"
	"time"
)

func NativeApiServicePrepay(tradeId string, amount int64) (codeUrl string, err error) {

	var (
		mchID                      string = "1615933939"                               // 商户号
		mchCertificateSerialNumber string = "33DDFEC51BF5412F663B9B56510FD567B625FC68" // 商户证书序列号
		mchAPIv3Key                string = "fvV2xDHuM8ch3QagCkLChEMsikUTSNiI"         // 商户APIv3密钥
	)
	fmt.Println("充值的金额为：", amount)
	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
	if err != nil {
		log.Print("load merchant private key error")
	}

	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Printf("new wechat pay client err:%s", err)
	}

	svc := native.NativeApiService{Client: client}
	resp, result, err := svc.Prepay(ctx,
		native.PrepayRequest{
			Appid:         core.String("wxac396a3be7a16844"),
			Mchid:         core.String("1615933939"),
			Description:   core.String("样叽微信支付充值"),
			OutTradeNo:    core.String(tradeId),
			TimeExpire:    core.Time(time.Now()),
			Attach:        core.String("微信支付充值"),
			NotifyUrl:     core.String("https://www.weixin.qq.com/wxpay/pay.php"),
			SupportFapiao: core.Bool(true),
			Amount: &native.Amount{
				Currency: core.String("CNY"),
				Total:    core.Int64(amount),
			},
		},
	)

	if err != nil {
		// 处理错误
		log.Printf("call Prepay err:%s", err)
		return "", err
	} else {
		// 处理返回结果
		log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
		log.Println("codeUrl:", *resp.CodeUrl)
	}
	return *resp.CodeUrl, nil
}

func QueryOrderByOutTradeNo(tradeId string) (status string, err error) {

	var (
		mchID                      string = "1615933939"                               // 商户号
		mchCertificateSerialNumber string = "33DDFEC51BF5412F663B9B56510FD567B625FC68" // 商户证书序列号
		mchAPIv3Key                string = "V12345678910Younggee10987654321V"         // 商户APIv3密钥
	)

	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
	if err != nil {
		log.Print("load merchant private key error")
	}

	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Printf("new wechat pay client err:%s", err)
	}

	svc := native.NativeApiService{Client: client}
	resp, result, err := svc.QueryOrderByOutTradeNo(ctx,
		native.QueryOrderByOutTradeNoRequest{
			OutTradeNo: core.String(tradeId),
			Mchid:      core.String("1615933939"),
		},
	)
	fmt.Printf("支付 %+v\n", resp)
	if err != nil {
		// 处理错误
		log.Printf("call QueryOrderByOutTradeNo err:%s", err)
		return "", err
	} else {
		// 处理返回结果
		log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
	}
	fmt.Printf("支付状态 %+v\n", *resp.TradeState)
	return *resp.TradeState, nil
}
