package cn.reghao.autodop.dmaster.util.db;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * Hibernate 分页
 *
 * @author reghao
 * @date 2021-06-02 11:07:56
 */
public class PageSort {
    private static final int DEFAULT_PAGE_SIZE = 10;
    private static final String DEFAULT_ORDER_BY_COLUMN = "updateTime";
    private static final Sort.Direction DEFAULT_SORT_DIRECTION = Sort.Direction.DESC;

    public static PageRequest pageRequest() {
        return pageRequest(DEFAULT_PAGE_SIZE, DEFAULT_ORDER_BY_COLUMN, DEFAULT_SORT_DIRECTION);
    }

    /**
     * @param pageSize 分页大小
     * @param orderBy 排序字段
     * @param sortDirection 排序方向(升序/降序)
     * @return
     * @date 2021-06-02 下午1:25
     */
    public static PageRequest pageRequest(int pageSize, String orderBy, Sort.Direction sortDirection) {
        int index = Integer.parseInt(HttpRequestUtil.getParameter("page", String.valueOf(1)));
        int size = Integer.parseInt(HttpRequestUtil.getParameter("size", String.valueOf(pageSize)));
        String order =  HttpRequestUtil.getParameter("orderBy", orderBy);
        String direction = HttpRequestUtil.getParameter("direction", sortDirection.toString());
        Sort sort = Sort.by(sortDirection, order);
        return PageRequest.of(index-1, size, sort);
    }

    public static PageRequest pageRequest(String orderBy, Sort.Direction sortDirection) {
        int index = Integer.parseInt(HttpRequestUtil.getParameter("page", String.valueOf(1)));
        int size = Integer.parseInt(HttpRequestUtil.getParameter("size", String.valueOf(DEFAULT_PAGE_SIZE)));
        String order =  HttpRequestUtil.getParameter("orderBy", orderBy);
        String direction = HttpRequestUtil.getParameter("direction", sortDirection.toString());
        Sort sort = Sort.by(sortDirection, order);
        return PageRequest.of(index-1, size, sort);
    }
}
