package pposRequest

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

//NewPayRefundRequest ... 会员卡退款
func (that *PPOSClient) NewPayRefundRequest() *PayRefundRequest {
	return &PayRefundRequest{
		Request: Request{
			Client: that,
			publicParamsSlice: []string{
				"src_trade_no", //原支付流水号
				"trade_no",     //支付中心发起退单的交易号
				"pay_worth",    //扣除价值
			},
			apiAddress: "/member/memberCard/payRefund",
		},
	}
}

//NewClassRefundRequest ... 课时卡退款
func (that *PPOSClient) NewClassRefundRequest() *PayRefundRequest {
	return &PayRefundRequest{
		Request: Request{
			Client: that,
			publicParamsSlice: []string{
				"src_trade_no", //原支付流水号
				"trade_no",     //支付中心发起退单的交易号
				"pay_worth",    //扣除价值
			},
			apiAddress: "/class/studentCourse/payRefund",
		},
	}
}

//PayRefundRequest
type PayRefundRequest struct {
	Request
}

func (that *PayRefundRequest) SetSrcTradeNo(value string) *PayRefundRequest {
	that.initParams()
	that.params.Set("src_trade_no", value) //原支付流水号
	return that
}
func (that *PayRefundRequest) SetTradeNo(value string) *PayRefundRequest {
	that.initParams()
	that.params.Set("trade_no", value) //新退款交易号
	return that
}
func (that *PayRefundRequest) SetPayWorth(value string) *PayRefundRequest {
	that.initParams()
	that.params.Set("pay_worth", value) //退款金额(价值)
	return that
}
func (that *PayRefundRequest) SetOrderFrom(value interface{}) *PayRefundRequest {
	that.initParams()
	that.params.Set("order_from", utils.ToString(value)) //订单来源
	return that
}

//Params ...
func (that *PayRefundRequest) 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 *PayRefundRequest) Do() (*MemberCardPayResponse, error) {
	//返回data
	_data, _err := that.Client.GetData(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	//
	_sliceData, _ok := _data.(map[string]interface{})
	if !_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(MemberCardPayResponse)
	_err = json.Unmarshal(_str, &_rs)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + _err.Error())
	}
	return _rs, nil
}
