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

import com.alibaba.fastjson.JSON;
import com.mortals.xhx.common.key.QueueKey;
import com.mortals.xhx.module.access.model.AccessLogEntity;
import com.mortals.xhx.module.biz.model.BizLogEntity;
import com.mortals.xhx.module.biz.service.BizLogService;
import com.mortals.xhx.module.error.model.ErrorLogEntity;
import com.mortals.xhx.module.error.model.ErrorLogQuery;
import com.mortals.xhx.module.error.service.ErrorLogService;
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.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.nio.charset.Charset;
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.ERROR_LOG_QUEUE,
        containerFactory = "consumerBatchContainerFactory")
public class ErrorMessageConsumerListener {

    @Autowired
    private ErrorLogService errorLogService;

    @RabbitHandler
    public void onMessage(List<ErrorLogEntity> messages) {
        log.info("[Error onMessage][消息数量：{}]", messages.size());
        messages.stream().peek(entity -> {
            entity.setCreateUserId(1L);
            entity.setCreateTime(new Date());
            if (!ObjectUtils.isEmpty(entity.getFingerprint())) {
                //// TODO: 2022/8/24 指纹匹配
            }
            //比较message platform appname 如果相同 则checknum+1 并更新日志时间
           /* ErrorLogQuery errorLogQuery = new ErrorLogQuery();
            errorLogQuery.setAppName(entity.getAppName());
            errorLogQuery.setPlatform(entity.getPlatform());
            errorLogQuery.setErrorStack(entity.getErrorStack());
            ErrorLogEntity errorLogEntity = errorLogService.selectOne(errorLogQuery, null);
            if (!ObjectUtils.isEmpty(errorLogEntity)) {
                errorLogEntity.setCheckNum(errorLogEntity.getCheckNum() + 1);
                errorLogEntity.setLogTime(entity.getLogTime());
                errorLogEntity.setThreadNo(entity.getThreadNo());
                errorLogEntity.setCreateTime(new Date());
                errorLogEntity.setUpdateTime(new Date());
                errorLogService.update(errorLogEntity);
            } else {
                errorLogService.save(entity);
            }*/


          //  errorLogService.save(entity);
        }).count();
    }
}
