package com.app.framework.core.support.view.grid;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 分页参数工具类
 *  主要是从HttpServletRequest中获取分页参数
 *  用法：Paging paging = PagingUtils.getPaging(request);
 */
public class PagingUtils {

    /**
     * 从request对象中获取分页参数、排序参数
     * @param request
     * @return	Page
     */
    public static Paging getPaging(HttpServletRequest request){
        return getPaging(request, null);
    }

    /**
     * 从request对象中获取分页参数、排序参数
     * @param request
     * @param limit 每页显示记录数(用于设置每页显示记录数)
     * @return	Page
     */
    public static Paging getPaging(HttpServletRequest request, Integer limit){
        Paging page = new Paging();
        Enumeration<?> paramNames = request.getParameterNames();
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if("pageNo".equals(paramName)){
                String pageNo = request.getParameter("pageNo");
                if(StringUtils.isNotBlank(pageNo)){
                    page.setPageNo(Integer.parseInt(pageNo));
                }
            }else if("start".equals(paramName)){
                String start = request.getParameter("start");
                if(StringUtils.isNotBlank(start)){
                    page.setStart(Integer.parseInt(start));
                }
            }else if("limit".equals(paramName)){
                String slimit = request.getParameter("limit");
                if(StringUtils.isNotBlank(slimit)){
                    page.setLimit(Integer.parseInt(slimit));
                }
            }else if("isPage".equals(paramName)){
                String isPage = request.getParameter("isPage");
                if(StringUtils.isNotBlank(isPage)){
                    page.setIsPage(Boolean.parseBoolean(isPage));
                }
            }else if("isCountPage".equals(paramName)){
                String isCountPage = request.getParameter("isCountPage");
                if(StringUtils.isNotBlank(isCountPage)){
                    page.setIsCountPage(Boolean.parseBoolean(isCountPage));
                }
            }else if("sort".equals(paramName)){
                String sort = request.getParameter("sort");
                if(StringUtils.isNotBlank(sort)){
                    page.setSort(sort);
                }
            }else if("dir".equals(paramName)){
                String dir = request.getParameter("dir");
                if(StringUtils.isNotBlank(dir)){
                    page.setDir(dir);
                }
            }
        }
        if(limit != null){
            page.setLimit(limit);
        }
        return page;
    }

}
