package com.ximai.mes.remote.dto;

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

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title: PageParams</p>
 * <p>Description: 分页参数</p>
 *
 * @author chicheng.li
 * @version V1.0
 */
public class ErpPageParams {

    private int current;

    private int pageSize;

    private Sort sort;

    public Pageable toPageable() {
        if(sort == null){
            return PageRequest.of(current - 1, pageSize);
        }
        return PageRequest.of(current - 1, pageSize, sort.toJpaSort());
    }

    public static class Sort{
        private List<Order> orders;

        org.springframework.data.domain.Sort toJpaSort(){
            if(orders == null || orders.size()==0){
                return org.springframework.data.domain.Sort.unsorted();
            }
            return org.springframework.data.domain.Sort.by(orders.stream().map(Order::toJpaOrder).collect(Collectors.toList()));
        }

        public List<Order> getOrders() {
            return orders;
        }

        public void setOrders(List<Order> orders) {
            this.orders = orders;
        }
    }

    public static class Order{

        public Order(){}

        public Order(String property, String direction){
            this.property = property;
            this.direction = direction;
        }
        private String direction;
        private String property;

        org.springframework.data.domain.Sort.Order toJpaOrder(){
            if("ASC".equalsIgnoreCase(direction)){
                return org.springframework.data.domain.Sort.Order.asc(property);
            }
            return org.springframework.data.domain.Sort.Order.desc(property);
        }

        public String getDirection() {
            return direction;
        }

        public void setDirection(String direction) {
            this.direction = direction;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }
    }


    public int getCurrent() {
        return current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public Sort getSort() {
        return sort;
    }

    public void setSort(Sort sort) {
        this.sort = sort;
    }
}
