package com.skr.mdm.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.skr.mdm.bean.dto.UserLoginCallbackDTO;
import com.skr.mdm.constant.RabbitmqQueueConstants;
import com.skr.mdm.publish.MdmEventPublisher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author nfq
 * @date 2020/11/25 11:51
 */
@Component
@RabbitListener(queues = RabbitmqQueueConstants.REGISTER_SUCCESS_QUEUE)
@Slf4j
public class UserLoginCallbackConsumer {

    @Autowired
    private MdmEventPublisher mdmEventPublisher;

    @RabbitHandler
    public void handle(UserLoginCallbackDTO userLoginCallbackDTO, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(deliveryTag, false);
            if (CollectionUtils.isEmpty(userLoginCallbackDTO.getDeviceIdList()) || userLoginCallbackDTO.getCompanyId() == null) {
                return;
            }
            mdmEventPublisher.publishEvent(userLoginCallbackDTO.getDeviceIdList().get(0),
                    userLoginCallbackDTO.getCompanyId(), userLoginCallbackDTO.getDepartmentId());
        } catch (Exception e) {
            channel.basicAck(deliveryTag, false);
            log.error("rabbitmq接收用户激活信息异常：" + JSONUtil.toJsonStr(userLoginCallbackDTO), e);
        }
    }
}
