package com.tmerclub.cloud.common.mongodb.util;

import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.util.PageUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * mongoDB分页工具
 * @author CDT
 */
@Component
public class MongoPageUtil {

    private static final Logger logger = LoggerFactory.getLogger(MongoPageUtil.class);

    private final MongoTemplate mongoTemplate;

    @Autowired
    public MongoPageUtil(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    public <T> PageVO<T> doPage(Class<T> clazz, PageDTO mongoPageDTO, Query query) {
        long total = mongoTemplate.count(query, clazz);

        int skip = mongoPageDTO.getPageSize() * (mongoPageDTO.getPageNum() - 1);
        query.skip(skip).limit(mongoPageDTO.getPageSize());

        logger.info("构建MongoPageUtil查询语句： {}", query);

        List<T> list = mongoTemplate.find(query, clazz);

        PageVO<T> mongoPageVO = new PageVO<>();
        mongoPageVO.setTotal(total);
        mongoPageVO.setList(list);
        mongoPageVO.setPages(PageUtil.getPages(total, mongoPageDTO.getPageSize()));
        return mongoPageVO;
    }
}

