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.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
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.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

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

    @Resource
    private RocketMQTemplate deliveryRocketMqTemplate;

    /**
     * @Description 发现配送信息到rabbitMQ
     * @param deliveryRequest
     */
    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);
        mqService.convertAndSend(PushOrderConfig.EXCHANGE_NAME, PushOrderConfig.OPEN_PLATFORM_ORDER_DELIVERY_ROUTING_KEY, mqMessage);
    }

    /**
     * @Description 发送配送信息到rocketMq:
     * @param deliveryRequest
     */
    public void sendRocketMqOfDeliveryInfo(CallbackUrlRequestDto deliveryRequest) {
        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.info("sendDelivery of status:{}, message:{},", sendResult.toString(), JSON.toJSONString(message));
        } catch (Exception e) {
            log.error("sendDelivery.error, message:{}, cause:{}", JSON.toJSONString(message), Throwables.getStackTraceAsString(e));
        }
    }
}
