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

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

//NewPayQueryRequest ... 微信、支付宝、其他支付方式订单状态查询
func (that *CooperClient) NewPayQueryRequest() *PayQueryRequest {
	return &PayQueryRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{
				//...
			},
			apiAddress: "/pay/query",
		},
	}
}

//NewRefundQueryRequest ... 微信、支付宝、其他支付方式退单状态查询
func (that *CooperClient) NewRefundQueryRequest() *PayQueryRequest {
	return &PayQueryRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{
				//...
			},
			apiAddress: "/pay/refundQuery",
		},
	}
}

//PayQueryRequest
type PayQueryRequest struct {
	Request
}

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

func (that *PayQueryRequest) SetTransactionId(value string) *PayQueryRequest {
	that.initParams()
	that.params.Set("transaction_id", value) //第三方订单号
	return that
}

//Params ...
func (that *PayQueryRequest) 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 *PayQueryRequest) Do() (*PayResponse, error) {
	//返回data
	_data, _err := that.Client.Post(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	//
	_slice := []string{
		"trade_no", //支付中心交易号
		"order_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(PayResponse)
	_err = json.Unmarshal(_str, &_rs)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + _err.Error())
	}
	return _rs, nil
}
