package com.artfess.application.jms;

import com.artfess.base.constants.JmsConstant;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.ExceptionUtil;
import com.artfess.base.util.JsonUtil;
import com.artfess.sysConfig.service.SysLogsBatchService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.TextMessage;

@Service
@ConditionalOnProperty(value="jms.enable", matchIfMissing = true)
public class JmsSysLogConsumer {
	private static final Logger logger = LoggerFactory.getLogger(JmsSysLogConsumer.class);
	@Resource
    SysLogsBatchService sysLogsBatchService;
	

	@JmsListener(destination = JmsConstant.SYS_LOG_QUEUE, containerFactory="jmsListenerContainerQueue")
	public void receiveQueue(Object model) {
		logger.debug("[JMS]: queue message is :"+model.getClass().getName()+"---"+model);
		handlerSysLog(model);
	}

	private void handlerSysLog(Object source) {
		if(BeanUtils.isEmpty(source) || !(source instanceof TextMessage)) return;

		TextMessage textMsg = (TextMessage)source;
		try {
			String text = textMsg.getText();
			JsonNode jsonNode = JsonUtil.toJsonNode(text);
			if(BeanUtils.isNotEmpty(jsonNode) && jsonNode.isObject()) {
				ObjectNode objectNode = (ObjectNode)jsonNode;
				String type = JsonUtil.getString(objectNode, "type");
				//保存操作日志
				if("sysLog".equals(type)) {
					sysLogsBatchService.reader(objectNode);
					logger.debug("操作日志: " + JsonUtil.toJsonString(objectNode));
				}
			}
		} catch (Exception e) {
			logger.error( ExceptionUtil.getExceptionMessage(e) );
		}
	}
}
