<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */
namespace frontendApi\modules\v1\controllers;

use common\models\Article;
use common\models\ArticleCategory;

class ArticleController extends BaseController
{
    public $modelClass = Article::class;

    /**
     * 返回所有分类并带5条新闻
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionIndex(){
        $news=ArticleCategory::find()->select('ID,CATE_NAME')->asArray()->all();
        foreach ($news as &$value){
            $value['LISTS']=Article::find()->select('ID,TITLE,CID,CREATED_AT')->where('CID=:CID AND STATUS=1',[':CID'=>$value['ID']])->orderBy('CREATED_AT DESC')->limit(5)->asArray()->all();
        }
        return static::notice($news);
    }


    /**
     * 文章分类
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionCategory(){
        return static::notice(ArticleCategory::getAllCategory());
    }

    /**文章前10条列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionGetNewArticle(){
        $data = Article::find()->select('ID,TITLE,CID,CREATED_AT')->where('STATUS=1')->orderBy('CREATED_AT DESC')->limit(10)->asArray()->all();
        return static::notice($data);
    }

    /**
     * 文章列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionList(){
        $cid = \Yii::$app->request->get('cid');
        $condition = ' AND STATUS=1';
        $params = [];
        if($cid){
            $condition .= ' AND CID=:CID';
            $params[':CID'] = $cid;
        }
        $data = Article::lists($condition, $params, [
            'select' => 'ID,TITLE,CID,CREATED_AT',
            'orderBy' => 'CREATED_AT DESC',
            'useSlaves' => true,
        ]);
        // 全部分类
        $data['allCategory'] = ArticleCategory::getAllCategory();
        return static::notice($data);
    }

    /**
     * 获取文章详细
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDetail(){
        $id = \Yii::$app->request->get('id');
        $data = null;
        if($id){
            $data = Article::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=>$id], 'ID,TITLE,CID,CREATED_AT');
        }
        if($data){
            // 暂时先从文件中取内容
            $path = \Yii::getAlias('@common/runtime/articleContent/').$data['ID'];
            if(!file_exists($path)){
                $data['CONTENT'] = '';
            } else {
                $data['CONTENT'] = file_get_contents($path);
            }
            return static::notice($data);
        } else {
            return static::notice('文章不存在', 400);
        }
    }
}