package com.ylcm.sys.interceptor;

import java.net.URLEncoder;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ylcm.sys.common.Constants;


public class LoginInterceptor extends HandlerInterceptorAdapter {
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		request.getSession().setAttribute("basePath", Constants.PATH_BASE);
		request.getSession().setAttribute("staticPath", Constants.PATH_STATIC);
		
		String path = request.getServletPath();
		String[] actions = path.split("/");
		
		String queryString = this.getQueryString(request);
		String url = request.getServletPath().substring(1) + (StringUtils.isBlank(queryString) ? "" : "?" + queryString);
		
		
		if(null == request.getSession().getAttribute("manager")){
			if (!Constants.uninterceptUrl.contains(actions[1])) {
				response.sendRedirect(Constants.PATH_BASE.concat("login.do?next=").concat(URLEncoder.encode(url, Constants.ENCODING_UTF8)));
				return false;
			}
		}
		
		if("login.do".equals(actions[1])){
			if (null != request.getSession().getAttribute("manager") && null != request.getSession().getAttribute("nextUrl")) {
				response.sendRedirect(Constants.PATH_BASE.concat((String) request.getSession().getAttribute("nextUrl")));
			}
		}
		return true;
	}
	
	/**
	 * 获取get和post请求中的参数列表，返回格式化字符串
	 * @param request http请求
	 * @return 参数字符串
	 */
	private String getQueryString(HttpServletRequest request) {
		String queryString = "";
		String method = request.getMethod();
		if ("GET".equals(method)) {
			queryString = request.getQueryString();
		} else {
			 Map<String, String[]> params = request.getParameterMap();
		     for (String key : params.keySet()) {
		    	 if(params.get(key) instanceof String[]){
		    		 String[] values = params.get(key);
			         for (int i = 0; i < values.length; i++) {
			             String value = values[i];
			             queryString += key + "=" + value + "&";
			         }
		    	 }else{
		    		 queryString += key + "=" + params.get(key) + "&";
		    	 }
		         
		     }
		     if (queryString.length() > 1) {
				queryString = queryString.substring(0, queryString.length() - 1);
			}
		}
		
		return queryString;
	}
}