package api

import (
	"fmt"
	"net/http"
	"pay/bus"
	"pay/conf"
	"pay/db/model"
	"pay/utils"
	"strings"

	"github.com/go-pay/gopay/wechat/v3"
	"infish.cn/comm"
)

type MutliWechatPayCallback struct {
}

func NewMutliWechatPayCallback() PayCallback {
	return &MutliWechatPayCallback{}
}

func (w *MutliWechatPayCallback) CallBack(c *http.Request) (interface{}, error) {
	fmt.Println("--------------------------------------------wechat-multi-callback----------------------------------------")
	fmt.Println("---------------------------------------------------------------------------------------------------------")
	notifyReq, err := wechat.V3ParseNotify(c)
	if err != nil {
		return "FAIL", err
	}
	multiCnf := utils.GetMultiPayConfig(conf.AppConfig)

	// result, err := notifyReq.DecryptCipherText("BSNDcbbL5r122gEdoCSd9tGNIPNvjSxx")
	result, err := notifyReq.DecryptCipherText(multiCnf.WechatPay.ApiV3Key)
	if err != nil {
		return "FAIL", err
	}

	// multiPayCnf := utils.GetMultiPayConfig(conf.AppConfig)
	// refund, err := notifyReq.DecryptRefundCipherText(multiPayCnf.WechatPay.ApiV3Key)

	// fmt.Printf("%#v\n", refund)
	// {Mchid:"", OutTradeNo:"wechat_63116317f17ac790a0e71a81", TransactionId:"4200001591202209212097988473",
	// OutRefundNo:"632ad588ba4c081d98c4016d", RefundId:"50302003512022092125115377323", RefundStatus:"SUCCESS",
	// SuccessTime:"2022-09-21T17:12:49+08:00",
	// UserReceivedAccount:"支付用户零钱", Amount:(*wechat.RefundAmount)(0xc00011f500)}

	orderSlice := strings.Split(result.OutTradeNo, "_")
	payMode := 1
	res := &model.OrderMsg{Id: orderSlice[1], PayMode: &payMode, ModName: orderSlice[0]}
	if result.TradeState == "SUCCESS" {
		fmt.Println("----------------success----------------------")
		err = bus.NatsCenter.PushMessage(comm.NewAppPaySuccSubject(orderSlice[0]), res)
		if err != nil {
			fmt.Println("----------------success-err----------------------")
			return "FAIL", err
		}
	} else {
		fmt.Println("----------------fail----------------------")
		err = bus.NatsCenter.PushMessage(comm.NewAppPayFailSubject(orderSlice[0]), res)
		if err != nil {
			fmt.Println("----------------fail-err----------------------")
			return "FAIL", err
		}
	}
	fmt.Println("----------------success-end----------------------")
	return "SUCCESS", nil
}
