package com.xhkjedu.suser.interceptors;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.suser.utils.JedisUtil;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Configuration
@Slf4j
public class RequestInterceptor extends JedisUtil implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // 请求结束时间
        Long endTime = System.currentTimeMillis();
        // 从HttpServletRequest获取开始时间
        Long startTime = (Long) arg0.getAttribute("_startTime");
        double time = ((endTime - startTime) * 1.000) / 1000;
        // 打印接口信息及耗时
        if (time > 1) {
            log.error(" {}；耗时：{}s", arg0.getRequestURI(), time);
        }
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    /**
     * 在调用controller具体方法前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("请求的uri:" + request.getRequestURI());
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json;charset=UTF-8");

        // 记录请求开始时间
        request.setAttribute("_startTime", System.currentTimeMillis());
        String requestURI = request.getRequestURI();
        String key = request.getHeader("Token-Key");
        String token = request.getHeader("Token-Value");
        if (!requestURI.contains("user/login") && !requestURI.endsWith("/get_new")
                && N_Utils.isNotEmpty(key) && N_Utils.isNotEmpty(token)) {//非登录和获取最新版本相关接口验证token
            String redis_token = get(key);//系统缓存中保存的token
            if (!token.equals(redis_token)) {
                ResultVo result = new ResultVo();
                result.setCode(2);
                result.setMsg("登录失效");

                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
        }
        return true;
    }
}
