package com.app.aspect.platform;

import cn.hutool.json.JSONUtil;
import com.app.mapper.platform.OperationLogMapper;
import com.app.service.platform.auth.AccountService;
import com.app.service.platform.monitor.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
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.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 功能描述：
 *
 * @Author 梁展鹏
 */
@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private AccountService accountService;

    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private OperationLogMapper mapper;

    private ThreadLocal<Long> currentTime = new ThreadLocal();

    /**
     * 功能描述：配置切入点
     * 该方法无方法体,主要为了让同类中其他方法使用此切入点
     */
    @Pointcut("@annotation(com.app.annotation.platform.OperationLog)")
    public void logPointcut() {}

    /**
     * 功能描述：配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.app.annotation.platform.OperationLog aopOperationLog = method.getAnnotation(com.app.annotation.platform.OperationLog.class);

        currentTime.set(System.currentTimeMillis());
        Object result = joinPoint.proceed();
        Long time = System.currentTimeMillis() - currentTime.get();
        currentTime.remove();

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        operationLogService.insertInfoLog(request, joinPoint.getTarget().getClass().getName(), signature.getName(), getParameter(method, joinPoint.getArgs()), time, aopOperationLog.value());

        return result;
    }

    /**
     * 功能描述：配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e         exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.app.annotation.platform.OperationLog aopOperationLog = method.getAnnotation(com.app.annotation.platform.OperationLog.class);

        Long time = System.currentTimeMillis() - currentTime.get();
        currentTime.remove();

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        operationLogService.insertErrorLog(request, joinPoint.getTarget().getClass().getName(), signature.getName(), getParameter(method, joinPoint.getArgs()), time, getStackTrace(e).getBytes(StandardCharsets.UTF_8), aopOperationLog.value());
    }

    private String getStackTrace(Throwable e) {
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            e.printStackTrace(pw);
            return sw.toString();
        }
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private String getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }

            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }

        if (argList.size() == 0) {
            return "";
        }

        return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList);
    }

}
