package com.ruoyi.common.utils;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.sql.SqlUtil;

/**
 * 分页工具类
 * 
 * @author ruoyi
 */
public class PageUtils extends PageHelper
{
    /**
     * 设置请求分页数据
     */
    public static void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage()
    {
        PageHelper.clearPage();
    }

    public static void obtainPage(int[] ret)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if(null != pageNum)
            ret[0] = pageNum;
        if(null != pageSize)
            ret[1] = pageSize;
    }

    public static int offset(int pageNo, int pageSize)
    {
        return (pageNo - 1) * pageSize;
    }

    /**
     * 设置请求分页数据(允许不分页)
     */
    public static void startPage(Integer pageNum, Integer pageSize)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest(pageNum, pageSize);
        pageNum = pageDomain.getPageNum();
        pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        if(null != pageNum && pageNum > 0 && null != pageSize && pageSize > 0)
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        else if(StringUtils.isNotEmpty(orderBy))
            PageHelper.orderBy(orderBy);
    }
}
