/**
 * 核心服务接口sdk（golang版）
 *
 * @desc 啪啪运动 核心服务接口sdk
 * ---------------------------------------------------------------------
 * @author		tang <unphp@qq.com>
 * @date		2020-09-07
 * @copyright	core-utils
 * ---------------------------------------------------------------------
 */
package cooper

import (
	"encoding/json"
	"errors"
	"net/url"
)

//NewTradeOrderGetRequest ... 获取交易订单
func (that *CooperClient) NewTradeOrderGetRequest() *PayQueryRequest {
	return &PayQueryRequest{
		Request: Request{
			Client: that,
			publicParamsSlice: []string{
				"trade_no",
			},
			apiAddress: "pay/getOrder",
		},
	}
}

//TradeOrderGetRequest
type TradeOrderGetRequest struct {
	Request
}

func (that *TradeOrderGetRequest) SetTradeNo(value string) *TradeOrderGetRequest {
	that.initParams()
	that.params.Set("trade_no", value) //支付中心的交易号
	return that
}

//Params ...
func (that *TradeOrderGetRequest) Params() (url.Values, error) {
	that.initParams()
	_params := that.params
	if that.publicParamsSlice != nil {
		for _, _v := range that.publicParamsSlice {
			if _params.Get(_v) == "" {
				return nil, errors.New(that.apiAddress + "缺少参数:" + _v)
			}
		}
	}
	return _params, nil
}

//Do ...
func (that *TradeOrderGetRequest) Do() (*TradeOrderResponse, error) {
	//返回data
	_data, _err := that.Client.Post(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	//
	_slice := []string{
		"trade_no", //支付中心交易号
	}
	//
	_sliceData, _ok := _data.(map[string]interface{})
	if !_ok {
		return nil, errors.New(that.apiAddress + "请求响应格式不正确")
	}
	//
	for _, _val := range _slice {
		if _, _ok := _sliceData[_val]; !_ok {
			return nil, errors.New(that.apiAddress + "请求响应参数不正确")
		}
	}
	//
	_str, _err := json.Marshal(_sliceData)
	if _err != nil {
		return nil, errors.New(that.apiAddress + _err.Error())
	}
	//返回结果
	_rs := new(TradeOrderResponse)
	_err = json.Unmarshal(_str, &_rs)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + _err.Error())
	}
	return _rs, nil
}
