package kuaishou_mini

import (
	"encoding/json"
	"errors"
	"git.rosy.net.cn/baseapi/utils"
	"io/ioutil"
	"net/http"
)

const (
	CallbackTypePay    = "PAYMENT" // 支付回调
	CallbackTypeRefund = "REFUND"  // 退款回调
	CallbackTypeSettle = "SETTLE"  // 结算回调

	OrderPayStatusHandleing = "PROCESSING" // 支付订单处理中
	OrderPayStatusSuccess   = "SUCCESS"    // 订单支付成功
	OrderPayStatusFailed    = "FAILED"     // 订单支付失败
)

// KauiShouCallback 回调处理
func (a *API) KauiShouCallback(request *http.Request) (*CallBackDetail, *RefundCallBack, string, string, error) {
	data, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return nil, nil, "", "-1", err
	}

	var callback *KauiShouCallbackRes
	if err := json.Unmarshal(data, &callback); err != nil {
		return nil, nil, "", "-1", err
	}

	switch callback.BizType {
	case CallbackTypePay:
		var payCallback *CallBackDetail
		if value, ok := callback.Data.(string); ok {
			if err := json.Unmarshal([]byte(value), &payCallback); err != nil {
				return nil, nil, "", callback.MessageId, err
			}
		} else {
			if err := json.Unmarshal([]byte(utils.Interface2String(value)), &payCallback); err != nil {
				return nil, nil, "", callback.MessageId, err
			}
		}
		return payCallback, nil, CallbackTypePay, callback.MessageId, err
	case CallbackTypeRefund:
		var refundCallback *RefundCallBack
		if value, ok := callback.Data.(string); ok {
			if err := json.Unmarshal([]byte(value), &refundCallback); err != nil {
				return nil, nil, "", callback.MessageId, err
			}
		} else {
			if err := json.Unmarshal([]byte(utils.Interface2String(value)), &refundCallback); err != nil {
				return nil, nil, "", callback.MessageId, err
			}
		}
		return nil, refundCallback, CallbackTypeRefund, callback.MessageId, err
	case CallbackTypeSettle:
		return nil, nil, "", callback.MessageId, errors.New("无效回调类型")
	default:
		return nil, nil, "", callback.MessageId, errors.New("无效回调类型")
	}
}

// KuaiShouRefundCallBack 快手退款回调
//func (a *API) KuaiShouRefundCallBack(request *http.Request) (*RefundCallBack, error) {
//	data, err := ioutil.ReadAll(request.Body)
//	if err != nil {
//		return nil, err
//	}
//
//	var callback *RefundCallBack
//	if err := json.Unmarshal(data, &callback); err != nil {
//		return nil, err
//	}
//
//	return callback, err
//}

// KuaiShouSettleCallBack 当订单结算成功之后，快手小程序服务端会通过 post 方式回调开发者提供的 HTTP 接口
//func (a *API) KuaiShouSettleCallBack(request *http.Request) (*SettleCallback, error) {
//	data, err := ioutil.ReadAll(request.Body)
//	if err != nil {
//		return nil, err
//	}
//
//	var callback *SettleCallback
//	if err := json.Unmarshal(data, &callback); err != nil {
//		return nil, err
//	}
//
//	return callback, err
//}
