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 {
		retVal.OrderPrice = utils.Float64ToStr(utils.Str2Float64(retVal.OrderPrice) + float64(utils.WayBillDeliveryMarkUp/100))
		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跑腿未返回取消运单详情")
	}
}

// GetOrderLiquidatedDamages 获取订单的违约金
func (a *API) GetOrderLiquidatedDamages(wayBillOrderID, orderID string) (int64, error) {
	preParam := a.MakeUURequestHead()
	preParam["order_code"] = wayBillOrderID
	preParam["origin_id"] = orderID
	resp, err := a.AccessAPI(BaseURL, "gethomeservicefee.ashx", RequestPost, preParam)
	if err != nil {
		return 0, err
	}

	var deductFee *LiquidatedDamagesFee
	if err := utils.Map2StructByJson(resp, &deductFee, false); err != nil {
		return 0, err
	}

	if deductFee.ReturnCode != "ok" {
		return 0, fmt.Errorf(deductFee.ReturnMsg)
	}

	return utils.Float64TwoInt64(utils.Str2Float64(deductFee.DeductFee) * 100), nil
}

type LiquidatedDamagesFee struct {
	DeductFee  string `json:"deduct_fee"`  // 违约金
	NonceStr   string `json:"nonce_str"`   // 随机字符串，不长于32位
	Sign       string `json:"sign"`        // 加密签名，详情见消息体签名算法
	Appid      string `json:"appid"`       // 第三方用户唯一凭证
	ReturnMsg  string `json:"return_msg"`  // 返回信息，如非空，为错误原因，如签名失败、参数格式校验错误
	ReturnCode string `json:"return_code"` // 状态，ok/fail表示成功
}

// 支付小费
func (a *API) AddTip(orderId, deliveryId string, tipFee int) error {
	param := a.MakeUURequestHead()
	param["order_code"] = deliveryId // 运单号
	param["origin_id"] = orderId     // 订单单号
	param["onlinefee"] = tipFee      // 小费金额

	resp, err := a.AccessAPI(BaseURL, "payonlinefee.ashx", RequestPost, param)
	if err != nil {
		return err
	}
	var result *AddTipResult
	if err := utils.Map2StructByJson(resp, result, false); err != nil {
		return err
	}
	if result.ReturnCode != "ok" {
		return fmt.Errorf(result.ReturnMsg)
	}
	return nil
}

type AddTipResult struct {
	ReturnCode string `json:"return_code"` // 状态，ok/fail表示成功
	ReturnMsg  string `json:"return_msg"`  // 通知消息
	AppID      string `json:"appid"`
	NonceStr   string `json:"nonce_str"`
	Sign       string `json:"sign"`
}
