package com.muyu.data.processing.rebbit;


import com.muyu.common.caffeine.utils.CacheUtils;
import com.muyu.common.rabbit.config.RabbitmqConfig;
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: 胡杨
 * @Name: DownlineRabbitConsumer
 * @Description: 车辆下线监听器
 * @CreatedDate: 2024/9/26 下午8:21
 * @FilePath: com.muyu.data.processing.rebbit
 */
@Slf4j
@Component
@Setter
public class DownlineRabbitConsumer {
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private CacheUtils cacheUtils;

    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_SEND})
    public void downline(String vin, Message message, Channel channel) {
        log.info("车辆 {} 下线, 配置信息准备中。。。",vin);
        try {
            deleteCarCache(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) {
        cacheUtils.delCacheValueAll(vin);
        log.info("车辆编码:{},本地缓存删除完成...", vin);
    }
}
