package com.heyu.api.job.api.listener;

import com.alibaba.fastjson.JSON;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.dto.CalcaAccountLogDTO;
import com.heyu.api.data.service.calca.CalcaAccountLogService;
import com.heyu.api.data.utils.OrderUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
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.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class LogQueueSimpleRabbitListener {

    @Value("${eb.config.rabbitQueue.accountLogName}")
    private String accountLogNameQueue;


    @Autowired
    private CalcaAccountLogService calcaAccountLogService;


    @RabbitHandler
    @RabbitListener(queues = "#{accountLogNameQueue.name}", containerFactory = "accountLogNameQueueSimpleRabbitListenerContainerFactory")
    public void consumeMessage(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long delivertTag, Channel channel) {
        String userName = "";
        try {
            log.info("accountLogNameQueue请求参数是message :{}", message);
            CalcaAccountLogDTO calcaAccountLogDTO = JSON.parseObject(message, CalcaAccountLogDTO.class);
            String newTraceId = calcaAccountLogDTO.getTraceId() + "_" + OrderUtil.getUserPoolOrder("on");
            MDC.put(ApiConstants.TRACE_ID, newTraceId);
            calcaAccountLogService.insertCalcaAccountLog(calcaAccountLogDTO.getCalcaAccountLogEntity());
        } catch (Exception e) {
            log.error("accountLogNameQueue handle", e);
        } finally {
            try {
                log.info("accountLogNameQueue消息{},消息确认完成", message + ",username : " + userName);
                channel.basicAck(delivertTag, true);
            } catch (IOException e) {
                log.error("accountLogNameQueue消息确认异常", e);
            }
        }
    }
}