package tonglianpayapi

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

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

func (a *API) AccessAPI(action string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	params := make(map[string]interface{})
	params["appid"] = a.appID
	params["cusid"] = a.cusID
	params["randomstr"] = utils.GetUUID()
	params["version"] = "12"
	params = utils.MergeMaps(params, bizParams)
	signStr := a.signParam(params)
	params["sign"] = signStr
	var fullURL string
	if action == sepcAction2 {
		fullURL = utils.GenerateGetURL(prodURL2, action, nil)
	} else {
		fullURL = utils.GenerateGetURL(prodURL, action, nil)
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			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")
			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 {
				returnCode := utils.Interface2String(jsonResult1["trxstatus"])
				if returnCode != TrxStatusSuccess {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(utils.Interface2String(jsonResult1["errmsg"])+utils.Interface2String(jsonResult1["retmsg"]), returnCode)
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) CreateUnitorderOrder(param *CreateUnitorderOrderParam) (result *CreateUnitOrderOrderResult, err error) {
	params := make(map[string]interface{})
	params["trxamt"] = param.Trxamt
	params["notify_url"] = param.NotifyUrl
	params["reqsn"] = param.Reqsn
	params["acct"] = param.Acct
	params["paytype"] = param.PayType
	params["sub_appid"] = param.SubAppID
	retVal, err := a.AccessAPI(sepcAction, params)
	if err == nil {
		utils.Map2StructByJson(retVal, &result, false)
	}
	return result, err
}

func (a *API) PayRefund(param *PayRefundParam) (result *PayRefundResult, err error) {
	params := make(map[string]interface{})
	params["trxamt"] = param.Trxamt
	params["reqsn"] = param.Reqsn
	//params["oldreqsn"] = param.OldReqsn
	params["remark"] = param.Remark
	params["oldtrxid"] = param.OldTrxID
	retVal, err := a.AccessAPI("unitorder/refund", params)
	if err == nil {
		utils.Map2StructByJson(retVal, &result, false)
	}
	return result, err
}

func (a *API) CreateH5UnitorderOrder(param *CreateH5UnitorderOrderParam) (err error) {
	params := make(map[string]interface{})
	params["trxamt"] = param.Trxamt
	params["reqsn"] = param.Reqsn
	params["charset"] = param.Charset
	params["body"] = param.Body
	params["returl"] = param.Returl
	_, err = a.AccessAPI(sepcAction2, params)
	return
}
