package com.mortals.xhx.base.login.interceptor;

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

import com.mortals.xhx.base.framework.config.InterceptorConfig;
import org.springframework.beans.factory.annotation.Autowired;

import com.mortals.framework.ap.CookieService;
import com.mortals.framework.model.CookieInfo;
import com.mortals.framework.service.ITokenService;
import com.mortals.framework.web.interceptor.BaseInterceptor;

//@Component
public class LoginJsonInterceptor extends BaseInterceptor {

    @Autowired(required = false)
    private ITokenService tokenService;
    @Autowired
    private InterceptorConfig config;

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE - 10;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try {
            String uri = request.getServletPath();
            if (config.needCheckAuth(uri)) {
                CookieInfo cookie = CookieService.getLoginCookie(request, config.getSecurityKey());
                boolean expire = true;
                try {
                    if (cookie == null || cookie.getUser() == null
                            || (cookie != null && tokenService != null && tokenService.isExpireToken(cookie))) {
                        expire = true;
                    } else {
                        expire = false;
                    }
                } catch (Exception e) {
                    logger.warn("校验cookie是否过期异常-->原因：" + e.getMessage());
                }
                // 判断用户是否登录
                if (expire) {
                    CookieService.deleteLoginCookie(request, response);
                    writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "用户未登录或登录失效，请重新登录111333");
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error("登录校验拦截请求处理异常-->" + e.getMessage());
            writeJsonResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "用户登录校验异常");
            return false;
        }

        return super.preHandle(request, response, handler);
    }
}
