package com.pannk.mms.common.base;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pannk.mms.common.filters.SQLFilter;
import org.apache.commons.lang.StringUtils;

import java.util.Map;

import static com.pannk.mms.common.base.Constant.*;

/**
 * Created by wolf on 20-11-20.
 */
public class Query<T> {

    /**
     * 分页参数
     *
     * @param params 参数
     * @return
     */
    public IPage<T> getPage(Map<String, Object> params) {
        return this.getPage(params, null, false);
    }

    /**
     * 分页
     *
     * @param params            参数
     * @param defaultOrderField 默认排序字段
     * @param isAsc             是否升序
     * @return
     */
    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {

        Object pageObj = params.get(PAGE);
        Object limitObj = params.get(LIMIT);

        long curPage = pageObj == null ? DEFAULT_CUR_PAGE : Long.parseLong(pageObj.toString());
        long pageSize = limitObj == null ? DEFAULT_PAGE_SIZE : Long.parseLong(limitObj.toString());

        Page<T> page = new Page<>(curPage, pageSize);

        params.put(PAGE, page);


        String orderField = SQLFilter.sqlInject((String) params.get(Constant.ORDER_FIELD));
        String order = (String) params.get(Constant.ORDER);

        if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) {
            return page.addOrder(ASC.equalsIgnoreCase(order) ? OrderItem.asc(orderField) : OrderItem.desc(orderField));
        }

        if (StringUtils.isBlank(defaultOrderField)) {
            return page;
        }
        page.addOrder(isAsc ? OrderItem.asc(defaultOrderField) : OrderItem.desc(defaultOrderField));
        return page;
    }

}
