package cn.freemud.management.service.handle;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.management.adapter.DeliverySdkAdapter;
import cn.freemud.management.entities.dto.request.console.BizDTO;
import cn.freemud.management.entities.dto.request.console.BusinessInfoDTO;
import cn.freemud.management.entities.dto.request.console.ConsoleResponseDTO;
import cn.freemud.management.entities.dto.request.console.ExpandFieldsDTO;
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.service.OrderBaseService;
import cn.freemud.management.thirdparty.DeliveryMCCafeClient;
import cn.freemud.management.util.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.ApiLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.service.EmailAlertService;
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;

import java.util.Objects;


/**
 * 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
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;
    @Value("${delivery.support.ordersource}")
    private String supportOrderSource;

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


    /**
     * 创建配送单
     * 【ID1036616】 【野萃山】【万象&小助手】支持门店手动创建运单，通知骑手到店取餐
     * @param orderBean
     * @param request
     * @return
     */
    public BaseResponse createDelivery(OrderBeanV1 orderBean, OrderManagerRequest request, ConsoleResponseDTO<BizDTO> storeInfo,boolean idAutoCreate) {
        if (storeInfo == null || ObjectUtils.notEqual(ResponseResult.SUCCESS.getCode(), storeInfo.getStatusCode()) || storeInfo.getBizVO() == null || storeInfo.getBizVO().getStoreInfo() == null) {
            return ResponseUtil.error(ResponseResult.STORE_INFO_NOT_FOUND);
        }
        // 【ID1036616】 【野萃山】【万象&小助手】支持门店手动创建运单，通知骑手到店取餐
        BusinessInfoDTO businessInfo = storeInfo.getBizVO().getBusinessInfo();
        if (idAutoCreate && Objects.nonNull(businessInfo) && Objects.nonNull(businessInfo.getExpandFields())) {
            ExpandFieldsDTO expandFields = businessInfo.getExpandFields();
            String dispatchType = expandFields.getDispatchType();
            // 1. 手动派单
            if (Objects.equals(dispatchType, "1")) {
                ApiLog.printLog("oms 门店自动创建运单->", JSON.toJSONString(orderBean.getOid()),null,null);
                return ResponseUtil.success();
            }
        }
        if (!checkOrderOfDelivery(orderBean)) {
            return ResponseUtil.success();
        }
        // 调用配送系统创建配送单
        CreateDeliveryOrderRequestDto requestDto = deliverySdkAdapter.buildDeliveryOrderRequestDto(orderBean, storeInfo, deliveryCallBackUrl);
        CreateDeliveryOrderResponseDto deliveryResponse = deliveryService.deliveryOrderAdd(requestDto, LogThreadLocal.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, deliveryResponse == null ? "" : deliveryResponse.getMsg());
            return ResponseUtil.error(deliveryResponse == null ? "调用配送服务失败" : deliveryResponse.getMsg());
        }
        // 创建配送单成功
        orderBaseService.updateDeliverySuccess(orderBean.getOid(), deliveryResponse.getData().getDeliveryId(), operator);
        return ResponseUtil.success();
    }

    /**
     * 取消配送
     *
     * @param data
     * @param request
     * @return
     */
    public BaseResponse cancelDelivery(OrderBeanV1 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(OrderBeanV1 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);
            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(OrderBeanV1 orderBean) {
        //判断外卖单
        if (1 != orderBean.getType()) {
            return false;
        }
        //订单来源异常
        boolean sourceCheck = false;
        String[] supportSource = supportOrderSource.split(","); // OrderSourceType.SAAS.getCode()
        for (String source : supportSource){
            if (orderBean.getSource().equalsIgnoreCase(source)) {
                sourceCheck = true;
                break;
            }
        }
        if (!sourceCheck){
            return false;
        }
        //配送信息为空，则不创建配送单
        if (orderBean.getAddInfo() == null || orderBean.getAddInfo().getDeliveryType() == null) {
            return false;
        }
        //自配送不创建配送单
        if (delivery_type_self.equalsIgnoreCase(orderBean.getAddInfo().getDeliveryType())) {
            return false;
        }
        return true;
    }



}
