package sfps2

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/globals"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
)

type Response struct {
	HttpStatusCode int `json:"http_status_code"`
	BaseRetVal     *BaseRetVal
}

type BaseRetVal struct {
	ErrorCode int         `json:"error_code"`
	ErrorMsg  string      `json:"error_msg"`
	ErrorData interface{} `json:"error_data"`
	Result    interface{} `json:"result"`
}

func New(devId int, devKey string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}

	return &API{
		devId:  int64(devId),
		devKey: devKey,
		locker: sync.RWMutex{},
		client: &http.Client{Timeout: curConfig.ClientTimeout},
		config: &curConfig,
	}
}

func (a *API) SignParam(params []byte) (sig string) {
	sign := fmt.Sprintf("%s&%d&%s", string(params), a.devId, a.devKey)
	md2sign := md5.Sum([]byte(sign))
	return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%x", md2sign)))
}

func (a *API) HttpPostJson(url string, data interface{}) *Response {
	//序列化参数
	b, err := json.Marshal(data)
	if err != nil {
		var msg = fmt.Sprintf("json serialize err:%+v", err)
		fmt.Println(msg)
		result := Response{
			HttpStatusCode: 500,
		}
		return &result
	}
	//签名
	sign := a.SignParam(b)
	fullUrl := utils.GenerateGetURL(BaseURL, url, map[string]interface{}{"sign": sign})
	request, err := http.NewRequest(http.MethodPost, fullUrl, strings.NewReader(string(b)))
	client := &http.Client{}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	resp, err := client.Do(request)
	if err != nil {
		globals.SugarLogger.Errorf(" HttpPostJson err %v", err)
		return nil
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		globals.SugarLogger.Errorf(" ReadAll err %v", err)
		return nil
	}

	result := Response{
		HttpStatusCode: resp.StatusCode,
	}

	var content BaseRetVal
	err = json.Unmarshal(body, &content)
	if err == nil {
		result.BaseRetVal = &content
	} else {
		globals.SugarLogger.Errorf(" Unmarshal err %v", err)
		return nil
	}

	return &result
}

func CallbackResponseErr(param bool) (callbackResponse *CallbackResponse) {
	if param {
		return &CallbackResponse{ErrorCode: FailCode, ErrorMsg: FailMsg}
	}
	return &CallbackResponse{ErrorCode: SuccessCode, ErrorMsg: SuccessMsg}
}
