package wxpay

import (
	"git.rosy.net.cn/baseapi/platformapi/wxpayapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner/pay"
)

func OnCallback(msg *wxpayapi.CallbackMsg) (err error) {
	switch msg.MsgType {
	case wxpayapi.MsgTypePay:
		err = onWxpayFinished(msg.Data.(*wxpayapi.PayResultMsg))
	case wxpayapi.MsgTypeRefund:
		err = onWxpayRefund(msg.Data.(*wxpayapi.RefundResultMsg))
	}
	return err
}

func onWxpayFinished(msg *wxpayapi.PayResultMsg) (err error) {
	opResult := &pay.PayOpResult{
		OriginalData: string(utils.MustMarshal(msg)),
	}
	if msg.ReturnCode == wxpayapi.ResponseCodeSuccess {
		opResult.Status = pay.OpStatusSuccessed
		opResult.ID = msg.OutTradeNo
		if msg.ResultCode == wxpayapi.ResponseCodeSuccess {
			opResult.VendorID = msg.TransactionID
		} else {
			opResult.VendorStatus = msg.ErrCode
			opResult.ErrMsg = msg.ErrCodeDes
		}
	} else {
		opResult.Status = pay.OpStatusFailed
	}
	err = payHandler.responseHandler.OnCreatePay(model.VendorIDWXPay, opResult)
	return err
}

func onWxpayRefund(msg *wxpayapi.RefundResultMsg) (err error) {
	opResult := &pay.PayOpResult{
		OriginalData: string(utils.MustMarshal(msg)),
	}
	if msg.ReturnCode == wxpayapi.ResponseCodeSuccess {
		opResult.Status = pay.OpStatusSuccessed
		if msg.ResultCode == wxpayapi.ResponseCodeSuccess {
			opResult.ID = msg.ReqInfoObj.OutRefundNo
			opResult.VendorID = msg.ReqInfoObj.RefundID
		} else {
			opResult.VendorStatus = msg.ErrCode
			opResult.ErrMsg = msg.ErrCodeDes
		}
	} else {
		opResult.Status = pay.OpStatusFailed
	}
	err = payHandler.responseHandler.OnRefundPay(model.VendorIDWXPay, opResult)
	return err
}
