package com.mortals.xhx.base.framework.listener;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.xhx.common.key.QueueKey;
import com.mortals.xhx.module.error.model.ErrorLogEntity;
import com.mortals.xhx.module.error.service.ErrorLogService;
import com.mortals.xhx.module.operate.model.OperateLogEntity;
import com.mortals.xhx.module.operate.service.OperateLogService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
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.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * rabbitmq 操作日志消息消费类
 *
 * @author: zxfei
 * @date: 2022/8/17 20:45
 * @description:
 **/
@Slf4j
@Component
@RabbitListener(queues = QueueKey.OPERATION_LOG_QUEUE,
        containerFactory = "consumerBatchContainerFactory")
public class OperateMessageConsumerListener {

    @Autowired
    private OperateLogService operateLogService;

    @RabbitHandler
    public void onMessage(@Payload List<String> messages, Channel channel) throws Exception {
        log.info("[OperateLog onMessage][线程编号:{} 消息数量：{}]", Thread.currentThread().getId(), messages.size());

        List<OperateLogEntity> collect = messages.stream().map(str -> {
            OperateLogEntity entity = JSON.parseObject(str, OperateLogEntity.class);
            entity.setId(IdUtil.getSnowflake(0, 1).nextId());
            entity.setCreateUserId(1L);
            entity.setCreateTime(new Date());
            return entity;
        }).collect(Collectors.toList());
        operateLogService.save(collect);
    }
}
