package com.bonus.common.core.utils;

import com.bonus.common.core.web.page.TableDataInfo;
import com.github.pagehelper.PageHelper;
import com.bonus.common.core.utils.sql.SqlUtil;
import com.bonus.common.core.web.page.PageDomain;
import com.bonus.common.core.web.page.TableSupport;

import java.util.List;

/**
 * 分页工具类
 * 
 * @author bonus
 */
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 TableDataInfo endPage(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setTotal(list.size());
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        int offset = (pageNum - 1) * pageSize;
        int limit = pageSize;
        if ((offset + limit) < list.size()) {
            list = list.subList(offset, offset + limit);
        } else {
            list = list.subList(offset, list.size());
        }
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        return rspData;
    }

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