package recharge_phone_bill

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

type API struct {
	account  string
	password string
	secret   string
	locker   sync.RWMutex
	client   *http.Client
	config   *platformapi.APIConfig
}

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

// 大写( md5( md5(密码)+手机号码+产品编码+商户订单号+秘钥 ) ) 话费充值签名接口
func (a *API) signParam(params map[string]interface{}) (sig string) {
	paramsSign := ""
	if params["mobile"] != "" && params["flowCode"] != "" && params["orderNumber"] != "" && params["mobile"] != nil && params["flowCode"] != nil && params["orderNumber"] != nil {
		paramsSign = params["mobile"].(string) + params["flowCode"].(string) + params["orderNumber"].(string)
	}
	oneMd5 := fmt.Sprintf("%x", md5.Sum([]byte(a.password))) + paramsSign + a.secret
	//twoMd5 := strings.ToUpper(fmt.Sprintf("%X", md5.Sum([]byte(oneMd5))))
	return strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(oneMd5))))
}

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

	// 全路径请求参数
	fullURL := utils.GenerateGetURL(baseUrl, actionApi, nil)

	// 发送请求
	sendUrl := func() *http.Request {
		var request *http.Request
		if http.MethodPost == method {
			request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
		} else {
			request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
		}
		request.Header.Set("Content-Type", "application/json")
		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"]) != 2000 {
			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
}
