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 SingleWechatPayCallback struct {
}

func NewSingleWechatPayCallback() PayCallback {
	return &SingleWechatPayCallback{}
}

func (a *SingleWechatPayCallback) CallBack(c *http.Request) (interface{}, error) {
	fmt.Println("--------------------------------------------wechat-single-callback----------------------------------------")
	fmt.Println("---------------------------------------------------------------------------------------------------------")

	sinlePayCnf := utils.GetSinglePayConfig(conf.AppConfig)
	notifyReq, err := wechat.V3ParseNotify(c)
	if err != nil {
		return "FAIL", err
	}
	result, err := notifyReq.DecryptCipherText(sinlePayCnf.WechatPay.ApiV3Key)

	// 退款通知解密
	// refund, err := notifyReq.DecryptRefundCipherText(sinlePayCnf.WechatPay.ApiV3Key)
	if err != nil {
		return "FAIL", err
	}

	// ========异步通知应答========
	// 退款通知http应答码为200且返回状态码为SUCCESS才会当做商户接收成功，否则会重试。
	// 注意：重试过多会导致微信支付端积压过多通知而堵塞，影响其他正常通知。

	orderSlice := strings.Split(result.OutTradeNo, "_")
	payMode := 1
	// orderSlice[0] 代表来源 mall cloud sku3d...
	if result.TradeState == "SUCCESS" {
		fmt.Println("----------------success----------------------")
		res := &model.OrderMsg{Id: orderSlice[1], PayMode: &payMode, ModName: orderSlice[0]}
		// err = bus.NatsCenter.PushMessage(comm.NewAppPaySuccSubject(orderSlice[0]), res)
		err = bus.NatsCenter.PushMessage(comm.NewAppPaySuccSubject(orderSlice[0]), res)
		if err != nil {
			fmt.Println("----------------success-err----------------------")
			return "FAIL", err
		}

	} else {
		fmt.Println("----------------fail----------------------")
		res := &model.OrderMsg{Id: orderSlice[1], PayMode: &payMode, ModName: orderSlice[0]}
		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
}
