package tiktok_api

import (
	"crypto/md5"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	beego "github.com/astaxie/beego/server/web"
	"io/ioutil"
	"net/http"
	"net/url"
)

func GetCmd(request *http.Request) (cmd string) {
	cmd, _ = url.QueryUnescape(request.FormValue("tag"))
	return cmd
}

// EventSignChange 回调消息防伪标签校验
func (a *API) EventSignChange(c *http.Request) (*CallbackResponse, []byte) {
	body, _ := ioutil.ReadAll(c.Body)
	if beego.BConfig.RunMode == "jxgy" || beego.BConfig.RunMode == "jxpet" {
		return CallbackResponseErr(true), body
	}
	return &CallbackResponse{Code: CallbackSuccessCode, Msg: CallbackSuccess}, body
	signParam := a.appKey + string(body) + a.appSecret
	sign := fmt.Sprintf("%X", md5.Sum([]byte(signParam)))
	return CallbackResponseErr(sign != c.Header.Get("event-sign")), body
}

func (a *API) unmarshalData(data []byte, msg interface{}) (callbackResponse *CallbackResponse) {
	err := utils.UnmarshalUseNumber(data, msg)
	return CallbackResponseErr(err == nil)
}

func CallbackResponseErr(param bool) (callbackResponse *CallbackResponse) {
	if param {
		return &CallbackResponse{Code: CallbackSuccessCode, Msg: CallbackSuccess}
	}
	return &CallbackResponse{Code: CallbackFailCode, Msg: CallbackFail}
}

func Err2CallbackResponse(err error, data string) *CallbackResponse {
	if err == nil {
		return &CallbackResponse{Code: CallbackSuccessCode, Msg: CallbackSuccess}
	}
	if data == "" {
		data = err.Error()
	}
	return &CallbackResponse{
		Code: CallbackFailCode,
		Msg:  data,
	}
}
