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

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.xhx.base.framework.ws.message.Message;
import com.mortals.xhx.common.key.QueueKey;
import com.mortals.xhx.module.access.model.AccessLogEntity;
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 org.springframework.util.ObjectUtils;

import java.util.*;
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(List<byte[]> messages) {
        log.info("[Oper onMessage][线程编号:{} 消息数量：{}]", Thread.currentThread().getName() + Thread.currentThread().getId(), messages.size());
        List<OperateLogEntity> collect = messages.stream().map(str -> {
            OperateLogEntity entity = JSON.parseObject(new String(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);
    }*/

    @RabbitHandler
    public void onMessage(List<OperateLogEntity> messages) {
        log.info("[Oper onMessage][消息数量：{}]", messages.size());
        List<OperateLogEntity> collect = messages.stream().map(entity -> {
            //OperateLogEntity entity = JSON.parseObject(new String(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);
    }
}
