package cn.freemud.management.service.handle;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.log.LogTreadLocal;
import cn.freemud.management.adapter.DeliverySdkAdapter;
import cn.freemud.management.entities.dto.request.delivery.DeliveryOrderHaltedRequest;
import cn.freemud.management.entities.dto.request.order.OrderManagerRequest;
import cn.freemud.management.enums.DeliveryStatus;
import cn.freemud.management.enums.ResponseResult;
import cn.freemud.management.intercept.DeliveryServiceException;
import cn.freemud.management.intercept.OrderServiceException;
import cn.freemud.management.service.OrderBaseService;
import cn.freemud.management.thirdparty.DeliveryMCCafeClient;
import cn.freemud.management.util.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.couponcenter.offline.response.CouponRedeemResponse;
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.service.EmailAlertService;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
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.Component;


/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: 配送服务处理类
 * @Package cn.freemud.management.service.handle
 * @Description:
 * @author: shuhu.hou
 * @date: 2020/4/26 15:44
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
@Slf4j
public class DeliveryHandle {

    private static final String THIRD = "third";
    private static final String delivery_type_self = "self";
    private static final int SUCCESS = 100;

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

    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private DeliverySdkAdapter deliverySdkAdapter;
    @Autowired
    private OrderBaseService orderBaseService;
    @Autowired
    private DeliveryMCCafeClient deliveryMCCafeClient;
    @Autowired
    private EmailAlertService emailAlertService;


    /**
     * 创建配送单
     *
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse createDelivery(QueryOrdersResponse.DataBean.OrderBean orderBean, OrderManagerRequest request, StoreResponse storeInfo) {
        if (storeInfo == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), storeInfo.getStatusCode().toString()) || storeInfo.getBizVO() == null) {
            return ResponseUtil.error(ResponseResult.STORE_INFO_NOT_FOUND);
        }
        if (!checkOrderOfDelivery(orderBean)) {
            return ResponseUtil.success();
        }
        // 调用配送系统创建配送单
        CreateDeliveryOrderRequestDto requestDto = deliverySdkAdapter.buildDeliveryOrderRequestDto(orderBean, storeInfo, deliveryCallBackUrl);
        CreateDeliveryOrderResponseDto deliveryResponse = deliveryService.deliveryOrderAdd(requestDto, LogTreadLocal.getTrackingNo());

        String operator = request == null || StringUtils.isBlank(request.getOperator()) ? "系统" : request.getOperator();
        //创建配送单失败，更新订单为异常单
        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 ResponseUtil.success();
        }
        // 创建配送单成功
        orderBaseService.updateDeliverySuccess(orderBean.getOid(), deliveryResponse.getData().getDeliveryId(), operator);
        return ResponseUtil.success();
    }

    /**
     * 取消配送
     *
     * @param data
     * @param request
     * @return
     */
    public BaseResponse cancelDelivery(QueryOrdersResponse.DataBean.OrderBean data, OrderManagerRequest request) {
        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 ResponseUtil.success();
            }
            //运单状态非待接单或系统接单时，不能取消运单
            if (ObjectUtils.equals(DeliveryStatus.RIDERSTARTDELIVERY.getCode(), deliverStatus)) {
                return ResponseUtil.error(ResponseResult.DELIVERY_CANCEL_ORDER_ERROR);
            }
            CancelDeliveryOrderRequestDto cancelDeliveryOrderRequestDto = new CancelDeliveryOrderRequestDto();
            cancelDeliveryOrderRequestDto.setDeliveryId(data.getAddInfo().getDeliveryId());
            cancelDeliveryOrderRequestDto.setOrderCancelCode(4);
            //商家退款取消配送
            cancelDeliveryOrderRequestDto.setOrderCancelDescription("顾客取消订单");
            DeliveryResponseDto deliveryResponse = deliveryService.deliveryOrderCancel(cancelDeliveryOrderRequestDto, LogThreadLocal.getTrackingNo());
            if (deliveryResponse == null || !StringUtils.equals(ResponseResult.SUCCESS.getCode(), deliveryResponse.getCode()+"")) {
                return ResponseUtil.error(ResponseResult.DELIVERY_CANCEL_ORDER_ERROR);
            }
        }
        return ResponseUtil.success();
    }

    /**
     * 配送停单
     *
     * @param data
     * @return
     */
    public BaseResponse haltedDelivery(QueryOrdersResponse.DataBean.OrderBean data) {
        if (data.getType() == 1 && data.getAddInfo() != null && ObjectUtils.equals(data.getAddInfo().getDeliveryType(), THIRD)) {
            DeliveryOrderHaltedRequest deliveryOrderHaltedRequest =new DeliveryOrderHaltedRequest();
            deliveryOrderHaltedRequest.setHaltedReason("foe入机失败");
            deliveryOrderHaltedRequest.setOrderKey(data.getOid());
            deliveryOrderHaltedRequest.setStoreId(data.getShopId());
            DeliveryResponseDto deliveryResponse = deliveryMCCafeClient.halted(deliveryOrderHaltedRequest);
            log.info("配送停机入参：{},出参：{}",JSONObject.toJSONString(deliveryOrderHaltedRequest),JSONObject.toJSON(deliveryResponse));
            if (deliveryResponse == null || !StringUtils.equals(ResponseResult.SUCCESS.getCode(), deliveryResponse.getCode()+"")) {
                emailAlertService.sendEmailAlert("配送单停单失败", String.format("request:%s \r\nresponse:%s", JSONObject.toJSONString(deliveryOrderHaltedRequest), JSONObject.toJSONString(deliveryResponse)));
                return ResponseUtil.error(ResponseResult.DELIVERY_ORDER_STOP_ERROR);
            }
        }
        return ResponseUtil.success();
    }




    /**
     * 校验是否要创建配送单
     *
     * @param orderBean
     * @return
     */
    private boolean checkOrderOfDelivery(QueryOrdersResponse.DataBean.OrderBean orderBean) {
        //判断外卖单
        if (1 != orderBean.getType()) {
            return false;
        }
        //订单来源异常
        if (!orderBean.getSource().equalsIgnoreCase(OrderSourceType.SAAS.getCode())) {
            return false;
        }
        //配送信息为空，则不创建配送单
        if (orderBean.getAddInfo() == null || orderBean.getAddInfo().getDeliveryType() == null) {
            return false;
        }
        //自配送不创建配送单
        if (delivery_type_self.equalsIgnoreCase(orderBean.getAddInfo().getDeliveryType())) {
            return false;
        }
        return true;
    }
}
