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

package cooper

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

//OrderPayQueryRequest 支付查询
type OrderPayQueryRequest struct {
	Client  *CoreClient
	OrderNo string `json:"order_no"` //订单号
}

//Params ...
func (that OrderPayQueryRequest) Params() url.Values {
	var m = make(url.Values)
	m.Set("order_no", that.OrderNo)
	return m
}

//Post ...
func (that OrderPayQueryRequest) Post(result interface{}) (int, error) {
	_response, _err := that.Client.Post("/pay/query", that)
	if _err != nil {
		return 3, _err
	}
	//
	var _data ResponseMap
	_data = make(map[string]interface{})
	if _err := _response.ToJSON(&_data); _err != nil {
		return 2, _err
	}
	if !_data.Has("return_code") || !_data.Has("result_code") {
		return 3, _err
	}
	_returnCode, _ := _data.String("return_code")
	_resultCode, _ := _data.String("result_code")
	//
	if _returnCode == "FAIL" {
		return 3, _err
	}
	//
	if _resultCode == "FAIL" {
		if !_data.Has("err_code") {
			return 3, errors.New("未知错误") //未知错误
		}
		_errCode, _ := _data.String("err_code")
		_errMsg := _data.DefaultString("err_msg", "未知错误")
		switch _errCode {
		case "40001002":
			return 2, errors.New(_errMsg)
		case "40001004":
			return 4, errors.New(_errMsg)
		default: //其他错误，包括参数不合法等
			return 3, errors.New(_errMsg)
		}

	}
	//成功...
	if _returnCode == "SUCCESS" && _resultCode == "SUCCESS" {
		_result, _err := json.Marshal(_data.Get("result"))
		if _err != nil {
			return 3, errors.New("返回结果不符合格式") //未知错误
		}
		//
		if _err := json.Unmarshal(_result, result); _err != nil {
			return 3, errors.New("返回结果不符合格式") //未知错误
		}
		return 0, nil
	}
	return 3, errors.New("未知错误") //未知错误
}
