package com.tykj.workflowcore.base.page;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * JPA分页类
 * @author HuangXiahao
 * @class CustomOrder
 * @data 2020/5/13
 **/
public class JpaCustomPage {

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private Integer page = 0;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private Integer size = 15;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<JpaCustomOrder> orders = new ArrayList<>();

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        Assert.isTrue(page >= 0, "分页信息错误！");
        this.size = size;
    }

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

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

    @JsonIgnore
    public long getOffset() {
        return page * size;
    }

    @JsonIgnore
    public Integer getLimit() {
        return size;
    }

    @JsonIgnore
    public PageRequest getPageable() {
        if (orders.size() != 0) {
            List<Sort.Order> orders = new ArrayList<>();
            this.orders.stream().forEach(item ->
                    orders.add(new Sort.Order(item.getDirection(), item.getCoulmn())));
            return PageRequest.of(getPage(), getLimit(), Sort.by(orders));
        }


        return PageRequest.of(getPage(), getLimit());
    }


}
