package com.younike.store.common;

import com.younike.store.common.util.AppContextHolder;
import com.younike.common.annotation.RestAuth;
import com.younike.common.exception.ApiException;
import com.younike.common.utils.JWTUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 权限验证逻辑
 */
@Component
@Aspect
@Order(1)
public class AuthInterceptor {

    private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Pointcut("execution(* com.younike.store.*.*.*(..)) || execution(* com.younike.store.*.*(..))")
    public void auth() {
    }


    @SuppressWarnings("rawtypes")
    @Before("auth()")
    public void before(JoinPoint joinPoint) {
        // 如果标示了公有的方法则不需要验证签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // web无request时，如果导出任务注解为true，则直接跳过权限检查
        if (RequestContextHolder.getRequestAttributes() == null) {
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        Enumeration<String> headerNames = request.getHeaderNames();
//        while(headerNames.hasMoreElements()){
//            System.out.println(request.getHeader(headerNames.nextElement()));
//        }
        String token = request.getHeader("token");
        String secret = request.getHeader("secret");

        RestAuth restAuth = method.getDeclaredAnnotation(RestAuth.class);
        if (restAuth != null && restAuth.isPublic()) {
            return;
        }



        //验证参数的正确性
        if (StringUtils.isBlank(token) ) {
            throw new ApiException(201,"登录过期，请重新登录");
        }

         // 验证token
        JWTUtils.verifyToken(token);
        String userId = JWTUtils.getAudience(token);

        // 验证userId的准确性（是否为用户表中的userId）
        if(StringUtils.isEmpty(userId)) {
            throw new ApiException(201,"登录过期，请重新登录");
        }

        // 存储userId
        AppContextHolder.setUserId(userId);

    }

    @After("auth()")
    public void after(JoinPoint joinPoint) {
        AppContextHolder.removeUserId();
    }

}
