package com.engine.organization.util.page;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collections;
import java.util.List;


public class PageUtil {

    public static void start(Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize <= 0 ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);
    }


    public static <T> Page<T> buildPage(Integer pageNo, Integer pageSize) {
        pageNo = pageNo == null || pageNo <= 0 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize <= 0 ? 10 : pageSize;
        return new Page(pageNo, pageSize, true);
    }

    /**
     * 分页
     *
     * @param pageNo   页码（从1开始）
     * @param pageSize 每页条数
     * @param source   待分页的数据
     * @param <T>      范型制定类
     * @return
     */
    public static <T> List<T> subList(int pageNo, int pageSize, List<T> source) {
        if (CollectionUtils.isEmpty(source)) {
            return Collections.emptyList();
        }
        int endIndex = pageNo * pageSize;
        int startIndex = (pageNo - 1) * pageSize;
        startIndex = startIndex < 0 ? 0 : startIndex;
        return source.subList(startIndex > source.size() ? source.size() : startIndex,
                endIndex > source.size() ? source.size() : endIndex);
    }
}
