package cn.freemud.management.service;

import cn.freemud.management.adapter.MessagePushAdapter;
import cn.freemud.management.enums.DeliveryStatus;
import cn.freemud.management.enums.OperateType;
import cn.freemud.management.enums.OrderSource;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.service.OrderServiceV1;
import com.freemud.application.sdk.api.structure.request.PushMessageNoticeDto;
import com.freemud.application.sdk.api.structure.service.MessageCenterClient;
import com.freemud.sdk.api.assortment.message.request.MessagePushOrderTemplateRequest;
import com.freemud.sdk.api.assortment.message.request.MessageTemplateRequest;
import com.freemud.sdk.api.assortment.message.service.IMessageTemplatePushService;
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.service.OrderCenterSdkService;
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.Qualifier;
import org.springframework.stereotype.Service;


@Service
public class OrderBaseService {

    private static final int SUCCESS = 100;

    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private MessageCenterClient messageCenterClient;
    @Autowired
    private MessagePushAdapter messagePushAdapter;
    @Autowired
    @Qualifier("messageTemplatePushOrderService")
    private IMessageTemplatePushService<MessagePushOrderTemplateRequest> messageTemplatePushService;

    @Autowired
    private OrderServiceV1 serviceV1;

    public OrderBeanV1 getByOrderCode(String orderCode) {
//        BaseQueryOrderRequest queryRequest = new BaseQueryOrderRequest();
//        queryRequest.setOrderId(orderCode);
//        QueryOrderByIdResponse response = orderCenterSdkService.queryOrderById(queryRequest);
//        if (ObjectUtils.notEqual(response.getErrcode(), SUCCESS) || response.getData() == null) {
//            return null;
//        }
//        return response.getData();
        String trackingNo =  LogThreadLocal.getTrackingNo();
        return serviceV1.queryOrderById(null,orderCode,null,null,trackingNo);
    }

    public void sendMessage(OrderBeanV1 orderBean, OperateType opType, String reason) {
        //发送消息到pos消息中心
        PushMessageNoticeDto pushMessageNoticeDto1 = null;
        try {
            pushMessageNoticeDto1 = messagePushAdapter.convent2PushMessageNoticeDto1(orderBean, opType);
            messageCenterClient.createMessage(pushMessageNoticeDto1, LogThreadLocal.getTrackingNo());
        } catch (Exception e) {
            ErrorLog.printErrorLog("sendMessageCenterError", "", pushMessageNoticeDto1, e);
        }
        //发送微信模板消息
        if (orderBean.getExtInfo() != null && !(OrderSource.SAAS.getSource().equals(orderBean.getSource()) || OrderSource.ALIPAY.getSource().equals(orderBean.getSource()))) {
            return;
        }
        MessageTemplateRequest<MessagePushOrderTemplateRequest> messageTemplateRequest = null;
        try {
            messageTemplateRequest = messagePushAdapter.convent2MessageTemplateRequest(orderBean, reason, opType);
            if (messageTemplateRequest!=null && messageTemplateRequest.getMessageEventType() != null) {
                BaseResponse baseResponse = messageTemplatePushService.sendTemplateMsg(messageTemplateRequest);
                if(baseResponse != null && !ResponseResultEnum.SUCCESS.getCode().equals(baseResponse.getCode())){
                    ApiLog.printLog("sendTemplateMsg",orderBean.getOid(), JSONObject.toJSONString(baseResponse),null);
                }
            }
        } catch (Exception e) {
            ErrorLog.printErrorLog("sendTemplateMsgError", "", messageTemplateRequest, e);
        }


    }

    /**
     * 创建配送单一车 -> 更新订单为异常单
     *
     * @param partnerId
     * @param orderCode
     * @param deliveryId
     */
    public void updateDeliveryAbnormal(String partnerId, String orderCode, String deliveryId, String operator,String msg) {
        AssortmentUpdateDeliveryAbnormalRequest request = AssortmentUpdateDeliveryAbnormalRequest.builder()
                .abnormalDesc("配送异常"+ msg)
                .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);
        updateDeliveryInfoByIdRequest.setRemark("创建运单成功");
        orderCenterSdkService.updateDeliveryInfoById(updateDeliveryInfoByIdRequest);
    }
}
