package uuptapi

import (
	"crypto/md5"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
	"math/rand"
	"net/http"
	"sort"
	"strings"
	"time"
)

const (
	BaseURL = "https://openapi.uupt.com/v2_0" //正式环境
	//BaseURL       = "http://openapi.test.uupt.com/v2_0" //沙箱环境测试
	ReturnSuccess = "ok"   //返回成功
	ReturnFail    = "fail" //返回失败
	signKey       = "sign"
	secretKey     = "secret"
	letters       = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
)

func (a *API) MakeUURequestHead() map[string]interface{} {
	requestParam := make(map[string]interface{}, 4)
	requestParam["timestamp"] = utils.Int64ToStr(time.Now().Unix())
	requestParam["nonce_str"] = randStr()
	requestParam["openid"] = a.openid
	requestParam["appid"] = a.appid
	return requestParam
}
func New(appID, appKey, openID string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	if appID == "" {
		return nil
	}
	return &API{
		appid:  appID,
		appKey: appKey,
		openid: openID,
		client: &http.Client{Timeout: curConfig.ClientTimeout},
		config: &curConfig,
	}
}

func (a *API) signParam(params map[string]interface{}) (sign string) {
	keyValues := make([]string, 0)
	for k, v := range params {
		if k != signKey {
			temp := fmt.Sprint(v)
			if (k == "goods_weight" || k == "shop_id" || k == "goods_price") && temp == "0" {
				continue
			}
			if temp != "" {
				keyValues = append(keyValues, k+"="+temp)
			}
		}
	}
	sort.Sort(sort.StringSlice(keyValues)) //字典升序
	sign = strings.Join(keyValues, "&")
	sign += "&key=" + a.appKey   //末尾拼接密钥
	sign = strings.ToUpper(sign) //大写
	return fmt.Sprintf("%X", md5.Sum([]byte(sign)))
}

func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	bizParams["sign"] = a.signParam(bizParams)
	//序列化
	//data, err := json.Marshal(bizParams)
	//if err != nil {
	//	return nil, err
	//}
	//完整请求url
	fullPath := utils.GenerateGetURL(baseUrl, actionApi, nil)
	//发送请求
	sendUrl := func() *http.Request {
		var request *http.Request
		if method == RequestPost {
			request, _ = http.NewRequest(http.MethodPost, fullPath, strings.NewReader(utils.Map2URLValues(bizParams).Encode()))
		} else {
			request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
		}
		request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		return request
	}
	//数据解析
	dataMarshal := func(response *http.Response, bodyStr string, jsonResp map[string]interface{}) (errMsg string, err error) {
		if jsonResp == nil {
			return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
		}
		if jsonResp["return_code"] != ReturnSuccess {
			errMsg = platformapi.ErrLevelGeneralFail
			err = utils.NewErrorCode(jsonResp["return_msg"].(string), utils.Int64ToStr(utils.MustInterface2Int64(jsonResp["return_code"])))
		}
		retVal = jsonResp
		return errMsg, err
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
	return retVal, err
}

//以下为辅助函数
func randStr() string {
	b := make([]byte, 16)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}
