package api

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

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

type MutliAliPayCallback struct {
}

func NewMutliAliPayCallback() PayCallback {
	return &MutliAliPayCallback{}
}

// CallBack 阿里回调
func (a *MutliAliPayCallback) CallBack(c *http.Request) (interface{}, error) {
	fmt.Println("--------------------------------------------alipay-multi-callback----------------------------------------")
	fmt.Println("---------------------------------------------------------------------------------------------------------")
	notifyReq, err := alipay.ParseNotifyToBodyMap(c) // c.Request 是 gin 框架的写法
	if err != nil {
		return "fail", err
	}

	orderSlice := strings.Split(notifyReq["out_trade_no"].(string), "_")
	payMode := 0 // 支付宝模式
	res := &model.OrderMsg{Id: orderSlice[1], PayMode: &payMode, ModName: orderSlice[0]}

	if notifyReq["trade_status"] == "TRADE_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
}
