package com.muyu.processing.consumer;

import com.muyu.domain.Fence;
import com.muyu.domain.Vehicle;
import com.muyu.domain.WarnRule;
import com.muyu.domain.WarnStrategy;
import com.muyu.enterprise.cache.*;
import com.muyu.processing.utils.CacheUtil;
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.stereotype.Component;

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

/**
 * 上线监听
 * @Author：杨鹏
 * @Package：com.muyu.processing.consumer
 * @Project：car-cloud-server
 * @name：MQconsumer
 * @Date：2024/9/29 17:19
 */
@Log4j2
@Component
public class OnLineMonitoringConsumer {

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private VehicleCacheService vehicleCacheService;

    @Resource
    private FaultCacheService faultCacheService;

    @Resource
    private FenceCahceService fenceCahceService;

    @Resource
    private WarnRuleCacheService warnRuleCacheService;

    @Resource
    private WarnStrategyCacheService warnStrategyCacheService;

    /**
     * 上线监听车辆网关中车辆上线时
     */
    @RabbitListener(queuesToDeclare = @Queue("long_time_no_see"))
    public void receive(String vin, Message message, Channel channel){

        try {
            log.info("添加本地缓存,车辆vin: {}", vin);
            WarnRule warnRule = warnRuleCacheService.get(vin);
            WarnStrategy warnStrategy = warnStrategyCacheService.get(vin);
            Vehicle vehicle = vehicleCacheService.get(vin);
            Object breakdown = faultCacheService.get(vin);
            Fence fence = fenceCahceService.get(vin);
            HashMap<String, Object> map = new HashMap<>();
            map.put("warnRule",warnRule);
            map.put("warnStrategy",warnStrategy);
            map.put("vehicle",vehicle);
            map.put("breakdown",breakdown);
            map.put("fence",fence);
            cacheUtil.put(vin,map);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }

    }

}
