<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Controller;
use yii\data\Pagination;
use common\models\Article;
use common\models\ArticleCategory;
use common\components\CHelper;

class NewsController extends Controller
{

    public function behaviors()
    {
        $pagecache = \common\models\Pagecache::getCache();
        return [
            [
                'class' => 'yii\filters\PageCache',
                'enabled'=>$pagecache['news']['status']==1?true:false,
                'only' => ['index'],
                'duration' => $pagecache['news']['time'],
                'variations'=>[Yii::$app->request->get('page')],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT count(*) FROM '.Yii::$app->db->tablePrefix.'article',
                ],
            ],
            [
                'class' => 'yii\filters\PageCache',
                'enabled'=>$pagecache['news_list']['status']==1?true:false,
                'only' => ['list'],
                'duration' => $pagecache['news_list']['time'],
                'variations'=>[Yii::$app->request->get('cid'),Yii::$app->request->get('page')],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT count(*) FROM '.Yii::$app->db->tablePrefix.'article',
                ],
            ],
            [
                'class' => 'yii\filters\PageCache',
                'enabled'=>$pagecache['news_detail']['status']==1?true:false,
                'only' => ['detail'],
                'duration' => $pagecache['news_detail']['time'],
                'variations'=>[Yii::$app->request->get('id')],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT updatetime FROM '.Yii::$app->db->tablePrefix.'article where `id`='.Yii::$app->request->get('id'),
                ],
            ],
        ];
    }
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $category = '新闻中心';
        $data = Article::find()->andWhere(['display'=>1]);
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 10,'defaultPageSize'=>10]);
        $list = $data->asArray()->offset($pages->offset)->orderBy('ordid desc,updatetime desc,id desc')->limit($pages->limit)->all();
        $list = $this->_format_list($list);
        return $this->render('index',[
            'list'=>$list,
            'pages' => $pages,
            'category' => $category,
        ]);
    }
    public function actionList($cid)
    {
        $category = ArticleCategory::getCache($cid);
        $data = Article::find()->andWhere(['cid'=>$cid,'display'=>1]);
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 10,'defaultPageSize'=>10]);
        $list = $data->asArray()->offset($pages->offset)->orderBy('ordid desc,updatetime desc,id desc')->limit($pages->limit)->all();
        $list = $this->_format_list($list);
        return $this->render('index',[
            'list'=>$list,
            'pages' => $pages,
            'category' => $category,
        ]);
    }
    public function actionDetail($id){
        $model = $this->findModel($id);
        return $this->render('detail',[
            'model'=>$model,
        ]);
    }
    protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    private function _format_list($list){
        foreach ($list as $key => $value) {
            $list[$key]['brief'] = strip_tags($value['content']);
            $list[$key]['brief'] = CHelper::cutStr($list[$key]['brief'],80);
            if($list[$key]['url']){
                $list[$key]['target'] = "_blank";
            }else{
                $list[$key]['url'] = Yii::$app->urlManager->createUrl(['news/detail','id'=>$value['id']]);
                $list[$key]['target'] = "_self";
            }
            $list[$key]['thumb'] = $value['thumb']?CHelper::attach($value['thumb'],'article/thumb'):RESOURCE_DIR.Yii::$app->params['news_no_thumb'];
        }
        return $list;
    }
}
