package cn.reghao.oss.console.util.db;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Hibernate 分页
 *
 * @author reghao
 * @date 2021-06-02 11:07:56
 */
@Deprecated
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(getParameter("page", String.valueOf(1)));
        int size = Integer.parseInt(getParameter("size", String.valueOf(pageSize)));
        String order =  getParameter("orderBy", orderBy);
        String direction = 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(getParameter("page", String.valueOf(1)));
        int size = Integer.parseInt(getParameter("size", String.valueOf(DEFAULT_PAGE_SIZE)));
        String order =  getParameter("orderBy", orderBy);
        String direction = getParameter("direction", sortDirection.toString());
        Sort sort = Sort.by(sortDirection, order);
        return PageRequest.of(index-1, size, sort);
    }

    private static String getParameter(String param, String defaultValue){
        String parameter = getRequest().getParameter(param);
        return StringUtils.isEmpty(parameter) ? defaultValue : parameter;
    }

    private static HttpServletRequest getRequest(){
        return getServletRequest().getRequest();
    }

    private static HttpServletResponse getResponse(){
        return getServletRequest().getResponse();
    }

    private static ServletRequestAttributes getServletRequest(){
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }
}
