package tao_vegetable

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/domain"
	request2 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/request"
	"io/ioutil"
	"net/http"
)

// ReaderOrderInfo 获取订单状态回调
func (a *API) ReaderOrderInfo(c *http.Request) (*CallbackOrder, string, error) {
	body, _ := ioutil.ReadAll(c.Body)

	if len(body) == 0 {
		return nil, "", nil
	}
	var callbackOrder *CallbackOrder
	if err := json.Unmarshal(body, &callbackOrder); err != nil {
		return nil, "", err
	}

	return callbackOrder, string(body), nil
}

// QueryOrderDetail 自配送查询订单详情
func (a *API) QueryOrderDetail(req *request2.AlibabaAelophyOrderGetRequest) (*domain.AlibabaAelophyOrderGetOrderResponse, error) {
	client := ability591.NewAbility591(&a.client)
	data, _ := client.AlibabaAelophyOrderGet(req, a.token)
	if !*data.ApiResult.Success {
		return nil, fmt.Errorf(*data.ApiResult.ErrMsg)
	}

	return data.ApiResult.Model, nil
}

// DeliveryFinish 订单一下的没一个状态通知接口
// ACCEPTED = 商户接单 REJECTED = 商户取消订单 PICKED = 拣货完成 PACKAGED = 打包出库 SHIPPING = 开始配送 SIGN = 用户签收 REFUSED = 用户拒收
func (a *API) DeliveryFinish(req *request2.AlibabaAelophyOrderWorkCallbackRequest) error {
	client := ability591.NewAbility591(&a.client)

	data, err := client.AlibabaAelophyOrderWorkCallback(req, a.token)
	if err != nil {
		return err
	}
	if data != nil && !*data.ApiResult.Success {
		return fmt.Errorf(*data.ApiResult.ErrMsg)
	}

	return nil
}

// DeliveryTrajectory 自配送轨迹回传(骑手开始配送之后同步订单数据)
func (a *API) DeliveryTrajectory(req *request2.AlibabaAelophyOrderLogisticsTraceCallbackRequest) error {
	client := ability591.NewAbility591(&a.client)

	data, _ := client.AlibabaAelophyOrderLogisticsTraceCallback(req, a.token)

	if !*data.ApiResult.Success {
		return fmt.Errorf(*data.ApiResult.ErrMsg)
	}
	return nil
}

// DelivererChange 骑手信息变化时传入
func (a *API) DelivererChange(req *request2.AlibabaAelophyOrderDelivererChangeRequest) error {
	client := ability591.NewAbility591(&a.client)

	data, err := client.AlibabaAelophyOrderDelivererChange(req, a.token)
	if err != nil {
		return err
	}

	if data != nil && !*data.ApiResult.Success {
		return fmt.Errorf(*data.ApiResult.ErrMsg)
	}
	return nil
}
