package cn.iocoder.yudao.framework.mybatis.core.vo;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.CaseFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * 功能描述: 分页字段
 * <p>
 * 作者: Admin
 * 日期: 2020-09-15 12:00
 * @author Admin
 */
@ToString(callSuper = true)
public class PageVO {
    private static final int MAX = 10000;

    @Setter
    @Getter
    @ApiModelProperty(value = "页码，从 1 开始", required = true, example = "1")
    @NotNull(message = "页码不能为空")
    @Min(value = 1, message = "页码最小值为 1")
    private Integer page = 1;

    @Setter
    @Getter
    @ApiModelProperty(value = "每页条数，最大值为 10000", required = true, example = "10")
    @NotNull(message = "每页条数不能为空")
    @Min(value = 1, message = "每页条数最小值为 1")
    @Max(value = 10000, message = "每页条数最大值为 10000")
    private Integer rows = 10;

    @Setter
    @Getter
    @ApiModelProperty(value = "正数倒叙，0或负数正序", example = "1")
    private Integer sort = 0;

    @Setter
    @Getter
    @ApiModelProperty(value = "排序字段", example = "id")
    private String field;

    @Getter
    @ApiModelProperty(value = "排序方式", hidden = true)
    private String by = "id DESC";

    /***
     * 构造方法
     */
    public PageVO() {}

    /***
     * 构造方法
     * @param page
     * @param rows
     * @param sort
     * @param field
     */
    public PageVO(int page, int rows, int sort, String field) {
        this.page  = page;
        this.rows  = rows;
        this.sort  = sort;
        this.field = field;
    }

    /***
     * 分页信息
     * @param page
     * @param rows
     * @param sort
     * @param field
     * @return
     */
    public static PageVO of(int page, int rows, int sort, String field) {
        return new PageVO(page, rows, sort, field);
    }

    public int getRows() {
        if (rows > MAX) { return MAX; }
        return rows;
    }

    public String getBy() {
        if (StrUtil.isNotBlank(field)) {
            boolean reversed = false;
            if (0 < sort) { reversed = true; }

            return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field) + " " + (reversed?"DESC":"ASC");
        }
        return by;
    }
}
