package cn.freemud.management.service;

import cn.freemud.management.enums.DeliveryStatus;
import com.freemud.sdk.api.assortment.order.request.order.AssortmentUpdateDeliveryAbnormalRequest;
import com.freemud.sdk.api.assortment.order.request.order.BaseQueryOrderRequest;
import com.freemud.sdk.api.assortment.order.request.order.UpdateDeliveryInfoByIdRequest;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderBaseService {

    @Autowired
    private OrderCenterSdkService orderCenterSdkService;

    public QueryOrdersResponse.DataBean.OrderBean getByOrderCode(String orderCode) {
        try {
            BaseQueryOrderRequest queryRequest = new BaseQueryOrderRequest();
            queryRequest.setOrderId(orderCode);
            QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(queryRequest);
            if (response.getErrcode() == 100) {
                return response.getData();
            }
            return response.getData();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 创建配送单一车 -> 更新订单为异常单
     *
     * @param partnerId
     * @param orderCode
     * @param deliveryId
     */
    public void updateDeliveryAbnormal(String partnerId, String orderCode, String deliveryId, String operator) {
        AssortmentUpdateDeliveryAbnormalRequest request = AssortmentUpdateDeliveryAbnormalRequest.builder()
                .abnormalDesc("配送异常")
                .deliveryId(deliveryId)
                .orderCode(orderCode)
                .partnerId(partnerId)
                .operator(StringUtils.isNotBlank(operator) ? operator : "sys")
                .build();
        orderCenterSdkService.updateDeliveryAbnormal(request);
    }

    /**
     * 创建配送单成功后 -> 更新订单配送信息
     *
     * @param orderCode
     * @param deliveryId
     */
    public void updateDeliverySuccess(String orderCode, String deliveryId, String operator) {
        // 创建配送单成功
        UpdateDeliveryInfoByIdRequest updateDeliveryInfoByIdRequest = new UpdateDeliveryInfoByIdRequest();
        updateDeliveryInfoByIdRequest.setDeliveryId(deliveryId);
        updateDeliveryInfoByIdRequest.setOrderId(orderCode);
        updateDeliveryInfoByIdRequest.setOrderSubState(DeliveryStatus.WATINGORDER.getCode());
        operator = StringUtils.isNotBlank(operator) ? operator : "sys";
        updateDeliveryInfoByIdRequest.setOperator(operator);
        orderCenterSdkService.updateDeliveryInfoById(updateDeliveryInfoByIdRequest);
    }
}
