package com.uas.search.jms;

import com.uas.search.constant.model.SPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 消息
 *
 * @author sunyj
 * @since 2017/10/11 17:33
 */
@Service
public class LuceneMessageServiceImpl implements LuceneMessageService {

    /**
     * 默认的页码
     */
    private static final int PAGE_INDEX = 1;

    /**
     * 默认每页的大小
     */
    private static final int PAGE_SIZE = 20;

    @Autowired
    private LuceneMessageDao luceneMessageDao;

    @Override
    public SPage<LuceneMessage> findAll(Integer page, Integer size) {
        // 处理分页信息
        if (page == null || page <= 0) {
            page = PAGE_INDEX;
        }
        if (size == null || size <= 0) {
            size = PAGE_SIZE;
        }

        SPage<LuceneMessage> sPage = new SPage<>();
        long totalElement = luceneMessageDao.count();
        sPage.setTotalElement(totalElement);
        // 总数目为0，返回
        if (totalElement == 0) {
            return sPage;
        }

        int totalPage = (int) Math.ceil(totalElement / (1.0 * size));
        sPage.setTotalPage(totalPage);
        // 如果页码过大
        if (page > totalPage) {
            page = totalPage;
        }
        int start = (page - 1) * size;
        sPage.setPage(page);
        sPage.setSize(size);
        if (page == 1) {
            sPage.setFirst(true);
        }
        if (page == totalPage) {
            sPage.setLast(true);
        }
        List<LuceneMessage> messages = luceneMessageDao.findList(start, size);
        sPage.setContent(messages);
        return sPage;
    }
}
