package cn.freemud.amp.service;

import cn.freemud.amp.config.PushOrderConfig;
import cn.freemud.amqp.Header;
import cn.freemud.amqp.MQAction;
import cn.freemud.amqp.MQMessage;
import cn.freemud.amqp.MQService;
import cn.freemud.constant.RocketMQConst;
import cn.freemud.entities.dto.delivery.CallbackUrlRequestDto;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.log.ApiLog;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * mq发送方
 */
@Service
public class ProduceMQService {
    @Autowired
    private MQService mqService;

    @Resource
    private RocketMQTemplate deliveryRocketMqTemplate;

    @Value("${rocketmq.delivery.enable:false}")
    private Boolean rocketMQDeliveryEnable;

    /**
     * @param deliveryRequest
     * @Description 发现配送信息到rabbitMQ
     */
    public void sendOfDeliveryInfo(CallbackUrlRequestDto deliveryRequest) {
        Header header = new Header(MQAction.UPDATE.getAction(), "delivery/callbackUrl", deliveryRequest.getOrderId(), "open-platform-order-delivery-queue");
        MQMessage<CallbackUrlRequestDto> mqMessage = new MQMessage<>(header, deliveryRequest);
        try {
            mqService.convertAndSend(PushOrderConfig.EXCHANGE_NAME, PushOrderConfig.OPEN_PLATFORM_ORDER_DELIVERY_ROUTING_KEY, mqMessage);
        } catch (Exception e) {
            ErrorLog.printErrorLog("sendOfDeliveryInfo.error","delivery/callbackUrl",deliveryRequest,e);
//            log.error("sendOfDeliveryInfo.error, message:{}, cause:{}", JSON.toJSONString(deliveryRequest), Throwables.getStackTraceAsString(e));
        }
    }

    /**
     * @param deliveryRequest
     * @Description 发送配送信息到rocketMq:
     */
    public void sendRocketMqOfDeliveryInfo(CallbackUrlRequestDto deliveryRequest) {

        if (BooleanUtils.isNotTrue(rocketMQDeliveryEnable)) {
            return;
        }

        Header header = new Header(MQAction.UPDATE.getAction(), "delivery/callbackUrl", deliveryRequest.getOrderId(), RocketMQConst.ORDER_THIRD_PUSH_TOPIC);
        MQMessage<CallbackUrlRequestDto> mqMessage = new MQMessage(header, deliveryRequest);
        String destination = String.format("%s:%s", RocketMQConst.ORDER_THIRD_PUSH_TOPIC, RocketMQConst.OrderSubsidiaryTag.delivery);
        Message message = MessageBuilder
                .withPayload(mqMessage)
                .setHeader("partnerId", deliveryRequest.getPartnerId())
                .setHeader(MessageConst.PROPERTY_KEYS, deliveryRequest.getDeliveryId())
                .build();

        try {
            SendResult sendResult = deliveryRocketMqTemplate.syncSendOrderly(destination, message, deliveryRequest.getOrderId());
//            log.debug("sendDelivery of status:{}, message:{},", sendResult.toString(), JSON.toJSONString(message));
        } catch (Exception e) {
            ErrorLog.printErrorLog("sendDelivery.error","delivery/callbackUrl",message,e);
//            log.error("sendDelivery.error, message:{}, cause:{}", JSON.toJSONString(message), Throwables.getStackTraceAsString(e));
        }
    }
}
