package com.fdage.aop;

import com.fdage.pojo.TbLog;
import com.fdage.service.ILogService;
import com.fdage.shiro.JwtUtil2;
import lombok.extern.slf4j.Slf4j;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by owen on 2020/2/25 0025 9:24
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

    @Autowired
    private ILogService logService;

    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(com.fdage.aop.WebControllerLog)")//切入点描述 这个是controller包的切入点
    public void controllerLog(){}//签名，可以理解成这个切入点的一个名称

    @Before("controllerLog()") //在切入点的方法run之前要干的
    public void logBeforeController(JoinPoint joinPoint) throws Exception{

        // 获取token
        String token = request.getHeader("token");
        Long userId = null;
        if (token != null) {
             userId = JwtUtil2.getUserId(token);
        }


        // 记录下请求内容
//        log.info("request URL : {}" , request.getRequestURL().toString());
        log.info("request Method : {}" , request.getMethod());
        log.info("request IP : {}" , request.getRemoteAddr());
        log.info("request Args : {}" , Arrays.toString(joinPoint.getArgs()));

        String description = getControllerLogDescription(joinPoint);

        log.info("request description : {}", description);

        //下面这个getSignature().getDeclaringTypeName()是获取包+类名的   然后后面的joinPoint.getSignature.getName()获取了方法名
        log.info("request Class_Method : {}" , joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        // 保存数据库
        List<String> detail = getDetail(description);
        TbLog logEntity = new TbLog();
        logEntity.setCreateTime(new Date());
        logEntity.setType(detail.get(0));
        logEntity.setDescription(detail.get(1));
        logEntity.setUserId(userId);

        logService.save(logEntity);

    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint
     *            切点
     * @return 方法描述
     * @throws Exception
     */
    public static String getControllerLogDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(WebControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }

    private static List<String> getDetail(String str){
        String[] split = str.split("-");
        return Arrays.asList(split);
    }

//    public static void main(String[] args) {
//        String str = "aaaaaaa-bb";
//        String[] detail = getDetail(str);
//        List<String> list = Arrays.asList(detail);
//
//
//        for (String i:detail) {
//            System.out.println(i);
//        }
//    }
}
