package com.njzscloud.common.mp.support;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

import java.util.Collections;
import java.util.List;

/**
 * 分页结果类
 */
@Getter
@Setter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class PageResult<T> {

    private final List<T> records;

    /**
     * 总数
     */
    private final Integer total;

    /**
     * 总页数
     */
    private final Integer pages;

    /**
     * 当前页
     */
    private final Integer current;

    /**
     * 每页显示条数，默认 10
     */
    private final Integer size;


    public static <E> PageResult<E> of(IPage<E> page) {
        return new PageResult<>(page.getRecords(), (int) page.getTotal(), (int) page.getPages(), (int) page.getCurrent(), (int) page.getSize());
    }

    public static <E> PageResult<E> of(PageParam pageParam, List<E> data) {
        Integer current_ = pageParam.getCurrent();
        Integer size_ = pageParam.getSize();
        int current = current_ == null ? 1 : current_;
        int size = size_ == null ? 500 : size_;
        if (data == null) data = Collections.emptyList();
        int total = data.size();
        int pages = Math.toIntExact(total % size == 0 ? (total / size) : (total / size + 1));
        PageUtil.setFirstPageNo(1);
        return new PageResult<>(ListUtil.page(current, size, data), total, pages, current, size);
    }

}
