package cn.iocoder.yudao.framework.common.model;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.base.CaseFormat;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Map;

/**
 * 功能描述: 分页查询参数封装
 * <p>
 * 作者: July
 * 日期: 2020-09-16 18:23
 * @author Administrator
 */
@Getter
@Setter
@ToString
public class PageQuery extends QueryRequest {

    private static final long serialVersionUID = -7184214292667326280L;

    /** 页索引 */
    private int page;

    /** 每页显示数量 */
    private int rows;

    /** 排序方式 */
    private String by = "id DESC";

    public PageQuery(Map<String, Object> params) {
        super(params);

        // 分页参数
        this.page = Integer.parseInt((String) params.getOrDefault("page", "1"));
        this.rows = Integer.parseInt((String) params.getOrDefault("rows", "10"));

        // 排序字段名
        String col = (String) params.get("col");
        if (StrUtil.isNotBlank(col)) {
            boolean reversed = false;
            if (params.containsKey("sort")) {
                reversed = parseBoolean((String) params.getOrDefault("sort", "0"));
            }
            else if (params.containsKey("mode")) {
                // 排序方式 mode DESC ASC
                String mode = (String) params.get("mode");
                // "descending", "ascending", "DESC", "ASC"
                reversed = CollUtil.contains(CollUtil.toList("descending", "DESC", "desc"), mode);
            }
            this.by = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, col) + " " + (reversed ? "DESC" : "ASC");
        }

        this.remove("page");
        this.remove("rows");
        this.remove("col");
        this.remove("mode");
        this.remove("sort");
    }
}
