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"     // 订单支付失败
)

type T struct {
	Data struct {
		KsOrderNo                string      `json:"ks_order_no"`
		RefundType               interface{} `json:"refund_type"`
		OutRefundNo              interface{} `json:"out_refund_no"`
		KsSettleNo               interface{} `json:"ks_settle_no"`
		Channel                  string      `json:"channel"`
		OutOrderNo               string      `json:"out_order_no"`
		KsRefundFailReason       interface{} `json:"ks_refund_fail_reason"`
		ApplyRefundReason        interface{} `json:"apply_refund_reason"`
		PromotionAmount          int         `json:"promotion_amount"`
		DeveloperPromotionAmount int         `json:"developer_promotion_amount"`
		ExtraInfo                string      `json:"extra_info"`
		SettleAmount             interface{} `json:"settle_amount"`
		OrderAmount              int         `json:"order_amount"`
		EnablePromotion          bool        `json:"enable_promotion"`
		OutSettleNo              interface{} `json:"out_settle_no"`
		RefundAmount             interface{} `json:"refund_amount"`
		TradeNo                  string      `json:"trade_no"`
		Attach                   string      `json:"attach"`
		KsRefundNo               interface{} `json:"ks_refund_no"`
		Status                   string      `json:"status"`
	} `json:"data"`
	BizType   string `json:"biz_type"`
	MessageId string `json:"message_id"`
	AppId     string `json:"app_id"`
	Timestamp int64  `json:"timestamp"`
}

// 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 err := utils.Map2StructByJson(callback.Data, &payCallback, false); err != nil {
			return nil, nil, "", callback.MessageId, err
		}
		return payCallback, nil, CallbackTypePay, callback.MessageId, nil
	case CallbackTypeRefund:
		var refundCallback *RefundCallBack
		if err := utils.Map2StructByJson(callback.Data, &refundCallback, false); err != nil {
			return nil, nil, "", callback.MessageId, err
		}
		return nil, refundCallback, CallbackTypeRefund, callback.MessageId, nil
	case CallbackTypeSettle:
		return nil, nil, "", callback.MessageId, errors.New("无效回调类型")
	default:
		return nil, nil, "", callback.MessageId, errors.New("无效回调类型")
	}
}
