package org.example.entity;

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

/**
 * 分页结果封装类
 */
public class PageResult<T> {
    
    /**
     * 当前页数据
     */
    private List<T> records;
    
    /**
     * 总记录数
     */
    private long total;
    
    /**
     * 当前页码
     */
    private int page;
    
    /**
     * 每页条数
     */
    private int pageSize;
    
    /**
     * 总页数
     */
    private int totalPages;
    
    public PageResult() {
    }
    
    public PageResult(List<T> records, long total, int page, int pageSize) {
        this.records = records;
        this.total = total;
        this.page = page;
        this.pageSize = pageSize;
        this.totalPages = (int) Math.ceil((double) total / pageSize);
    }
    
    /**
     * 对列表进行内存分页
     */
    public static <T> PageResult<T> of(List<T> allData, int page, int pageSize) {
        if (allData == null || allData.isEmpty()) {
            return new PageResult<>(Collections.emptyList(), 0, page, pageSize);
        }
        
        int total = allData.size();
        int fromIndex = (page - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        
        if (fromIndex >= total) {
            return new PageResult<>(Collections.emptyList(), total, page, pageSize);
        }
        
        List<T> records = new ArrayList<>(allData.subList(fromIndex, toIndex));
        return new PageResult<>(records, total, page, pageSize);
    }

    public List<T> getRecords() {
        return records;
    }

    public void setRecords(List<T> records) {
        this.records = records;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }
}
