package com.yaoyicloud.config;

import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionInterceptor implements HandlerInterceptor {

    public static final Map<String, String> SESSION_MAP = new ConcurrentHashMap<>();
    private static final String TARGET_PATH = "/report/";
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
        @NonNull Object handler) throws Exception {

        String requestUri = request.getRequestURI();

        // 判断是否是目标路径，如果不是则直接放行
        if (!requestUri.contains(TARGET_PATH)) {
            return true;
        }
        String relationId = request.getHeader("relationId");
        String mysession = request.getHeader("X-Session-Id");
        if (mysession == null) {
            HttpSession session = request.getSession(true);
            SESSION_MAP.put(relationId, session.getId());
        }
        if (mysession != null && SESSION_MAP.get(relationId) == null) {
            SESSION_MAP.put(relationId, mysession);
        }
        return true;
    }

}
