package phpjx

import (
	"fmt"
	"net/http"
	"strings"

	"git.rosy.net.cn/baseapi"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

type API struct {
	token     string
	appKey    string
	appSecret string
	client    *http.Client
	config    *platformapi.APIConfig
}

const (
	ResponseCodeSuccess = 200
)

const (
	prodURL = "https://www.jingxicaishi.com/index.php/Weimendian/index"
)

var (
	exceedLimitCodes = map[int]int{}
	canRetryCodes    = map[int]int{}
)

var (
	jxAPI *API
)

func NewAPI(token, appKey, appSecret string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	return &API{
		token:     token,
		appKey:    appKey,
		appSecret: appSecret,
		client:    &http.Client{Timeout: curConfig.ClientTimeout},
		config:    &curConfig,
	}
}

func init() {
	jxAPI = NewAPI("", "", "")
}

func (a *API) AccessAPI(apiStr string, jxParams map[string]interface{}, traceInfo string) (retVal map[string]interface{}, err error) {
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			params := utils.MergeMaps(jxParams, map[string]interface{}{
				"timestamp": utils.GetCurTimeStr(),
			})
			var request *http.Request
			if false {

			} else {
				fullURL := prodURL + "/" + apiStr
				// baseapi.SugarLogger.Debug(utils.Map2URLValues(params).Encode())
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
				request.Header.Set("charset", "UTF-8")
				request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			}
			if traceInfo != "" {
				request.Header.Set(platformapi.KeyTrackInfo, traceInfo)
			}
			// request.Close = true //todo 为了性能考虑还是不要关闭
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			code := int(utils.Interface2Int64WithDefault(jsonResult1["code"], 0))
			if code == ResponseCodeSuccess {
				retVal = jsonResult1
				return platformapi.ErrLevelSuccess, nil
			}
			newErr := utils.NewErrorIntCode(jsonResult1["msg"].(string), code)
			if _, ok := exceedLimitCodes[code]; ok {
				return platformapi.ErrLevelExceedLimit, newErr
			} else if _, ok := canRetryCodes[code]; ok {
				return platformapi.ErrLevelRecoverableErr, newErr
			} else {
				baseapi.SugarLogger.Debugf("jx AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
				return platformapi.ErrLevelCodeIsNotOK, newErr
			}
		})
	return retVal, err
}
