package pposRequest

import (
	"PPOSUtils/utils"
	"errors"
	"net/url"
)

//现金订单、会员卡、pos、转账、次卡订单查询..
func (that *PPOSClient) NewOrderQueryRequest() *OrderQueryRequest {
	return &OrderQueryRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/shop/order/moneyQuery",
		},
	}
}

//第三方订单查询..
func (that *PPOSClient) NewOrderApiQueryRequest() *OrderQueryRequest {
	return &OrderQueryRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/shop/order/state",
			publicParamsSlice: []string{
				"parent_order_no",
			},
		},
	}
}

//
type OrderQueryRequest struct {
	Request
	paymentWay int64
}

func (that *OrderQueryRequest) SetTransactionId(value string) *OrderQueryRequest {
	that.initParams()
	that.params.Set("transaction_id", value)
	return that
}
func (that *OrderQueryRequest) SetParentOrderNo(value string) *OrderQueryRequest {
	that.initParams()
	that.params.Set("parent_order_no", value)
	return that
}
func (that *OrderQueryRequest) SetPaymentWay(value int64) *OrderQueryRequest {
	that.paymentWay = value
	return that
}
func (that *OrderQueryRequest) SetIsNotify() *OrderQueryRequest {
	that.initParams()
	that.params.Set("is_notify", "true")
	return that
}

//Params ...
func (that *OrderQueryRequest) Params() (url.Values, error) {
	that.initParams()
	_params := that.params
	_validate := utils.SliceInt{
		10, 20, 30, 80, 90,
	}
	if that.apiAddress == "/shop/order/moneyQuery" && !_validate.InSlice(int(that.paymentWay)) {
		return nil, errors.New(that.apiAddress + ",仅限查询现金订单、会员卡、pos、转账、次卡的订单")
	}
	return _params, nil
}

//
type OrderQueryResponse struct {
	ErrorCode      string `json:"error_code"`
	ReturnMsg      string `json:"return_msg"`
	TradeCode      string `json:"trade_code"`
	TotalFee       string `json:"total_fee"`
	OutTradeNo     string `json:"out_trade_no"`
	TradeStateDesc string `json:"trade_state_desc"`
	TimeEnd        string `json:"time_end"`
}

//Do ...
func (that *OrderQueryRequest) Do() (*OrderQueryResponse, error) {
	//返回data
	_data, _err := that.Client.GetData(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	_mp, _ok := _data.(map[string]interface{})
	if !_ok {
		return nil, errors.New(that.apiAddress + "请求响应格式不正确,错误代码01")
	}
	_slice := []string{"error_code", "return_msg", "trade_code", "total_fee", "out_trade_no", "trade_state_desc", "time_end"}
	for _, _v := range _slice {
		if _, _ok := _mp[_v]; !_ok {
			return nil, errors.New(that.apiAddress + "请求响应格式不正确,错误代码02")
		}
	}
	//返回结果
	_query := new(OrderQueryResponse)
	if _err := that.ParseResponeMp(_query, _mp); _err != nil {
		return nil, errors.New(that.apiAddress + "请求响应格式化异常:" + _err.Error())
	}
	//
	return _query, nil
}
