package com.bwie.auth.consumer;

import com.bwie.common.result.Result;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName LongSuccessConsumer
 * @Description TODO
 * @Created by 杨鹏
 */
@Component
@Log4j2
public class LongSuccessConsumer {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queuesToDeclare = @Queue(name = "longSuccess"))
    public void longSuccessConsumer(Integer userId, Message message, Channel channel) {
        String messageId = message.getMessageProperties().getMessageId();
        try {
            //直接添加到redis 的set 集合中
            Long count = redisTemplate.opsForSet().add("登录成功", messageId);
            if (count==1){
                log.info("接受到消息,消息内容为:{}",userId);
                try{
                    //TODO 记录成功日志
                    //Result code = authService.getCode(userPhone);
                    log.info("记录成功日志");
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }catch (Exception e){
                    e.printStackTrace();
                    //执行消息重试方法
                    log.info("执行失败");
//                    redisTemplate.opsForValue().set(messageId,"messageId");
                }
            }
            //消息不重复
        }catch (Exception e){
            redisTemplate.opsForSet().remove("登录失败",messageId);
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }

    }
}
