package com.bohuikeji.frame.module.admin.interceptor;


import com.alibaba.fastjson.JSON;
import com.bohuikeji.frame.module.admin.base.SuperBase;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 页面登陆拦截器
 * @author 10552
 */
@Slf4j
public class LoginInterceptor extends SuperBase implements HandlerInterceptor {
	@Autowired
	HttpSession session;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		SysUser user=(SysUser) session.getAttribute("loginUser");
		//未登录
		if (user==null){
			log.info("拦截到URL：{}",request.getRequestURL());
			//AJAX判断
			if(isAjax(request)){
				response.setStatus(412);
				response.setContentType("application/json; charset=utf-8");
				PrintWriter writer = response.getWriter();
				writer.print(JSON.toJSONString(APIEntity.fail("会话超时，请重新登陆或刷新页面。")));
				writer.close();
				response.flushBuffer();
				return false;
			}
			log.info("用户未登录，跳转到登录页:[{}]",StaticComponent.ctx +"/views/login");
			response.sendRedirect(StaticComponent.ctx +"/views/login");
			return false;
		}
		return true;
	}

	/**
	 * 业务处理之后
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 判断ajax请求
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAjax(HttpServletRequest request) {
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			return true;
		}
		return false;

	}

}
