<?php
namespace app\model;

class Article extends Base
{
    //获取最高访问的文章列表
    public static function getMostVisited($limit = 5)
    {
        if($limit <= 0){
            $limit = 5;
        }
        return self::order('views', 'desc')
        ->limit($limit)
        ->select()
        ->toArray();
    }
    //获取栏目下最新记录
    public static function getLatestByCategory($categoryId, $limit = 5, $status = -1, $order = [])
    {
        if(empty($categoryId)){
            return [];
        }
        $whereMap = [];
        if($limit <= 0){
            $limit = 5;
        }
        if(is_numeric($status) && $status != -1){
            $whereMap[] = ['status', '=',  $status];
        }
        if(empty($order)) {
            $order = ['create_time' => 'desc'];
        }
        return self::where('category_id', $categoryId)
        ->where($whereMap)
        ->order($order)
        ->limit($limit)
        ->select()
        ->toArray();
    }

    /**
     * 根据文章ID和栏目ID获取下一篇文章
     * @param int $id 当前文章ID
     * @param array $categoryIds 当前文章栏目IDs
     * @param bool $orderSort 是否以“sort”字段排序
     * @param int $currentSort 当前文章的排序号
     * @param bool $sortDesc 是否以sort字段倒叙排列
     * @return array
     */
    public static function getNextArticleByIdAndCategories($id, $categoryIds, $orderSort = false, $currentSort = 0, $sortDesc = false)
    {
        $whereMap  = [];
        if($orderSort && $currentSort > 0) {
            if($sortDesc) {
                $whereMap[] = ['sort', '<', $currentSort];
                $order = ['sort'=> 'desc'];
            } else {
                $whereMap[] = ['sort', '>', $currentSort];
                $order = ['sort'=> 'asc'];
            }
        } else {
            $whereMap[] = ['id', '>', $id];
            $order = ['id'=> 'asc'];
        }
        return self::where($whereMap)
        ->whereIn('category_id', $categoryIds)
        ->where('status', 1)
        ->order($order)
        ->findOrEmpty()
        ->toArray();
    }

    /**
     * 根据文章ID和栏目ID获取上一篇文章
     * @param int $id 当前文章ID
     * @param array $categoryIds 当前文章栏目IDs
     * @param bool $orderSort 是否以“sort”字段排序
     * @param int $currentSort 当前文章的排序号
     * @param bool $sortDesc 是否以sort字段倒叙排列
     * @return array
     */
    public static function getPrevArticleByIdAndCategories($id, $categoryIds, $orderSort = false, $currentSort = 0, $sortDesc = false)
    {
        $whereMap  = [];
        if($orderSort && $currentSort > 0) {
            if($sortDesc) {
                $whereMap[] = ['sort', '>', $currentSort];
                $order = ['sort'=> 'asc'];
            } else {
                $whereMap[] = ['sort', '<', $currentSort];
                $order = ['sort'=> 'desc'];
            }
        } else {
            $whereMap[] = ['id', '<', $id];
            $order = ['id'=> 'desc'];
        }
        return self::where($whereMap)
        ->whereIn('category_id', $categoryIds)
        ->where('status', 1)
        ->order($order)
        ->findOrEmpty()
        ->toArray();
    }
    //根据栏目ID获取文章列表
    public static function getListByCategory($categoryId, $limit = 10)
    {
        return self::where('category_id', $categoryId)
        ->where('status', 1)
        ->order("sort desc")
        ->limit($limit)
        ->select()
        ->toArray();
    }
    //根据栏目ID获取文章分页列表
    public static function getListPageByCategory($categoryId, $per = 20, $keyword = '')
    {
        $where = [
            ['category_id', '=', $categoryId],
            ['status', '=', 1],
        ];
        $param['category_id'] = $categoryId;
        if($keyword!=''){
            $where[] = ['title', 'like', '%'.$keyword.'%'];
            $param['keyword'] = $keyword;
        }
        $paginate = [
            'list_rows' => $per,
            'query' => $param
        ];
        return self::where($where)
        ->order("sort desc")
        ->paginate($paginate,false);
    }

    public static function onAfterInsert($article)
    {
        $article->sort = $article->id;
        $article->create_time = $article->update_time = time();
        $auth = session('auth');
        $article->created = $article->updated = $auth['userName'];
        $article->save();
    }

    /**
     * 获取文章列表
     * @param $categoryId 分类ID
     * @param int $per 每页数量
     * @param string $keyword 关键词
     * @param array $param 文章类型:置顶、热门、推荐 ['top','hot','recommend']
     * @param int $status 文章状态,-1表示不限制
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getList($categoryId, $per = 20, $keyword = '', $param = [], $status = -1)
    {
        $whereMap = [];
        $pageParam = [];
        if(is_numeric($categoryId) && $categoryId > 0) {
            $whereMap[] = ['category_id', '=', $categoryId];
            $pageParam['category_id'] = $categoryId;
        }
        if(!empty($keyword)){
            $whereMap[] = ['title', 'like',  '%'.$keyword.'%'];
            $pageParam['keyword'] = $keyword;
        }
        if (is_array($param) && count($param) > 0) {
            $pageParam['param'] = $param;
            foreach ($param as $vo) {
                if(in_array($vo, ['top','hot','recommend'], true)) {
                    $whereMap[] = ["{$vo}", '=', 1];
                }
            }
        }
        if(is_numeric($status) && $status != -1){
            $whereMap[] = ['status', '=',  $status];
            $pageParam['status'] = $status;
        }
        $paginate = [
            'list_rows' => $per,
            'query' => $pageParam
        ];
        return self::when(count($whereMap) > 0, function($query) use ($whereMap) {
                $query->where($whereMap);
            })
            ->order("sort desc")
            ->paginate($paginate,false);
    }

    //获取文章涉及到的图片
    public static function getFilesInUse()
    {
        $items = self::select()->toArray();
        $data = [];
        foreach($items as $item){
            $src = trim($item['src']);
            if(!empty($src)){
                $key = getKeyByPath($src);
                $data[$key] = $src;
            }
            $imgs = getImageUrlFromText($item['content']);
            if(!empty($imgs)){
                $data = array_merge($data, $imgs);
            }
            $videos = getVideoUrlFromText($item['content']);
            if(!empty($videos)){
                $data = array_merge($data, $videos);
            }
        }
        return $data;
    }

    // 查询栏目下的文章
    public static function getListByCategoryIds($categoryIds, $per = 20, $keyword = '', $param = [], $status = -1, $order = [])
    {
        $whereMap = [];
        if(is_array($categoryIds) && count($categoryIds) > 0) {
            $whereMap[] = ['category_id', 'in', $categoryIds];
        }
        if(!empty($keyword)){
            $whereMap[] = ['title', 'like',  '%'.$keyword.'%'];
        }
        if (is_array($param) && count($param) > 0) {
            foreach ($param as $vo) {
                if(in_array($vo, ['top','hot','recommend'], true)) {
                    $whereMap[] = ["{$vo}", '=', 1];
                }
            }
        }
        if(is_numeric($status) && $status != -1){
            $whereMap[] = ['status', '=',  $status];
        }
        if(empty($order)) {
            $order = ['sort'=>'desc'];
        }
        return self::when(count($whereMap) > 0, function($query) use ($whereMap) {
            $query->where($whereMap);
        })
        ->order($order)
        ->limit($per)
        ->select()
        ->toArray();
    }

    //根据栏目IDs获取文章分页列表
    public static function getListPageByCategories($categoryIds, $per = 20, $keyword = '',  $order = [])
    {
        $param = [];
        $where = [
            ['category_id', 'in', $categoryIds],
            ['status', '=', 1],
        ];
        if($keyword!=''){
            $where[] = ['title', 'like', '%'.$keyword.'%'];
            $param['keyword'] = $keyword;
        }
        $paginate = [
            'list_rows' => $per,
            'query' => $param
        ];
        if(empty($order)) {
            $order = ['sort'=>'desc'];
        }
        return self::where($where)
            ->order($order)
            ->paginate($paginate,false);
    }
}