package com.artfess.mongodb.page;



import com.artfess.mongodb.query.FieldSortMongo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhx
 * @create 2021/8/1
 */
public class Page<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 总数
     */
    protected long total = 0;
    /**
     * 每页显示条数，默认 10
     */
    protected long size = 10;

    /**
     * 当前页
     */
    protected long current = 1;

    /**
     * 总页数
     */
    protected long pages = 1;

    /**
     * 结果列表
     */
    private List<T> rows;

    public List<FieldSortMongo> getSorter() {
        return sorter;
    }

    public void setSorter(List<FieldSortMongo> sorter) {
        this.sorter = sorter;
    }

    /**
     * 排序字段
     */
    private List<FieldSortMongo> sorter = new ArrayList<FieldSortMongo>();

    public Page(){
        this.current = 1;
        this.size = 10;
    }
    public Page(int currentPage, int pageSize){
        this.current=currentPage<=0?1:currentPage;
        this.size=pageSize<=0?1:pageSize;
    }
    public long getSize() {
        return size;
    }
    public void setSize(long pageSize) {
        this.size = pageSize;
    }
    public long getCurrent() {
        return this.current;
    }

    public Page<T> setCurrent(long current) {
        this.current = current;
        return this;
    }
    public long getTotal() {
        return this.total;
    }

    public Page<T> setTotal(long total) {
        this.total = total;
        return this;
    }
    public void setPages(long pages){
        this.pages = pages;
    }
    public long getPages(){
        return this.pages;
    }

    /**
     * 设置结果 及总页数
     * @param rows
     */
    public void build(List<T> rows) {
        this.setRows(rows);
        long count =  this.getTotal();
        long divisor = count / this.getSize();
        long remainder = count % this.getSize();
        this.setPages(remainder == 0 ? divisor == 0 ? 1 : divisor : divisor + 1);
    }
    public List<T> getRows() {
        return rows;
    }
    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public static PageRequest getPageParam(Integer num, Integer size, Sort sort) {
        int pageNum = 0;
        if (Objects.nonNull(num) && num > 1) {
            pageNum = num - 1;
        }

        int pageSize = 10;
        if (Objects.nonNull(size) && size > 0) {
            pageSize = size;
        }

        return PageRequest.of(pageNum, pageSize, sort);
    }
}
