package com.huimv.beeboxs.config;

import com.alibaba.fastjson.JSONObject;
import com.huimv.beeboxs.common.token.TokenConstant;
import com.huimv.beeboxs.common.token.TokenSign;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  jwt拦截器
 * </p>
 * @since 2021/4/19
 */
public class JWTInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法，则直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        response.setContentType("application/json;charset=utf-8");
        // 获取token
        String token=request.getHeader("accessToken");


        if (null==token){
            Map<String, Object> map=new HashMap<>();
            map.put("data","token is null");
            map.put("code","401");
            response.setStatus(401);
            response.getWriter().write(JSONObject.toJSONString(map));
            return false;
        }else {
            Claims claims = TokenSign.getClaims(token);
            if (claims == null){
                Map<String, Object> map=new HashMap<>();
                map.put("data","token is overdue");
                map.put("code","403");
                response.setStatus(403);
                response.getWriter().write(JSONObject.toJSONString(map));
                return false;
            }

            boolean result= TokenSign.verify(token);
            if (result){
                //更新存储的token信息
                TokenConstant.updateTokenMap(token);
                return true;
            }
            Map<String, Object> map=new HashMap<>();
            map.put("data","token is null");
            map.put("code","401");
            response.setStatus(401);
            response.getWriter().write(JSONObject.toJSONString(map));
            return false;

        }
    }


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

    }

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

    }
}