package com.haha.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.common.constant.CommonConstants;

import java.util.HashMap;
import java.util.Map;

/**
 * 分页工具类
 * 统一分页参数解析和结果构建
 */
public final class PageUtil {

    private PageUtil() {}

    /**
     * 从请求参数Map中解析分页参数
     *
     * @param params 请求参数Map
     * @return 包含 page 和 pageSize 的数组 [page, pageSize]
     */
    public static int[] parsePageParams(Map<String, Object> params) {
        int page = CommonConstants.DEFAULT_PAGE;
        int pageSize = CommonConstants.DEFAULT_PAGE_SIZE;

        if (params != null) {
            Object pageObj = params.get("page");
            if (pageObj != null && !pageObj.toString().isEmpty()) {
                try {
                    page = Integer.parseInt(pageObj.toString());
                    if (page < 1) {
                        page = CommonConstants.DEFAULT_PAGE;
                    }
                } catch (NumberFormatException ignored) {
                }
            }

            Object pageSizeObj = params.get("pageSize");
            if (pageSizeObj != null && !pageSizeObj.toString().isEmpty()) {
                try {
                    pageSize = Integer.parseInt(pageSizeObj.toString());
                    if (pageSize < 1 || pageSize > CommonConstants.MAX_PAGE_SIZE) {
                        pageSize = CommonConstants.DEFAULT_PAGE_SIZE;
                    }
                } catch (NumberFormatException ignored) {
                }
            }
        }

        return new int[]{page, pageSize};
    }

    /**
     * 构建分页结果Map
     *
     * @param pageResult MyBatis-Plus分页结果
     * @param page      当前页码
     * @param pageSize  每页条数
     * @param <T>       数据类型
     * @return 分页结果Map
     */
    public static <T> Map<String, Object> buildPageResult(IPage<T> pageResult, int page, int pageSize) {
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);
        return result;
    }
}
