package com.m2pool.common.security.interceptor;

import com.m2pool.common.core.constant.SecurityConstants;
import com.m2pool.common.core.context.SecurityContextHolder;
import com.m2pool.common.core.utils.JwtUtils;
import com.m2pool.common.core.utils.ServletUtils;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.common.core.utils.ip.IpUtils;
import com.m2pool.common.security.auth.AuthUtil;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.system.api.model.LoginUser;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 自定义请求头拦截器，将请求头数据封装到线程变量中方便后续获取使用
 * 同时获取当前用户有效时间并刷新有效期
 * @Date 2024/6/13 20:29
 * @Author dy
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("调用默认拦截器,路径:"+request.getRequestURI());
        System.out.println("调用默认拦截器,路径:"+ IpUtils.getIpAddr(request));
        System.out.println(handler);
        if(!(handler instanceof HandlerMethod)){
            System.out.println("默认拦截器放行");
            return true;

        }
        System.out.println("默认拦截器处理");
        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request,SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request,SecurityConstants.USER_KEY));

        //开发环境
        String authorization = request.getHeader("Authorization");
        String userName = JwtUtils.getUserName(authorization);
        SecurityContextHolder.setUserName(userName);

        String token = SecurityUtils.getToken();
        if(StringUtils.isNotEmpty(token)){

            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if(StringUtils.isNotNull(loginUser)){

                //验证当前用户有效时间
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER,loginUser);
            }

        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        SecurityContextHolder.remove();

    }
}
