package com.xxfc.platform.uccn.biz;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.uccn.entity.Article;
import com.xxfc.platform.uccn.mapper.ArticleMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.util.*;


/**
 * @author Administrator
 */
@Service
public class ArticleBiz extends BaseBiz<ArticleMapper, Article> {
    /**
     * 随机文章条数
     */
    private final Integer RANDOM_NUMBER=3;

    /**
     * 首页文章条数
     */
    private final Integer HOME_PAGE_NUMBER=4;


    /**
     * 文章列表
     * @param page
     * @param limit
     * @param type
     * @return
     */
    public PageInfo getArticleList(Integer page, Integer limit, Integer type) {
        PageHelper.startPage(page, limit);
        List articleList = mapper.getArticleList(type);
        return PageInfo.of(articleList);
    }

    /**
     *  获取一条数据
     * @param id
     * @return
     */
    public Article getOne(Integer id) {
        Example example = Example.builder(Article.class).where(
                WeekendSqls.<Article>custom()
                        .andEqualTo(Article::getId,id)
                        .andEqualTo(Article::getIsDel, 0)
                        .andEqualTo(Article::getStatus, 1)
        ).build();
        Article article = mapper.selectOneByExample(example);
        return article;
    }


    /**
     * 随机获取三条连续的文章
     * @param type
     * @return
     */
    public List getThree(Integer type) {

        List<Article> articleList = mapper.getArticleList(type);
        if (!Objects.isNull(articleList)) {
            int size = articleList.size();
            if (RANDOM_NUMBER>=size) {
                return articleList;
            }else {
                Random random = new Random();
                int r = random.nextInt(size -RANDOM_NUMBER+1);
                List<Article> result = new ArrayList<>();
                for (int i=0;i<RANDOM_NUMBER.intValue();i++){
                    int index= i+r;
                    result.add(articleList.get(index));
                }
                return result;
            }
        }
        return new ArrayList();
    }


    /**
     * 首页文章列表
     * @param type
     * @return
     */
    public List getHomePageArticle(Integer type){
        List<Article> articleList = mapper.getArticleList(type);
        if (Objects.isNull(articleList)) {
            return new ArrayList();
        }else {
            if (articleList.size()>HOME_PAGE_NUMBER) {
                return articleList.subList(0,HOME_PAGE_NUMBER);
            }else {
                return articleList;
            }
        }
    }

}
