package cygx

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/refunddomestic"
	payUtils "github.com/wechatpay-apiv3/wechatpay-go/utils"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
)

const (
	//MchPKFileName              = "./utils/cert/apiclient_key.pem"
	//MchPKFileName              = "../hongze_mfyx/utils/cert/apiclient_key.pem"
	MchPKFileName              = "/home/code/wechat_cert/cygx/apiclient_key.pem"
	Mchid                      = "1624495680"
	MchCertificateSerialNumber = "5ED2719CFAE5205763034AD80BF4B8A33533C418"
	MchAPIv3Key                = "W1tbnzQrzQ7yRRNuQCIHjis8dgdasKVX"
)

// 微信商户建立连接
//func getWechatClient() (context.Context, *core.Client, error) {
//	var err error
//	defer func() {
//		if err != nil {
//			fmt.Println(err)
//			go alarm_msg.SendAlarmMsg(fmt.Sprint("微信商户建立连接失败 getWechatClient, err：", err.Error()), 2)
//		}
//	}()
//	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
//	mchPrivateKey, err := payUtils.LoadPrivateKeyWithPath(MchPKFileName)
//	if err != nil {
//		log.Print("load merchant private key error")
//		return nil, nil, err
//	}
//	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)
//		return nil, nil, err
//	}
//	return ctx, client, nil
//}

var WechatCertClient *core.Client

// 微信商户建立连接(全局)
func init() {
	if !utils.FileIsExist(MchPKFileName) {
		//fmt.Println("商户私钥文件不存在")
		go alarm_msg.SendAlarmMsg("微信商户链接失败 商户私钥文件不存在", 2)
		return
	}
	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	mchPrivateKey, err := payUtils.LoadPrivateKeyWithPath(MchPKFileName)
	if err != nil {
		fmt.Println(err)
		go alarm_msg.SendAlarmMsg("微信商户链接失败 LoadPrivateKeyWithPath"+err.Error(), 2)
	}
	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(Mchid, MchCertificateSerialNumber, mchPrivateKey, MchAPIv3Key),
	}

	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		fmt.Println(err)
		go alarm_msg.SendAlarmMsg("微信商户链接失败 NewClient"+err.Error(), 2)
	}
	WechatCertClient = client
	return
}

// 微信商户退款
func RefundsApiService(orderDetail *cygx.CygxOrderResp) (statusCode int, err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("微信商户退款失败 RefundsApiService, err：", err.Error()), 2)
		}
	}()
	//ctx, client, err := getWechatClient()
	//if err != nil {
	//	//log.Printf("getWechatClientt err:%s", err)
	//	return
	//}
	ctx := context.Background()
	svc := refunddomestic.RefundsApiService{Client: WechatCertClient}
	resp, result, err := svc.Create(ctx,
		refunddomestic.CreateRequest{
			//SubMchid:      core.String(Mchid),
			TransactionId: core.String(orderDetail.OutTradeCode),
			OutTradeNo:    core.String(orderDetail.OutTradeNo),
			OutRefundNo:   core.String("RE" + orderDetail.OrderCode),
			Reason:        core.String("退款"),
			NotifyUrl:     core.String(utils.Wx_MFYX_Refund_NotifyUrl),
			FundsAccount:  refunddomestic.REQFUNDSACCOUNT_AVAILABLE.Ptr(),
			Amount: &refunddomestic.AmountReq{
				Currency: core.String("CNY"),
				//From: []refunddomestic.FundsFromItem{refunddomestic.FundsFromItem{
				//	Account: refunddomestic.ACCOUNT_AVAILABLE.Ptr(),
				//	Amount:  core.Int64(444),
				//}},
				Refund: core.Int64(int64(orderDetail.PayMoney * 100)),
				Total:  core.Int64(int64(orderDetail.PayMoney * 100)),
			},
		},
	)
	if err != nil {
		return
	} else {
		utils.FileLogCygx.Info("status=%d resp=%s", result.Response.StatusCode, resp)
	}
	statusCode = result.Response.StatusCode

	return
}
