package com.dxhy.common.aspect;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.common.util.redis.UserAuthConfiguration;
import com.dxhy.common.utils.BaseContextHandler;
import com.dxhy.common.utils.HttpContextUtils;
import com.dxhy.common.utils.IPUtils;
import com.dxhy.common.vo.SysLogVo;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author jiaohongyang
 */
@Aspect
@Component
@Slf4j
@SuppressWarnings("AlibabaUndefineMagicConstant")
public class SysLogAspect {
    @Resource
    private RabbitMqSender rabbitLogsSender;
    @Resource
    private UserAuthConfiguration userAuthConfiguration;

    @Pointcut("@annotation(com.dxhy.common.aspect.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        // 保存日志
        saveSysLog(point, time);

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        SysLogVo sysLog = new SysLogVo();
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog syslog = method.getAnnotation(SysLog.class);
        if (syslog != null) {
            // 注解上的描述
            sysLog.setOperation(syslog.value());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        sysLog.setMethod(className + "." + methodName + "()");
        sysLog.setUrl(request.getServletPath());
        // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            if (args != null && args.length > 0) {
                String params = JSON.toJSONString(args[0], SerializerFeature.IgnoreErrorGetter);
                sysLog.setParams(params);
            }
            // 设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
            // 用户名
            sysLog.setTime(time);
            sysLog.setCreateDate(new Date());
            sysLog.setUsername(BaseContextHandler.getUsername());
            sysLog.setUserId(BaseContextHandler.getUserID());

            // 将数据存储到mq里面 使用消费者进项消费
            String json = JSON.toJSONString(sysLog);
            rabbitLogsSender.sendSaveLogs(Base64.encode(json.getBytes()));
        } catch (Exception e) {
            log.debug("生成日志异常---{}",e);
        }

    }

}
