<?php

namespace app\traits\cms;

use app\model\Archives;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Paginator;

trait ArticleTrait
{
    /**
     * 获取指定栏目下文章列表
     *
     * @param  int  $cateId
     * @param  int  $pageSize
     * @param  string  $keywords
     * @return Paginator
     */
    public function getArticleByCateIdWithPaginate(int $cateId, int $pageSize = 20, string $keywords = ''): Paginator
    {
        return Archives::getListPageByCategory($cateId, $pageSize, $keywords);
    }

    /**
     * 获取指定栏目下文章列表
     *
     * @param  int  $cateId
     * @param  int  $pageSize
     * @return array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getArticleListByCateId(int $cateId, int $pageSize = 20)
    {
        return Archives::getListByCategory($cateId, $pageSize, true);
    }

    /**
     * 获取文章 本身+上一篇+下一篇
     *
     * @param  int  $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function nearbyArticle(int $id): array
    {
        $article        = Archives::findById($id);
        $res['prev']    = Archives::getPrevArticleByIdAndCategoryId($id, $article['category_id']) ?: [];
        $res['next']    = Archives::getNextArticleByIdAndCategoryId($id, $article['category_id']) ?: [];
        $res['oneself'] = $article ?: [];
        return $res;
    }
}