package com.wms.annotation;

import com.wms.entity.table.WmsLog;
import com.wms.service.LogService;
import com.wms.utils.HttpUtils;
import com.wms.utils.WmsUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MyLogAspect {
    private final LogService logService;
    // 为了记录运行时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 设置操作日志切入点，这里介绍两种方式：
     * 1、基于注解切入（也就是打了自定义注解的方法才会切入）
     *    //@Pointcut("@annotation(com.wms.annotation.MyLog)")
     * 2、基于包扫描切入
     *    //@Pointcut("execution(public * com.wms.controller..*.*(..))")
     */
    @Pointcut("@annotation(com.wms.annotation.MyLog)")//在注解的位置切入代码
    public void operLogPointCut() {
    }
    @Before("operLogPointCut()")
    public void beforeMethod(JoinPoint point){
        startTime.set(System.currentTimeMillis());
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.wms.controller..*.*(..))")
    public void operExceptionLogPointCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     * @param joinPoint 切入点
     * @param result 返回结果
     */
    @AfterReturning(value = "operLogPointCut()", returning = "result")
    public void saveOperLog(JoinPoint joinPoint, Object result) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        }
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            MyLog myLog = method.getAnnotation(MyLog.class);
            WmsLog wmsLog = new WmsLog();
            wmsLog.setLogId(WmsUtils.generateId("LOG_"));
            if (myLog != null) {
                wmsLog.setLogTitle(myLog.logTitle());
                wmsLog.setLogMethod(myLog.logMethod());
            }
            // 设置日志表详情
            wmsLog.setLogRequest(joinPoint.getArgs().length > 0 ? joinPoint.getArgs()[0] : null);
            wmsLog.setLogResponse(result);
            if (request != null) {
                wmsLog.setLogIp(HttpUtils.getIpAddr(request));
            }
            wmsLog.setLogTime(LocalDateTime.now());
            // 获取用户名
            if (wmsLog.getLogRequest() != null) {
                Method methodToGetUserName =  wmsLog.getLogRequest().getClass().getMethod("getUserName");
                wmsLog.setLogUser((String) methodToGetUserName.invoke(wmsLog.getLogRequest(), new Object[]{}));
            }
            logService.save(wmsLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(pointcut = "operExceptionLogPointCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        }
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            MyLog myLog = method.getAnnotation(MyLog.class);
            WmsLog wmsLog = new WmsLog();
            wmsLog.setLogId(WmsUtils.generateId("LOG_"));
            if (myLog != null) {
                wmsLog.setLogTitle(myLog.logTitle());
                wmsLog.setLogMethod(myLog.logMethod());
            }
            // 设置日志表详情
            wmsLog.setLogRequest(joinPoint.getArgs().length > 0 ? joinPoint.getArgs()[0] : null);
            wmsLog.setLogResponse(e);
            if (request != null) {
                wmsLog.setLogIp(HttpUtils.getIpAddr(request));
            }
            wmsLog.setLogTime(LocalDateTime.now());
            // 获取用户名
            if (wmsLog.getLogRequest() != null) {
                Method methodToGetUserName =  wmsLog.getLogRequest().getClass().getMethod("getUserName");
                wmsLog.setLogUser((String) methodToGetUserName.invoke(wmsLog.getLogRequest(), new Object[]{}));
            }
            logService.save(wmsLog);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}