package com.sdut.labex.interceptor;

import com.sdut.labex.entity.User;
import com.sdut.labex.mapper.UserMapper;
import com.sdut.labex.utils.JWTUtil;
import com.sdut.labex.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * File: TokenInterceptor
 * Created: 2023/6/11
 * Author: springforest
 * Description:
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper usersMapper;
    private static final String AUTH_HEADER = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(AUTH_HEADER);
        if (request.getMethod().equals("OPTIONS") || request.getRequestURI().equals("/error")) {
            return true;
        }

        //输出请求信息
        log.info("----------------------请求信息-----------------------");
        // 输出请求方法
        log.info("请求方法: " + request.getMethod());
        // 输出请求URI
        log.info("请求URI: " + request.getRequestURI());
        // 输出token
        if (token != null) {
            log.info("token: " + token);
        }
        log.info("----------------------------------------------------");

        if (token != null && !JWTUtil.isExpired(token)) {
            User user = usersMapper.selectById(JWTUtil.decode(token).getClaim("id").asString());
            if (user == null) {
                return true;
            }
            //保存到本线程
            UserHolder.saveUser(user);
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }

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