package cn.freemud.management.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.log.LogTreadLocal;
import cn.freemud.management.entities.dto.request.delivery.DeliveryOrderRequest;
import cn.freemud.management.enums.DeliveryStatus;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.service.OrderBaseService;
import cn.freemud.management.util.CommonResp;
import cn.freemud.management.util.ResponseUtil;
import com.freemud.application.sdk.api.deliverycenter.dto.CancelDeliveryOrderRequestDto;
import com.freemud.application.sdk.api.deliverycenter.dto.CreateDeliveryOrderRequestDto;
import com.freemud.application.sdk.api.deliverycenter.response.CreateDeliveryOrderResponseDto;
import com.freemud.application.sdk.api.deliverycenter.response.DeliveryResponseDto;
import com.freemud.application.sdk.api.deliverycenter.service.DeliveryService;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.freemud.sdk.api.assortment.order.adapter.DeliverySdkAdapter;
import com.freemud.sdk.api.assortment.order.enums.OrderSourceType;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderDeliveryService {

    @Autowired
    private StoreCenterService storeCenterService;
    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private OrderBaseService orderBaseService;
    @Autowired
    private DeliverySdkAdapter deliverySdkAdapter;

    @Value("${saas.order.delivery.callBackUrl}")
    private String deliveryCallBackUrl;

    private int SUCCESS = 100;
    private String delivery_type_self = "self";

    /**
     * 外卖单创建配送信息
     *
     * @param orderCode
     * @return
     */
    public BaseResponse createDelivery(String orderCode, String operator) {
        QueryOrdersResponse.DataBean.OrderBean orderBean = orderBaseService.getByOrderCode(orderCode);
        if (null == orderBean) {
            return CommonResp.fail("订单不存在");
        }
        Pair<Boolean, String> delivery = this.createDelivery(orderBean, null, operator);
        return delivery.getKey()? ResponseUtil.success():ResponseUtil.error(ResponseResult.DELIVERY_CREATE_ORDER_ERROR);
    }

    /**
     * 创建配送信息
     *
     * @param orderBean
     * @return
     */
    public Pair<Boolean, String> createDelivery(QueryOrdersResponse.DataBean.OrderBean orderBean,StoreResponse storeInfo, String operator) {
        Pair<Boolean, String> pair = checkOrderOfDelivery(orderBean);
        if (!pair.getKey()) {
            return new Pair<>(true, "该订单不是外卖类型订单,无需创建配送单");
        }
        if (storeInfo==null){
            storeInfo = storeCenterService.getStoreInfo(new StoreInfoRequest(orderBean.getCompanyId(), orderBean.getShopId()), LogTreadLocal.getTrackingNo());
            if (SUCCESS != storeInfo.getStatusCode() || storeInfo.getBizVO() == null) {
                return new Pair<>(false, "获取门店信息失败");
            }
        }
        // 调用配送系统创建配送单
        CreateDeliveryOrderRequestDto requestDto = deliverySdkAdapter.buildDeliveryOrderRequestDto(orderBean, storeInfo, deliveryCallBackUrl);
        CreateDeliveryOrderResponseDto deliveryResponse = deliveryService.deliveryOrderAdd(requestDto, LogTreadLocal.getTrackingNo());

        if (StringUtils.isBlank(operator)) {
            operator = "系统";
        }
        //创建配送单失败，更新订单为异常单
        if (deliveryResponse == null || SUCCESS != deliveryResponse.getCode() || deliveryResponse.getData() == null) {
            String deliveryId = deliveryResponse != null && deliveryResponse.getData() != null ? deliveryResponse.getData().getDeliveryId() : "";
            orderBaseService.updateDeliveryAbnormal(orderBean.getCompanyId(), orderBean.getOid(), deliveryId, operator);
            return new Pair<>(true, "创建配送单信息失败，配送状态更新为配送异常");
        }
        // 创建配送单成功
        orderBaseService.updateDeliverySuccess(orderBean.getOid(), deliveryResponse.getData().getDeliveryId(), operator);
        return new Pair<>(true, "创建配送单成功");
    }

    /**
     * 校验订单是否符合创建配送单要求
     *
     * @param orderBean
     * @return
     */
    public Pair<Boolean, String> checkOrderOfDelivery(QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //判断外卖单
        if (1 != orderBean.getType()) {
            return new Pair<>(false, "该订单不是外卖类型订单");
        }
        if (!orderBean.getSource().equalsIgnoreCase(OrderSourceType.SAAS.getCode())) {
            return new Pair<>(false, "订单来源异常");
        }
        //配送信息为空，则不创建配送单
        if (orderBean.getAddInfo() == null || orderBean.getAddInfo().getDeliveryType() == null) {
            return new Pair<>(false, "未找到订单配送信息");
        }
        //自配送不创建配送单
        if (delivery_type_self.equalsIgnoreCase(orderBean.getAddInfo().getDeliveryType())) {
            return new Pair<>(false, "该订单为自配送");
        }
        return new Pair<>(true, "success");
    }


    /**
     * 取消外卖配送单
     * @return
     */
    public BaseResponse cancelDeliveryOrder(DeliveryOrderRequest request) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(SUCCESS + "");
        QueryOrdersResponse.DataBean.OrderBean data = orderBaseService.getByOrderCode(request.getOrderCode());
        if (null == data) {
            baseResponse.setCode("101");
            baseResponse.setMessage("订单不存在");
            return baseResponse;
        }
        if (data.getType() == 1 && data.getAddInfo() != null && ObjectUtils.equals(data.getAddInfo().getDeliveryType(), "third")) {
            Integer deliverStatus = data.getAddInfo().getDeliverStatus();
            //运单异常或取消时，无需作废三方配送运单
            if (ObjectUtils.equals(DeliveryStatus.DELIVERYERROR.getCode(), deliverStatus)
                    || ObjectUtils.equals(DeliveryStatus.DELIVERYCANCEL.getCode(), deliverStatus)
                    || ObjectUtils.equals(DeliveryStatus.DELIVERYARRIVED.getCode(), deliverStatus)) {
                return baseResponse;
            }
            //运单状态非待接单或系统接单时，不能取消运单
            if (ObjectUtils.equals(DeliveryStatus.RIDERSTARTDELIVERY.getCode(), deliverStatus)) {
                baseResponse.setCode("101");
                baseResponse.setMessage("配送单不能取消");
                return baseResponse;
            }
            CancelDeliveryOrderRequestDto cancelDeliveryOrderRequestDto = new CancelDeliveryOrderRequestDto();
            cancelDeliveryOrderRequestDto.setDeliveryId(data.getAddInfo().getDeliveryId());
            cancelDeliveryOrderRequestDto.setOrderCancelCode(4);
            //商家退款取消配送
            cancelDeliveryOrderRequestDto.setOrderCancelDescription("顾客取消订单");
            DeliveryResponseDto deliveryResponse = deliveryService.deliveryOrderCancel(cancelDeliveryOrderRequestDto, LogThreadLocal.getTrackingNo());
            if (deliveryResponse == null || SUCCESS != deliveryResponse.getCode()) {
                baseResponse.setCode("101");
                baseResponse.setMessage("取消配送单异常，不能操作");
                return baseResponse;
            }
        }
        return baseResponse;
    }


}
