package com.tykj.dev.misc.base;

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.forEach(item -> {
                        if ("ASC".equals(item.getDirection())) {
                            orders.add(new Sort.Order(Sort.Direction.ASC, item.getCoulmn()));
                        }
                        else if("DESC".equals(item.getDirection())){
                            orders.add(new Sort.Order(Sort.Direction.DESC, item.getCoulmn()));
                        }
                    }
            );
            if (orders.size()>0) {
                return PageRequest.of(getPage(), getLimit(), Sort.by(orders));
            }
            else {
                return PageRequest.of(getPage(), getLimit());
            }
        }
        return PageRequest.of(getPage(), getLimit());
    }


}
