package com.zzsn.util;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 分页过滤器
 * 创建人：李东亮   
 * 创建时间：2015-5-5 上午10:13:34   
 * 公司 ：郑州数能软件科技有限公司
 * @version  1.0  
 *
 */
public class PageInterceptor implements HandlerInterceptor {

	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception e)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			 Object obj) throws Exception {
		// TODO Auto-generated method stub
		String  offset = request.getParameter("pager.offset");
		if(offset!=null){
			 SystemContext.setOffSet(Long.valueOf(offset));
		     SystemContext.setPageSize(10L);
		}else
		{
			long page = getPage(request);
			long pageSize = getPagesize(request);
			 SystemContext.setOffSet((page-1)*pageSize);
		     SystemContext.setPageSize(pageSize);
		}
		
		
		return true;
	}
   /**
    * 获得page（第几页）参数的值 ，默认为第一页
    * @param request 
    * @return 
    */  
   protected long getPage(HttpServletRequest request) {  
       Long page = 1L;  
       try {  
       	String pageNum = request.getParameter("page");  
           if (page != null) {  
           	page =Long.parseLong(pageNum);  
           	if(page<1)
           	{
           		page = 1L;
           	}
           }  
       } catch (NumberFormatException e) {  
       	page = 1L;
       }  
       return page;  
   }  
   /** 
    * 设置每页大小 ,默认为Constants.PAGE_SIZE
    * @return 
    */  
   protected Long getPagesize(HttpServletRequest request) {  
   	Long size =10L;
       try {  
           String pagesize = request.getParameter("rows");  
           if (pagesize != null) {  
           	size =Long.parseLong(pagesize);  
           	if(size<1)
           	{
           		size = 10L;
           	}
           }
       } catch (NumberFormatException e) {  
       	size =10L;
       }
       return size;
   }

}
