package com.muyu.data.rabbit;


import com.muyu.common.rabbit.constants.RabbitConstants;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 下线事件监听
 * @Author: WangXin
 * @Description: 车辆下线监听器
 */
@Slf4j
@Component
@Setter
public class DownlineRabbitConsumer {
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private CacheManager cacheManager;

    @RabbitListener(queuesToDeclare = {@Queue(RabbitConstants.DOWN_LINE_QUEUE)})
    public void downline(String vin, Message message, Channel channel) {
        log.info("车辆 {} 下线, 配置信息准备中。。。",vin);
        try {
            // 重复性校验
            Long add = redisTemplate.opsForSet().add(RabbitConstants.DOWN_LINE_QUEUE, message.getMessageProperties().getMessageId());
            if (add>0) {
                deleteCarCache(vin);
                log.info("车辆 {} 下线, 消息已确认。。。",vin);
            } else {
                log.info("车辆 {} 下线, 消息重复消费，已确认。。。",vin);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("车辆 {} 下线, 配置信息已准备完毕。。。",vin);
        } catch (IOException e) {
            try {
                log.warn("车辆 {} 下线, 配置信息准备失败，返回队列，原因：{}", vin, e.getMessage());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                log.warn("车辆 {} 下线, 消息返回队列失败，原因：{}", vin, ex.getMessage());
            }
        }
    }


    /**
     * 车辆下线 - 删除缓存
     */
    public void deleteCarCache(String vin) {
        Cache cache = cacheManager.getCache(vin);
        if (ObjectUtils.isNotEmpty(cache)){
            cache.invalidate();
        }
        log.info("车辆编码:{},本地缓存删除完成...", vin);
    }
}
