package com.hdkj.lt.mq.service.base.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hdkj.lt.base.constants.RedisKeyConstants;
import com.hdkj.lt.base.constants.RocketMQConstants;
import com.hdkj.lt.core.bizms.modle.po.MessageRetryLog;
import com.hdkj.lt.core.mq.client.RocketMQTemplate;
import com.hdkj.lt.core.mq.config.RocketMQProperties;
import com.hdkj.lt.core.mq.model.RocketMQMessageEntity;
import com.hdkj.lt.mq.mapper.base.MessageRetryLogMapper;
import com.hdkj.lt.mq.service.base.MessageRetryLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author userlrk
 * @description 针对表【message_retry_log(MQ异常重试表)】的数据库操作Service实现
 * @createDate 2025-06-23 15:33:02
 */
@Service
public class MessageRetryLogServiceImpl extends ServiceImpl<MessageRetryLogMapper, MessageRetryLog>
        implements MessageRetryLogService {
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @Autowired
    RocketMQProperties rocketMQProperties;
    @Autowired
    MessageRetryLogMapper mapper;

    @Override
    public MessageRetryLog sendByMsgId(String messageId) {
        MessageRetryLog messageRetryLog = mapper.getByMessageId(messageId);
        //重启MQ请求
        if (rocketMQProperties.getEnabled()) {
            RocketMQMessageEntity messageEntity = RocketMQMessageEntity.builder()
                    .topicId(messageRetryLog.getMessageId())
                    .cacheKey(RedisKeyConstants.ASYNC_QUEUE_ANALYSIS_TRANSFER_RESULT_TICKET)
                    .tag(messageRetryLog.getTag()) // 1-计划停电，2-故障停电
                    .body(messageRetryLog.getMessageBody()).build();
            rocketMQTemplate.sendAsyncMessage(messageEntity);
        }
        return messageRetryLog;
    }

    /**
     * 保存异常信息
     *
     * @param messageRetryLog
     */
    @Override
    public void saveLog(MessageRetryLog messageRetryLog) {
        MessageRetryLog retryLog = mapper.getByMessageId(messageRetryLog.getMessageBody());
        if (retryLog != null) {
            messageRetryLog.setRetryCount(retryLog.getRetryCount() + 1);
            messageRetryLog.setId(retryLog.getId());
        }
        this.saveOrUpdate(messageRetryLog);
    }
}




