package com.foreverwin.mesnac.common.aspect;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.util.IPUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.TextMessage;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.UUID;

@Aspect
@Component
@ConditionalOnProperty(prefix = "spring", name = "activemq.brokerUrl")
public class MessageLogAspect {

    private Logger logger = LoggerFactory.getLogger(MessageLogAspect.class);

    @Autowired
    JmsMessagingTemplate jmsTemplate;

    @Value("${spring.activemq.brokerUrl}")
    String brokerURL;

    @Pointcut("@annotation(com.foreverwin.modular.core.annotation.MessageLog)")
    public void messageLog() {
    }

    /*@AfterReturning(pointcut = "messageLog()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    @AfterThrowing(pointcut = "messageLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }*/

    /*public void handleLog(JoinPoint joinPoint, Exception e ){

        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        JmsListener jmsListener = methodSignature.getMethod().getAnnotation( JmsListener.class );

        String queueName = jmsListener.destination();
        String messageBody = "";
        if (args[0] instanceof TextMessage) {
            try {
                messageBody = ((TextMessage) args[0]).getText();
            } catch (JMSException jmsException) {
                logger.error(jmsException.getLocalizedMessage(), jmsException);
            }
        } else {
            messageBody = (String) args[0];
        }


        //logger.info( "接收到信息: " + messageBody );

        JSONObject map = JSONObject.parseObject( messageBody );
        String site = map.getString( "SITE" );
        if(StrUtil.isBlank(site)){
            site = map.getString( "site" );
        }
        String ip = IPUtil.getIp();
        String result = null;
        String errorMsg = null;
        if( e == null ){
            result = "Y";
            //logger.info( "信息处理完成: " + messageBody );
        }else{
            result = "N";
            errorMsg = e.getMessage();
            //logger.info( "信息处理失败: " + errorMsg + ",信息：" + messageBody );
        }

        EapLog eapLog = new EapLog();
        eapLog.setHandle(UUID.randomUUID().toString() );
        eapLog.setSite( site );
        eapLog.setBrokeUrl( brokerURL );
        eapLog.setQueueName( queueName );
        eapLog.setMessageBody( messageBody != null && messageBody.length() > 2000 ? messageBody.substring( 0, 2000 ) : messageBody );
        eapLog.setResult( result );
        eapLog.setErrorMsg( errorMsg != null && errorMsg.length() > 2000 ? errorMsg.substring( 0, 2000 ) : errorMsg );
        eapLog.setServerIp( ip );
        eapLog.setCreatedDateTime(LocalDateTime.now());
        eapLogService.save(eapLog);
    }*/


    @Around("messageLog()")
    public Object handleLog(ProceedingJoinPoint joinPoint) {
        LocalDateTime startDate = LocalDateTime.now();

        String errorMsg = null;
        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            errorMsg = e.getMessage();
        } catch (Throwable throwable) {
            errorMsg = throwable.getMessage();
        } finally {
            LocalDateTime endDate = LocalDateTime.now();
            Duration duration = Duration.between(startDate, endDate);
            long runTime = duration.toMillis();

            Object[] args = joinPoint.getArgs();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            JmsListener jmsListener = methodSignature.getMethod().getAnnotation(JmsListener.class);

            String queueName = jmsListener.destination();
            String messageBody = "";
            if (args[0] instanceof TextMessage) {
                try {
                    messageBody = ((TextMessage) args[0]).getText();
                } catch (JMSException jmsException) {
                    logger.error(jmsException.getLocalizedMessage(), jmsException);
                }
            } else {
                messageBody = (String) args[0];
            }

            JSONObject map = JSONObject.parseObject(messageBody);
            String site = map.getString("SITE");
            if (StrUtil.isBlank(site)) {
                site = map.getString("site");
            }
            String ip = IPUtil.getIp();
            String result = null;
            if (StrUtil.isBlank(errorMsg)) {
                result = "Y";
            } else {
                result = "N";
            }
        }

        return null;
    }
}
