package bus

import (
	"context"
	"errors"
	"fmt"
	"pay/db/model"
	"pay/log"
	"pay/pay"
	"pay/utils"
	"strconv"

	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"

	cpay "infish.cn/comm/pay"
)

type SingleAliPay struct {
}

func NewSingleAliPay() PayInf {
	return &SingleAliPay{}
}

// Pay 阿里支付
func (a *SingleAliPay) Pay(ctx context.Context, orderMsg *cpay.OrderMsg) (interface{}, error) {
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	amount, err := strconv.ParseFloat(fmt.Sprintf("%.2f", *orderMsg.Amount), 64)
	if err != nil {
		return nil, errors.New("价格parse错误！")
	}
	orderId := orderMsg.Project + "_" + orderMsg.Id.Hex()
	bm.Set("subject", orderMsg.Name).
		Set("scene", "bar_code").
		Set("out_trade_no", orderId).
		Set("total_amount", amount).
		Set("timeout_express", "10m")

	// 下单url
	res, err := pay.SingleAlipayClient.TradePrecreate(ctx, bm)
	if err != nil {
		if bizErr, ok := alipay.IsBizError(err); ok {
			log.Errorf("%+v", bizErr)
			// do something
			return "", err
		}
		log.Errorf("阿里支付信息%v,err:%v\n", bm, err)
		return "", err
	}

	if res.Response.Msg != "Success" {
		return nil, errors.New(res.Response.Msg)
	}

	return res.Response.QrCode, nil

	// return map[string]interface{}{
	// 	"qrCode": res.Response.QrCode,
	// }, nil
}

func (a *SingleAliPay) Close(ctx context.Context, orderMsg *cpay.OrderMsg) (bool, error) {

	orderId := orderMsg.Project + "_" + orderMsg.Id.Hex()
	bm := make(gopay.BodyMap)
	bm.Set("out_trade_no", orderId)
	tradeClose, err := pay.SingleAlipayClient.TradeClose(ctx, bm)
	if err != nil {
		return false, err
	}
	if tradeClose.Response.Code != "10000" {
		return false, errors.New(tradeClose.Response.Msg)
	}
	return true, nil
}

// https://opendocs.alipay.com/apis/api_1/alipay.trade.refund
func (s *SingleAliPay) ReFundPay(ctx context.Context, refund *model.ReFund) (interface{}, error) {
	bm := make(gopay.BodyMap)
	// 整数转换为小数
	parseRefund, err := utils.IntToDecimal(*refund.Refund)
	if err != nil {
		return nil, err
	}
	bm.Set("out_trade_no", refund.TradeNo).
		Set("refund_amount", parseRefund).
		Set("refund_reason", refund.Reason).
		Set("out_request_no", refund.Id.Hex())
	res, err := pay.SingleAlipayClient.TradeRefund(ctx, bm)
	if err != nil {
		if bizErr, ok := alipay.IsBizError(err); ok {
			log.Errorf("%+v", bizErr)
			// do something
			return false, err
		}
		return false, err
	}
	if res.Response.Msg != "Success" {
		return false, errors.New(res.Response.SubMsg)
	}
	// {"errorNo":200,"result":true,"errorDesc":""}

	return true, nil

}

// 文档地址：https://opendocs.alipay.com/apis/api_1/alipay.trade.fastpay.refund.query
func (s *SingleAliPay) ReFundQuery(ctx context.Context, refund *model.ReFund) (interface{}, error) {
	bm := make(gopay.BodyMap)
	bm.Set("out_trade_no", refund.TradeNo).
		Set("out_request_no", refund.Id.Hex())
	// Set("query_options", []string{})

	res, err := pay.SingleAlipayClient.TradeFastPayRefundQuery(ctx, bm)
	if err != nil {
		if bizErr, ok := alipay.IsBizError(err); ok {
			log.Errorf("%+v", bizErr)
			// do something
			return false, err
		}
		return false, err
	}
	if res.Response.Msg != "Success" {
		return false, errors.New(res.Response.SubMsg)
	}

	return res.Response.RefundStatus, nil
	// return res.Response, nil
}
