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

package cooper

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

//NewMQ ...
func (that *CooperClient) NewMQ() *MQRequest {
	return &MQRequest{
		Client:     that,
		apiAddress: "/mq/publish",
	}
}

type MQReturn struct {
	data utils.Mp
}

//MQRequest mq队列请求参数..
type MQRequest struct {
	Client       *CooperClient
	ExchangeName string `json:"exchange_name"` //交换器名称
	RouteKey     string `json:"route_key"`     //路由关键字
	Data         string `json:"data"`          //消息参数
	DelayTime    int64  `json:"delay_time"`    //延迟时间戳
	apiAddress   string
}

//SetExchangeName...
func (that *MQRequest) SetExchangeName(name string, key ...string) *MQRequest {
	that.ExchangeName = name
	if len(key) > 0 {
		that.RouteKey = key[0]
	}
	return that
}

//SetData...
func (that *MQRequest) SetData(data string) *MQRequest {
	that.Data = data
	that.apiAddress = "/mq/publish"
	return that
}

//SetDelayTime...
func (that *MQRequest) SetDelayTime(delayTime int64) *MQRequest {
	that.DelayTime = delayTime
	return that
}

//Params ...
func (that *MQRequest) Params() (url.Values, error) {
	var m = make(url.Values)
	m.Set("exchange_name", that.ExchangeName)
	m.Set("route_key", that.RouteKey)
	m.Set("data", that.Data)
	m.Set("delay_time", utils.ToString(that.DelayTime))
	return m, nil
}

//Do ...
func (that *MQRequest) Do() (*MQReturn, error) {
	//
	_data, _err := that.Client.Post(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	_res, _ok := _data.(map[string]interface{})
	if !_ok {
		return nil, errors.New("mq return data type is:" + utils.TypeOf(_data))
	}
	return &MQReturn{_res}, nil
}

//eg...
func (that *MQRequest) Demo() (*MQReturn, error) {
	_obj := NewCooperClient("10010", "sV3UGoORqzNtsKhSbY3MgAIUGs3U83oB", "http://192.168.1.95:8192")
	_mp := _obj.NewMQ()
	_mp.SetExchangeName("ex_cooper", "cooper_wx_pay_notice")
	_mp.SetData("")
	_mp.SetDelayTime(0)
	return _mp.Do()
}
