package com.diagbot.aop;

import com.diagbot.annotation.SysLogger;
import com.diagbot.entity.SysLog;
import com.diagbot.enums.SysTypeEnum;
import com.diagbot.rabbit.MySender;
import com.diagbot.util.GsonUtil;
import com.diagbot.util.HttpUtils;
import com.diagbot.util.StringUtil;
import com.diagbot.util.UserUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description: 日志拦截切面
 * @author: gaodm
 * @time: 2018/8/2 13:36
 */
@Aspect
@Component
public class SysLoggerAspect {
    @Autowired
    private MySender mySender;

    @Pointcut("@annotation(com.diagbot.annotation.SysLogger)")
    public void loggerPointCut() {

    }

    @Before("loggerPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
        SysLogger sysLogger = method.getAnnotation(SysLogger.class);
        if(sysLogger != null){
            //注解上的描述
            sysLog.setOperation(sysLogger.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params="";
        for(Object o:args){
            params+=GsonUtil.toJson(o);
        }
        if(!StringUtil.isEmpty(params)) {
            sysLog.setParams(params);
        }
        //设置IP地址
        sysLog.setIp(HttpUtils.getIpAddress());
        //用户名
        String username = UserUtils.getCurrentPrinciple();
        if(!StringUtil.isEmpty(username)) {
            sysLog.setUsername(username);
        }
        sysLog.setGmtCreate(new Date());
        sysLog.setSysType(SysTypeEnum.BI_SERVICE.getKey());
        //保存系统日志
        mySender.outputLogSend(sysLog);
    }

}

