package com.corewing.app.common.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PageInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 默认分页参数
        int pageNum = 1;
        int pageSize = 10;

        // 从请求参数中获取分页信息
        String current = request.getParameter("current");
        String size = request.getParameter("size");

        // 解析页码
        if (current != null && !current.isEmpty()) {
            try {
                pageNum = Integer.parseInt(current);
                if (pageNum < 1) pageNum = 1; // 页码不能小于1
            } catch (NumberFormatException e) {
                // 非法参数使用默认值
            }
        }

        // 解析每页条数
        if (size != null && !size.isEmpty()) {
            try {
                pageSize = Integer.parseInt(size);
                if (pageSize < 1) pageSize = 10; // 每页条数不能小于1
                if (pageSize > 100) pageSize = 100; // 限制最大条数
            } catch (NumberFormatException e) {
                // 非法参数使用默认值
            }
        }

        // 创建 MyBatis-Plus 的 Page 对象并存储到 ThreadLocal
        Page<?> page = new Page<>(pageNum, pageSize);
        PageContext.setPage(page);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除ThreadLocal中的数据，防止内存泄漏
        PageContext.clear();
    }
}
