package link.at17.mid.tushare.component;


import lombok.extern.slf4j.Slf4j;

import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


/**
 * 注入拦截器
 */
@Component
@Slf4j
public class PlatformInterceptor implements HandlerInterceptor {

    @Autowired
    Reflections reflections;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        injectNecessary(request, handler);
        request.getSession(true);
        
        return true;
    }
    
    /**
     * 为前端模板注入变量
     * @param request
     */
    public void injectNecessary(HttpServletRequest request, Object handler) {
     
        // 只在 Controller（HandlerMethod）里才做注入
        if (!(handler instanceof HandlerMethod)) {
            // 静态资源、图片、css、js 都会被 ResourceHttpRequestHandler 处理，
            // 这里一律跳过
            return;
        }
        
        // 排除 @ResponseBody/json 接口
        HandlerMethod hm = (HandlerMethod) handler;
        if (hm.hasMethodAnnotation(ResponseBody.class) 
         || hm.getBeanType().isAnnotationPresent(RestController.class)) {
            return;
        }
        
        request.setAttribute("request", request); // 把 request 本身放到 attribute 里去，供前端部分位置用
    }
    
}
