package com.sunda.spmsweb.aspect;

import com.sunda.spmscommon.entity.SysLog;
import com.sunda.spmscommon.service.ISysLogService;
import com.sunda.spmsweb.util.IPUtils;
import com.sunda.spmsweb.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @program: spms
 * @description: operation aspect
 * @author: Wayne Wu
 * @create: 2020-12-16 16:20
 **/
@Aspect
@Component
public class OperationAspect {

    @Autowired
    ISysLogService iSysLogService;

    @Pointcut("@annotation(com.sunda.spmsweb.aspect.Operation)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLog(point, time);
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        HttpServletResponse response;

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SysLog sysLog = new SysLog();
        sysLog.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
        Method method = signature.getMethod();

        //日志类型 1操作；2登录；
        sysLog.setLogType("1");

        // 获取注解上的描述
        Operation logAnnotation = method.getAnnotation(Operation.class);
        if (logAnnotation != null) {
            sysLog.setLogContent(logAnnotation.logContent());
            sysLog.setOperateType(logAnnotation.operateType());
        }

        //请求路径
        String path = request.getRequestURI();
        sysLog.setRequestUrl(path);

        // 根据系统 token 获取用户工号
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        sysLog.setUserId(userId);

        // 设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        // 请求的方法参数值
        if ("POST".equals(request.getMethod().toUpperCase())){
            Object[] args = joinPoint.getArgs();
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] paramNames = u.getParameterNames(method);
            if (args != null && paramNames != null) {
                String params = "";
                for (int i = 0; i < args.length; i++) {
                    params += "  " + paramNames[i] + ": " + args[i];
                }
                sysLog.setRequestParam(params);
            }
        }else if ("GET".equals(request.getMethod().toUpperCase())) {
            sysLog.setRequestParam(request.getQueryString());
        }

        // 设置 http 请求类型
        sysLog.setRequestType(request.getMethod());

        // 设置程序执行耗时
        sysLog.setCostTime(time);

        //System.out.println("sysLog ===== " + sysLog.toString());
        // 保存系统日志
        iSysLogService.insertSysLog(sysLog);
    }
}
