package com.sw.mes.config.rabbit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * @author zhaowenjie
 */
//@Component
@Slf4j
public class InspectDataMsgProducer implements ConfirmCallback, ReturnCallback {
    /**
     * 由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public InspectDataMsgProducer(RabbitTemplate rabbitTemplate) {
        // rabbitTemplate如果为单例的话，那回调就是最后设置的内容
        /**
         * ConfirmCallback接口用于实现消息发送到RabbitMQ交换器后接收ack回调。
         * ReturnCallback接口用于实现消息发送到RabbitMQ交换器，但无相应队列与交换器绑定时的回调。
         */
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
        this.rabbitTemplate = rabbitTemplate;
    }

    private MessagePostProcessor correlationIdProcessor;

    @Autowired
    public void setCorrelationIdProcessor() {
        this.correlationIdProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message, Correlation correlation) {
                MessageProperties messageProperties = message.getMessageProperties();

                if (correlation instanceof CorrelationData) {
                    String correlationId = ((CorrelationData) correlation).getId();
                    messageProperties.setCorrelationId(correlationId);
                }
                return message;
            }

            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                return message;
            }
        };
    }

    /**
     * 发送检验数据队列
     *
     * @param inspectDataJson 检验数据
     */
    public void sendMsgInspectData(String inspectDataJson) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        /**
         * 确保消息发送失败后可以重新返回到队列中
         * 注意：yml需要配置 publisher-returns: true
         */
        rabbitTemplate.setMandatory(true);
        /**
         * 消费者确认收到消息后，手动ack回执回调处理
         */
        rabbitTemplate.setConfirmCallback(this);

        /**
         * 消息投递到队列失败回调处理
         */
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend(RabbitConfig.INSPECT_DATA_EXCHANGE, RabbitConfig.INSPECT_DATA, inspectDataJson, correlationIdProcessor, correlationId);
    }

    /**
     * SPC发送检验数据队列
     *
     * @param inspectDataJson 检验数据
     */
    public void sendSpcMsgInspectData(String inspectDataJson) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        /**
         * 确保消息发送失败后可以重新返回到队列中
         * 注意：yml需要配置 publisher-returns: true
         */
        rabbitTemplate.setMandatory(true);
        /**
         * 消费者确认收到消息后，手动ack回执回调处理
         */
        rabbitTemplate.setConfirmCallback(this);

        /**
         * 消息投递到队列失败回调处理
         */
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_SPC_SIX_YB_PRODUCT_INSPECT, RabbitConfig.KEY_SIX_SPC_PRODUCT_INSPECT, inspectDataJson, correlationIdProcessor, correlationId);
    }

    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("MQ消息发送成功，回调id:" + correlationData);
        } else {
            log.error("MQ消息发送失败，回调id:" + correlationData);
//            SysErrorLog sysErrorLog = new SysErrorLog();
//            sysErrorLog.setType(EnumValues.SysErrorLogType.发送MQ数据异常.getKey());
//            sysErrorLog.setTitle("发送MQ数据异常");
//            sysErrorLog.setContent("MQ消息发送失败，回调id:" + correlationData + "，错误信息：" + cause);
//            sysErrorLog.setCreateTime(new Date());
//            sysErrorLogService.insertSelective(sysErrorLog);
        }
    }

    /**
     * 发送错误
     *
     * @param message
     * @param replyCode
     * @param replyText
     * @param exchange
     * @param routingKey
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println(message.getMessageProperties().getCorrelationId() + " 发送失败");
        System.out.println("消息主体 message : " + message);
        System.out.println("消息主体 message : " + replyCode);
        System.out.println("描述：" + replyText);
        System.out.println("消息使用的交换器 exchange : " + exchange);
        System.out.println("消息使用的路由键 routing : " + routingKey);
    }
}
