package com.seer.teach.common.utils;

import com.seer.teach.common.PageListBean;

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

/**
 * <p>
 *
 * </p >
 *
 * @author Captain
 * @since 2025-08-11 20:41
 */
public class MemoryPageUtils {
    /**
     * 内存分页方法
     *
     * @param fullList 全部数据列表
     * @param page     当前页，从1开始
     * @param pageSize 每页条数
     * @param <T>      泛型
     * @return 分页结果封装 PageListBean
     */
    public static <T> PageListBean<T> paginate(List<T> fullList, int page, int pageSize) {
        PageListBean<T> pageListBean = new PageListBean<>();

        if (fullList == null || fullList.isEmpty()) {
            pageListBean.setList(Collections.emptyList());
            pageListBean.setPage(page <= 0 ? 1 : page);
            pageListBean.setPageSize(pageSize <= 0 ? 10 : pageSize);
            pageListBean.setTotal(0);
            pageListBean.setTotalPage(0);
            return pageListBean;
        }

        if (page <= 0) {
            page = 1;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }

        long total = fullList.size();
        long totalPage = (total + pageSize - 1) / pageSize;

        int fromIndex = (page - 1) * pageSize;
        if (fromIndex >= total) {
            pageListBean.setList(Collections.emptyList());
        } else {
            int toIndex = (int) Math.min(fromIndex + pageSize, total);
            pageListBean.setList(fullList.subList(fromIndex, toIndex));
        }

        pageListBean.setPage(page);
        pageListBean.setPageSize(pageSize);
        pageListBean.setTotal(total);
        pageListBean.setTotalPage(totalPage);

        return pageListBean;
    }
}
