package uuptapi

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

const (
	uuCallbackURL = "http://callback.jxc4.com/UuPt/UuWaybillCallback" //uu跑腿订单回调地址
)

var (
	SuccessResponse  = &CallbackResponse{ReturnCode: "ok"}
	SignatureIsNotOk = &CallbackResponse{ReturnCode: "fail"}
)

type CallbackResponse struct {
	ReturnCode string `json:"return_code"`
	ReturnMsg  string `json:"return_msg"`
}

func Err2CallbackResponse(err error) *CallbackResponse {
	if err == nil {
		return &CallbackResponse{
			ReturnCode: ReturnSuccess,
			//ReturnMsg:  ReturnSuccessMsg,
		}
	}
	return &CallbackResponse{
		ReturnCode: ReturnFail,
		ReturnMsg:  utils.Format4Output(err, false),
	}
}

//订单提交后状态变化回调
func (a *API) WaybillCallback(request *http.Request) (*WaybillCallbackParam, string, *CallbackResponse) {
	//if callbackResponse := a.CheckCallbackValidation(request); callbackResponse != nil {
	//	return nil, callbackResponse
	//}
	retVal := WaybillCallbackParam{}
	data := request.PostForm.Get("data")
	b := bytes.NewBufferString(data)
	decoder := json.NewDecoder(b)
	if err := decoder.Decode(&retVal); err != nil {
		return nil, "", Err2CallbackResponse(errors.New("uu跑腿回调参数解析错误,请检查"))
	}
	con := retVal != WaybillCallbackParam{}
	if con {
		return &retVal, data, Err2CallbackResponse(nil)
	} else {
		return nil, "", Err2CallbackResponse(errors.New("UU跑腿运单回调信息为空"))
	}
}

func (a *API) CheckCallbackValidation(request *http.Request) (callbackResponse *CallbackResponse) {
	err := request.ParseForm()
	if err == nil {
		sign := a.signParam(utils.URLValues2Map(request.PostForm))
		if sign != request.FormValue(signKey) {
			return SignatureIsNotOk
		}
	} else {
		callbackResponse = Err2CallbackResponse(err)
	}
	return callbackResponse
}
