package com.sckw.core.interceptor;

import com.alibaba.fastjson2.JSON;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginEntHolder;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.model.LoginEntInfo;
import com.sckw.core.web.model.LoginUserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 登录认证拦截器,用于从请求头中获取登录用户信息并设置到上下文中
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userInfoStrEncode = request.getHeader(Global.USER_INFO_STR_ENCODE);
        String entInfoStrEncode = request.getHeader(Global.ENT_INFO_STR_ENCODE);
        LoginUserInfo loginUserInfo = null;
        LoginEntInfo loginEntInfo = null;
        if(StringUtils.isNotBlank(userInfoStrEncode)){
            String userInfoStr = URLDecoder.decode(userInfoStrEncode, StandardCharsets.UTF_8);
            loginUserInfo = JSON.parseObject(userInfoStr, LoginUserInfo.class);
        }
        if(StringUtils.isNotBlank(entInfoStrEncode)){
            String entInfoStr = URLDecoder.decode(entInfoStrEncode, StandardCharsets.UTF_8);
            loginEntInfo = JSON.parseObject(entInfoStr, LoginEntInfo.class);
        }
        LoginUserHolder.set(loginUserInfo);
        LoginEntHolder.set(loginEntInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理用户和企业上下文线程变量
        LoginUserHolder.remove();
        LoginEntHolder.remove();
    }
}
