package uuptapi

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
)

//计算订单价格
func (a *API) GetOrderPrice(req map[string]interface{}) (*GetOrderPriceResp, error) {
	preParam := a.MakeUURequestHead()
	resp, err := a.AccessAPI(BaseURL, "getorderprice.ashx", RequestPost, utils.MergeMaps(preParam, req))
	if err != nil {
		return nil, err
	}
	if resp["return_code"] != ReturnSuccess {
		return nil, fmt.Errorf("UU跑腿获取运单价格失败:%s", resp["return_msg"])
	}
	retVal := GetOrderPriceResp{}
	if temp, err := json.Marshal(resp); err == nil {
		err = json.Unmarshal(temp, &retVal)
	}
	con := retVal != GetOrderPriceResp{}
	if con {
		return &retVal, nil
	} else {
		return nil, fmt.Errorf("UU跑腿未返回运单价格")
	}
}

//发布订单
func (a *API) AddOrder(req map[string]interface{}) (orderCode, originID string, err error) {
	preParam := a.MakeUURequestHead()
	resp, err := a.AccessAPI(BaseURL, "addorder.ashx", RequestPost, utils.MergeMaps(preParam, req))
	if err != nil {
		return "", "", err
	}
	if resp["return_code"] != ReturnSuccess {
		return "", "", fmt.Errorf("UU跑腿发布运单失败:%s", resp["return_msg"])
	}
	retVal := AddOrderResp{}
	if temp, err := json.Marshal(resp); err == nil {
		err = json.Unmarshal(temp, &retVal)
	}
	con := retVal != AddOrderResp{}
	if con {
		return retVal.OrderCode, retVal.OriginID, nil
	} else {
		return "", "", fmt.Errorf("UU跑腿未返回运单ID")
	}
}

//查询订单信息
func (a *API) GetOrderDetail(orderCode string) (*GetOrderDetailResp, error) {
	preParam := a.MakeUURequestHead()
	preParam["order_code"] = orderCode
	resp, err := a.AccessAPI(BaseURL, "getorderdetail.ashx", RequestPost, preParam)
	if err != nil {
		return nil, err
	}
	if resp["return_code"] != ReturnSuccess {
		return nil, fmt.Errorf("UU跑腿获取运单详情失败:%s", resp["return_msg"])
	}
	retVal := GetOrderDetailResp{}
	if temp, err := json.Marshal(resp); err == nil {
		err = json.Unmarshal(temp, &retVal)
	}
	con := retVal != GetOrderDetailResp{}
	if con {
		return &retVal, nil
	} else {
		return nil, fmt.Errorf("UU跑腿未返回运单详情")
	}
}

//取消订单
func (a *API) CancelOrder(orderCode, reason string) error {
	preParam := a.MakeUURequestHead()
	preParam["order_code"] = orderCode
	preParam["reason"] = reason
	resp, err := a.AccessAPI(BaseURL, "cancelorder.ashx", RequestPost, preParam)
	if err != nil {
		return err
	}
	if resp["return_code"] != ReturnSuccess {
		return fmt.Errorf("UU跑腿取消运单失败:%s", resp["return_msg"])
	}
	retVal := CancelOrderResp{}
	if temp, err := json.Marshal(resp); err == nil {
		err = json.Unmarshal(temp, &retVal)
	}
	con := retVal != CancelOrderResp{}
	if con {
		return nil
	} else {
		return fmt.Errorf("UU跑腿未返回取消运单详情")
	}
}
