package com.vctgo.common.security.interceptor;

import com.vctgo.common.core.constant.SecurityConstants;
import com.vctgo.common.core.context.SecurityContextHolder;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.security.auth.AuthUtil;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.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;
import java.util.Objects;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author vctgo
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        SecurityContextHolder.setTenantId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_TENANT_ID));
        SecurityContextHolder.setDeptId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_DEPT_ID));
        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserAccount(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ACCOUNT));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setNickName(ServletUtils.getHeader(request,SecurityConstants.DETAILS_NICKNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));

        String token = SecurityUtils.getToken();
        if (StrUtils.isNotEmpty(token)) {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (StrUtils.isNotNull(loginUser)) {
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
                SecurityContextHolder.setTenantId(String.valueOf(loginUser.getSysUserTempalte().getTenantId()));
                SecurityContextHolder.setUserId(loginUser.getUserid().toString());
                SecurityContextHolder.setUserAccount(loginUser.getUserAccount());
                SecurityContextHolder.setUserName(loginUser.getUsername());
                SecurityContextHolder.setTenantType(Objects.isNull(loginUser.getTenantType()) ? "3" : String.valueOf(loginUser.getTenantType()));
                SecurityContextHolder.setTenantName(loginUser.getTenantName());
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        SecurityContextHolder.remove();
    }
}
