package com.zcxk.charge.web.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 *MongoDB查询分页方法
 * @author Andy
 **/
@Component
public class MongoDbUtil<T> {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * MongDb分页公共方法
     *
     * @param clazz    实体类的class对象
     * @param pageSize 每页的数量
     * @param pageNum  当前的页数
     * @param query    query是啥不知道赶紧去查下，相当于sql语句
     * @return
     */
    public Page<T> pagination(Class<T> clazz, long pageSize, long pageNum, Query query) {
        long total = this.mongoTemplate.count(query, clazz);
        Integer pages = (int) Math.ceil((double) total / (double) pageSize);
        if (pageNum <= 0 || pageNum > pages) {
            pageNum = 1;
        }
        long skip = pageSize * (pageNum - 1);
        query.skip(skip).limit(Math.toIntExact(pageSize));
        List<T> list = mongoTemplate.find(query, clazz);
        Page pageResult = new Page();
        pageResult.setTotal(total);
        pageResult.setCurrent(pageNum);
        pageResult.setSize(pageSize);
        pageResult.setRecords(list);
        return pageResult;
    }
}
