package ali_logistics_query

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
	"net/http"
	"strings"
)

const (
	//BastUrl           = "https://express3.market.alicloudapi.com" // 基础访问路由
	BastUrl           = "http://express3.market.alicloudapi.com" // 基础访问路由
	GetOrderDetailApi = "express3"                               // 获取物流订单详情
)

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

func New(appKey, appSecret, appCode string, config ...*platformapi.APIConfig) (a *API) {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}

	a = &API{
		appKey:    appKey,
		appSecret: appSecret,
		appCode:   appCode,
		client:    &http.Client{Timeout: curConfig.ClientTimeout},
		config:    &curConfig,
	}
	return a
}

func (a *API) GetAppCode() string {
	return a.appCode
}

func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	// 序列化
	data, err := json.Marshal(bizParams)
	if err != nil {
		return nil, err
	}

	// 发送请求
	sendUrl := func() *http.Request {
		var request *http.Request
		if http.MethodPost == method {
			request, _ = http.NewRequest(http.MethodPost, utils.GenerateGetURL(baseUrl, actionApi, nil), strings.NewReader(string(data)))
		} else {
			request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
		}
		request.Header.Set("Content-Type", "application/json")
		request.Header.Set("Authorization", "APPCODE "+a.appCode)
		return request
	}

	// 数据解析
	dataMarshal := 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 {
			return "", err
		}
		if utils.MustInterface2Int64(jsonResult1["code"]) != 200 {
			errLevel = platformapi.ErrLevelGeneralFail
			err = utils.NewErrorCode(jsonResult1["msg"].(string), utils.Int64ToStr(utils.MustInterface2Int64(jsonResult1["code"])))
		}
		retVal = jsonResult1
		return errLevel, err
	}

	err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
	return retVal, err
}
