package com.lz.common.utils;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @Author: djc
 * @Desc:
 * @Date: 2020/9/27 14:48
 */
public class ListUtils {  //list 分页

    public static List startPage(List list, Integer pageNum,
                                  Integer pageSize) {
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        pageNum = pageNum<1?1:pageNum;
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        if(pageNum>pageCount){
            return Lists.newArrayList();
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (!Objects.equals(pageNum, pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }

}
