/**
 * Copyright (c) 2020 fumeiai All rights reserved.
 * <p>
 * <p>
 * <p>
 * 版权所有，侵权必究！
 */

package com.heyu.api.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

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

/**
 * 分页工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class PPageUtils<E> implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 总记录数
     */
    private int total;
    /**
     * 每页记录数
     */
    private int pageSize;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 当前页数
     */
    private int pageNum;
    /**
     * 列表数据
     */
    private List<?> rows;


    /**
     * 分页
     *
     * @param rows     列表数据
     * @param total    总记录数
     * @param pageSize 每页记录数
     * @param pageNum  当前页数
     */
    public PPageUtils(List<?> rows, int total, int pageSize, int pageNum) {
        this.rows = rows;
        this.total = total;
        this.pageSize = pageSize;
        this.pageNum = pageNum;
        this.totalPage = (int) Math.ceil((double) total / pageSize);
    }

    public PPageUtils() {

    }

    public <E> PPageUtils<E> doSelect(ISelect select) {
        IPage page = new Page(this.pageNum, this.pageSize);
        rows = select.doSelect(page);
        page.setRecords(rows);
        return new PPageUtils<E>(page);
    }

    /**
     * 开始分页
     *
     * @param pageNum  页码
     * @param pageSize 每页显示数量
     */
    public static <E> PPageUtils<E> startPage(int pageNum, int pageSize) {
        IPage<E> page = new Page<E>(pageNum, pageSize);
        return new PPageUtils<E>(page);
    }


    /**
     * 分页
     */
    public PPageUtils(IPage<?> page) {
        this.rows = page.getRecords();
        this.total = (int) page.getTotal();
        this.pageSize = (int) page.getSize();
        this.pageNum = (int) page.getCurrent();
        this.totalPage = (int) page.getPages();
    }


    public int getTotal() {
        return total;
    }

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

    public int getPageSize() {
        return pageSize;
    }

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

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public List<?> getRows() {
        return rows;
    }

    public void setRows(List<?> rows) {
        this.rows = rows;
    }
}
