package com.yccrc.common.utils;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.yccrc.common.core.page.PageDomain;
import com.yccrc.common.core.page.TableSupport;
import com.yccrc.common.utils.sql.SqlUtil;


/**
 * 分页工具类
 * 
 * @author yccrc
 */
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();
    }
    
    /**
     * 初始化分页信息
     * @param <T>
     * @return
     */
    public static <T> Page<T> initPage() {
    	PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String sort = pageDomain.getIsAsc();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());

        Page<T>  p = new Page<>(pageNum, pageSize);
        if (StringUtils.isNotEmpty(orderBy)&&StringUtils.isNotEmpty(orderBy)) {
            boolean isAsc = true;
            if ("desc".equals(orderBy.toLowerCase())) {
                isAsc = false;
            }
            if (isAsc) {
                p.addOrder(OrderItem.asc(sort));
            } else {
                p.addOrder(OrderItem.desc(sort));
            }
        }
        return p;
    }
}
