package com.muyu.common.core.web.model;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.core.web.page.PageReq;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import java.util.List;

/**
 * 列表查询模型
 *
 * @author DongZeLiang
 * @date 2024-11-20 14:18
 */
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class QueryModel<T> {

    /**
     * 当前记录起始索引
     */
    private Integer pageNum;

    /**
     * 每页显示记录数
     */
    private Integer pageSize;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     */
    private boolean isAsc = true;

    /**
     * 构建模型分页对象
     * @param pageReq 分页参数
     * @return 模型分页对象
     */
    public T domainBuild(PageReq pageReq) {
        this.pageNum = pageReq.getPageNum();
        this.pageSize = pageReq.getPageSize();
        this.orderByColumn = pageReq.getOrderByColumn();
        this.isAsc = "asc".equals(pageReq.getIsAsc());
        return (T) this;
    }

    /**
     * 构建查询分页对象
     * @return 查询分页对象
     */
    public <I> Page<I> buildPage(){
        Page<I> page = Page.of(this.getPageNum(), this.getPageSize());
        if(StringUtils.isNotBlank(this.getOrderByColumn())){
            page.setOrders(List.of(this.isAsc()
                    ? OrderItem.asc(this.getOrderByColumn()) : OrderItem.desc(this.getOrderByColumn())));
        }
        return page;
    }
}
