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.enums.EDelayBusType;
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;

/**
 * @Description:
 * @Author: sui q
 * @Time: 2023/3/9 16:02
 * @Classname: DelayedMessageListener
 * @PackageName: com.hzs.third.mqcall.listener
 */
@Slf4j
@Component
public class DelayedMessageListener {

    private RedisService redisService;

    @DubboReference
    private ICountryServiceApi countryServiceApi;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    @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()){
            countryServiceApi.updateConfigEffectById(delayedMessageDTO.getBusinessType(), delayedMessageDTO.getPkId());
        }else{
            // todo 处理订单
        }
        log.info("###########################################");
    }
}
