package com.hzs.third.mqcall.listener;

import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.enums.EBusinessType;
import com.hzs.common.core.service.RedisService;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.third.mq.dto.DelayedMessageDTO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DelayedMessageListener {

    @Autowired
    private RedisService redisService;

    @DubboReference
    ICountryServiceApi iCountryServiceApi;


    @RabbitListener(queues = {RabbitMqConstants.EFFECT_QUEUE_NAME})
    @RabbitHandler
    public void onMessage(Message<DelayedMessageDTO> message, Channel channel) throws Exception {
        // 手动ack
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
        DelayedMessageDTO delayedMessageDTO = message.getPayload();
        for (String key : delayedMessageDTO.getKeyList()) {
            redisService.deleteObjectByKey(key);
        }
        if (EBusinessType.REDIS_KEY.getValue() == delayedMessageDTO.getType()) {
            iCountryServiceApi.updateConfigEffectById(delayedMessageDTO.getBusinessType(), delayedMessageDTO.getPkId());
        }
    }
}
