package wxpay

import (
	"git.rosy.net.cn/baseapi/platformapi/wxpayapi"
	"git.rosy.net.cn/jx-callback/business/auth2/authprovider/weixin"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/partner/pay"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

type PayHandler struct {
	responseHandler pay.ResponseHandler
}

var (
	payHandler *PayHandler
)

func New(responseHandler pay.ResponseHandler) (handler *PayHandler) {
	return &PayHandler{
		responseHandler: responseHandler,
	}
}

func vendorPayType2WxpayType(vendorPayType string) string {
	return vendorPayType
}

func (p *PayHandler) CreatePay(ctx *jxcontext.Context, createParam *pay.CreatePayParam, isOffline bool) (prepayID, qrCodeURL string, err error) {
	param := &wxpayapi.CreateOrderParam{
		OutTradeNo:     createParam.PayOrderID,
		Body:           createParam.ProductDesc,
		NotifyURL:      globals.WxpayNotifyURL,
		SpbillCreateIP: ctx.GetRealRemoteIP(),
		TradeType:      vendorPayType2WxpayType(createParam.VendorPayType),
		TotalFee:       createParam.TotalFee,

		TimeStart:     wxpayapi.Time2PayTime(createParam.TimeStart),
		TimeExpire:    wxpayapi.Time2PayTime(createParam.TimeExpire),
		ProfitSharing: wxpayapi.OptYes,
	}
	if isOffline {
		param.TradeType = wxpayapi.TradeTypeNative
	}
	if authInfo, err := ctx.GetV2AuthInfo(); err == nil && authInfo.GetAuthType() == weixin.AuthTypeMini {
		param.OpenID = authInfo.GetAuthID()
	}
	if result, err := api.WxpayAPI.CreateUnifiedOrder(param); err == nil {
		prepayID = result.PrepayID
		qrCodeURL = result.CodeURL
	}
	return prepayID, qrCodeURL, err
}

func (p *PayHandler) ClosePay(ctx *jxcontext.Context, payOrderID, vendorPayOrderID string) (err error) {
	return api.WxpayAPI.CloseOrder(payOrderID)
}

func (p *PayHandler) RefundPay(ctx *jxcontext.Context, payOrderID, vendorPayOrderID, refundID, reason string, totalFee, refundFee int) (vendorRefundID string, err error) {
	param := &wxpayapi.PayRefundParam{
		OutTradeNo:  payOrderID,
		NotifyURL:   globals.WxpayNotifyURL,
		OutRefundNo: refundID,
		TotalFee:    totalFee,
		RefundFee:   refundFee,
		RefundDesc:  wxpayapi.CData(reason),
	}
	retVal, err := api.WxpayAPI.PayRefund(param)
	if err == nil {
		vendorRefundID = retVal.RefundID
	}
	return vendorRefundID, err
}
