package com.education.business.message;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.education.business.service.system.SystemMessageLogService;
import com.education.common.enums.MqMessageStatusEnum;
import com.education.model.entity.MessageLog;
import com.jfinal.json.Jackson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;


/**
 * 消息消费失败回调
 * @Auther: zjt
 * @Date: 2019/11/20 16:06
 * @Version: 1.0.3
 */
@Component
public class RabbitReturnCallback implements RabbitTemplate.ReturnsCallback {

    @Resource
    private SystemMessageLogService systemMessageLogService;

    private static final Logger logger = LoggerFactory.getLogger(RabbitReturnCallback.class);


    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        logger.warn("消息主体: {}", returnedMessage.getMessage());
        logger.warn("回复编码: {}", returnedMessage.getReplyCode());
        logger.warn("回复内容: {}", returnedMessage.getReplyText());
        logger.warn("交换器: {}", returnedMessage.getExchange());
        logger.warn("路由键: {}", returnedMessage.getRoutingKey());

        Map result = new Jackson().parse(new String(returnedMessage.getMessage().getBody()), Map.class);
        String cause = "{回复编码:" + returnedMessage.getReplyCode() + ", 回复内容: " + returnedMessage.getReplyText();
        LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<MessageLog>()
                .set(MessageLog::getStatus,  MqMessageStatusEnum.CONSUME_FAIL.getCode())
                .set(MessageLog::getConsumeCause, cause)
                .eq(MessageLog::getCorrelationDataId, result.get("messageId"));
        systemMessageLogService.update(updateWrapper);
    }
}
