package com.sw.mes.syslog.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.sw.mes.syslog.constant.RabbitCommon;
import com.sw.mes.syslog.domain.SysLog;
import com.sw.mes.syslog.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@RabbitListener(queues = RabbitCommon.SYS_LOG_QUEUE)
@Slf4j
public class SystemLoggerListener {
    @Autowired
    private SysLogService sysLogService;

    @RabbitHandler
    public void handlerSystemLog(String messageStr, Message message, Channel channel) {
        try {
            if (!StringUtils.isBlank(messageStr)){
                SysLog sysLog =  JSONObject.parseObject(messageStr, SysLog.class);
                sysLogService.saveOrUpdate(sysLog);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
