package com.tykj.workflowcore.user.util;

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 javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HuangXiahao
 * @class CustomOrder
 * @data 2020/5/13
 **/
public class CustomPage {

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

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

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<CustomOrder> 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<CustomOrder> getOrders() {
        return orders;
    }

    public void setOrders(List<CustomOrder> 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.getColumn())));
            return PageRequest.of(getPage(), getLimit(), Sort.by(orders));
        }


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


}
