package mtmemberapi

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

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

const (
	prodURL = "https://wechat.chengquan.cn"
)

type API struct {
	client *http.Client
	config *platformapi.APIConfig
}

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

func (a *API) AccessAPI(action string, url string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	fullURL := utils.GenerateGetURL(url, action, nil)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(bizParams).Encode()))
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			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")
			}
			if err == nil {
				if utils.MustInterface2Int64(jsonResult1["errorCode"]) != http.StatusOK {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(utils.Interface2String(jsonResult1["errorMsg"]), utils.Int64ToStr(utils.MustInterface2Int64(jsonResult1["errorCode"])))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) RechargeExchange(account int, shortLink string) (err error) {
	_, err = a.AccessAPI("uniteExchange/rechargeExchange", prodURL, map[string]interface{}{
		"account":   account,
		"shortLink": shortLink,
	})
	return err
}
