package cn.freemud.management.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.management.entities.dto.request.console.BizDTO;
import cn.freemud.management.entities.dto.request.console.ConsoleResponseDTO;
import cn.freemud.management.entities.dto.request.console.GetStoreMixRequest;
import cn.freemud.management.entities.dto.request.console.QueryFlag;
import cn.freemud.management.entities.dto.request.delivery.DeliveryOrderRequest;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.service.OrderBaseService;
import cn.freemud.management.service.handle.DeliveryHandle;
import cn.freemud.management.thirdparty.ConsoleApiClient;
import cn.freemud.management.util.ResponseUtil;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderDeliveryService {

    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private OrderBaseService orderBaseService;
    @Autowired
    private DeliveryHandle deliveryHandle;
    @Autowired
    private ConsoleApiClient consoleApiClient;

    private static final int SUCCESS = 100;

    /**
     * 外卖单创建配送信息
     *
     * @param orderCode
     * @return
     */
    public BaseResponse createDelivery(String orderCode, String operator) {
        OrderBeanV1 orderBean = orderBaseService.getByOrderCode(orderCode);
        if (null == orderBean) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        GetStoreMixRequest getStoreMixRequest = GetStoreMixRequest.builder().partnerId(orderBean.getCompanyId()).storeCode(orderBean.getShopId()).build();
        QueryFlag query = QueryFlag.builder().queryBusinessInfo(true).queryStoreInfo(true).build();
        getStoreMixRequest.setQuery(query);
        ConsoleResponseDTO<BizDTO> storeMix = consoleApiClient.getStoreMix(getStoreMixRequest);
        if (ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), storeMix.getStatusCode()) || storeMix.getBizVO() == null || storeMix.getBizVO().getStoreInfo()== null) {
            return ResponseUtil.error(ResponseResult.STORE_INFO_NOT_FOUND);
        }
        return deliveryHandle.createDelivery(orderBean, null, storeMix,false);
    }


    /**
     * 取消外卖配送单
     *
     * @return
     */
    public BaseResponse cancelDeliveryOrder(DeliveryOrderRequest request) {
        OrderBeanV1 data = orderBaseService.getByOrderCode(request.getOrderCode());
        if (null == data) {
            return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
        }
        return deliveryHandle.cancelDelivery(data, null);
    }


}
