package com.mini.capi.model;

import lombok.Data;

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

@Data
public class PageResult<T> implements Serializable {

    private final int total;        // 总记录数
    private final int pages;        // 总页数
    private final int pageNum;      // 当前页
    private final int pageSize;     // 每页条数
    private final List<T> data;     // 当前页数据

    private PageResult(int total, int pages, int pageNum, int pageSize, List<T> data) {
        this.total = total;
        this.pages = pages;
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.data = data;
    }

    public static <T> PageResult<T> of(List<T> listData, int pageNum, int pageSize) {
        if (listData == null || listData.isEmpty() || pageNum <= 0 || pageSize <= 0) {
            return new PageResult<>(0, 0, pageNum, pageSize, Collections.emptyList());
        }
        int total = listData.size();
        int pages = (int) Math.ceil((double) total / pageSize);

        int from = (pageNum - 1) * pageSize;
        if (from >= total) {
            return new PageResult<>(total, pages, pageNum, pageSize, Collections.emptyList());
        }
        int to = Math.min(from + pageSize, total);
        List<T> list = new ArrayList<>(listData.subList(from, to));
        return new PageResult<>(total, pages, pageNum, pageSize, list);
    }
}
