package com.sckw.core.web.response.result;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

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



/**
 * @author PC
 */
@Data
public class PageDataResult<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1803433537622129194L;
    /** 总记录数 */
    private long total;

    /** 当前页码（从1开始） */
    private int pageNum;

    /** 每页显示条数 */
    private int pageSize;

    /**
     * 总页数
     */
    private int pages;

    /** 当前页的数据列表 */
    private List<T> list;

    public PageDataResult() {

    }

    // 创建空分页结果
    public static <T> PageDataResult<T> empty(Integer pageNum, Integer pageSize) {
        return new PageDataResult<>(pageNum, pageSize, 0L, new ArrayList<>());
    }
    public PageDataResult(Integer pageNum, Integer pageSize, Long total, List<T> data) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.total = total;
        this.list = data;
        this.pages = (int) Math.ceil((double) total / pageSize);
    }

    public static <T> PageDataResult<T> success(Integer pageNum, Integer pageSize, Long total, List<T> data) {
        PageDataResult<T> pageResult = new PageDataResult<T>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(total);
        // 修正总页数计算
        if(total==0){
            pageResult.setPages(0);
        }else{
            pageResult.setPages((int) ((total + pageSize - 1) / pageSize));
        }
        pageResult.setList(data);
        return pageResult;
    }

    public static <T> PageDataResult<T> of(IPage page, List<T> records) {
        PageDataResult<T> pageResult = new PageDataResult<T>();
        pageResult.setPageNum((int)page.getCurrent());
        pageResult.setPageSize((int) page.getSize());
        pageResult.setTotal(page.getTotal());
        // 修正总页数计算
        pageResult.setPages((int) ((page.getTotal() + page.getSize() - 1) / page.getSize()));
        pageResult.setList(records);
        return pageResult;
    }


}
