package payment

import (
	"errors"
	"fmt"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"

	"tower_api/pkg/util"
	"tower_api/service"
)

// EightUPay 8U支付回调
type EightUPay struct {
	secret  string //每个游戏包的密钥不一样,需要根据不同的游戏包获取
	orderId string //自己平台上生成的订单号
}

func NewEightUPay() *EightUPay {
	return &EightUPay{}
}

func (e *EightUPay) Callback(c *gin.Context) (orderSn string, amount int, err error) {
	//1.请求数据解析
	var callback EightUCallBack
	if c.ShouldBind(&callback) != nil {
		return "", 0, errors.New("params error")
	}
	if callback.Validate() != nil {
		return "", 0, errors.New("params error")
	}
	//1.1 通过订单号找到具体包,找到对应的密钥
	orderService := service.NewOrderService()
	secret := orderService.GetSecret(callback.CpOrderId)
	if secret == "" {
		return "", 0, errors.New("can not find secret")
	}
	//2.验证签名
	tmpSign := callback.GenOrderSign(secret)
	if tmpSign != callback.Sign {
		return "", 0, errors.New("sign error")
	}
	//3. 订单金额转为分
	tmpMoney, _ := strconv.ParseFloat(callback.Money, 64)
	price := int(tmpMoney)
	//4. 返回单号等待处理
	return callback.CpOrderId, price, err
}

func (e *EightUPay) Confirm() error {
	return nil
}

func (e *EightUPay) ReplyContent(success bool) string {
	if success == true {
		return strings.ToLower("SUCCESS")
	} else {
		return strings.ToLower("FAIL")
	}
}

// EightUCallBack 8u支付回调的参数
type EightUCallBack struct {
	Uid       string `form:"uid" json:"uid"`
	Appid     string `form:"appid" json:"appid"`
	CpOrderId string `form:"cpOrderId" json:"cpOrderId"`
	OrderId   string `form:"orderid" json:"orderid"`
	Ext       string `form:"ext" json:"ext"`
	Sign      string `form:"sign" json:"sign"`
	Money     string `form:"money" json:"money"`
	Time      string `form:"time" json:"time"`
}

// Validate 校验参数
func (e *EightUCallBack) Validate() error {
	e.OrderId = strings.TrimSpace(e.OrderId)
	e.CpOrderId = strings.TrimSpace(e.CpOrderId)
	e.Sign = strings.TrimSpace(e.Sign)
	e.Money = strings.TrimSpace(e.Money)
	if isOrderSn(e.CpOrderId) == false || e.Sign == "" {
		return errors.New("parameter invalid")
	}
	//校验金额(8u传过来的是浮点型)
	tmpMoney, _ := strconv.ParseFloat(e.Money, 64)
	if tmpMoney <= 0 {
		return errors.New("parameter invalid")
	}
	return nil
}

// GenOrderSign 生成支付回调的签名
func (e *EightUCallBack) GenOrderSign(appKey string) string {
	str := fmt.Sprintf(
		"uid=%s&appid=%s&money=%s&orderid=%s&ext=%s&time=%s&appkey=%s",
		e.Uid,
		e.Appid,
		e.Money,
		e.OrderId,
		e.Ext,
		e.Time,
		appKey,
	)
	return util.EncodeMD5(str)
}
