package cc.smtweb.framework.core;

import cc.smtweb.framework.core.cache.redis.RedisManager;
import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.mvc.controller.IEditor;
import cc.smtweb.framework.core.mvc.realm.exception.ForbiddenException;
import cc.smtweb.framework.core.mvc.realm.exception.UnauthenticatedException;
import cc.smtweb.framework.core.session.SessionUtil;
import cc.smtweb.framework.core.session.UserSession;
import cc.smtweb.framework.core.util.NumberUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created by Akmm at 2022-08-24 10:53
 */
public class CoreInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!SwConsts.SysParam.SYS_STARTED) throw new BizException("系统启动中，请稍候...");
        String _Origin=request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", _Origin);
        String headers =request.getHeader("Access-Control-Request-Headers");
        if (null !=headers && !"".equals(headers)) {
            response.setHeader("Access-Control-Allow-Headers", headers);
        }
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "360000");
        // 如果是OPTIONS请求则结束
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        SessionUtil.checkSession(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

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