<?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\Job;
use common\components\CHelper;

class JobController extends Controller
{

    public function behaviors()
    {
        $pagecache = \common\models\Pagecache::getCache();
        return [
            [
                'class' => 'yii\filters\PageCache',
                'enabled'=>$pagecache['job']['status']==1?true:false,
                'only' => ['index'],
                'duration' => $pagecache['job']['time'],
                'variations'=>[Yii::$app->request->get('page')],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT * FROM '.Yii::$app->db->tablePrefix.'job',
                ],
            ],
            [
                'class' => 'yii\filters\PageCache',
                'enabled'=>$pagecache['job_detail']['status']==1?true:false,
                'only' => ['detail'],
                'duration' => $pagecache['job_detail']['time'],
                'variations'=>[Yii::$app->request->get('id')],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT * FROM '.Yii::$app->db->tablePrefix.'job 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 = Job::find()->andWhere(['display'=>1]);
        $list = $data->asArray()->orderBy('id desc')->all();
        $list = $this->_format_list($list);
        return $this->render('index',[
            'list'=>$list,
            'category' => $category,
        ]);
    }
    public function actionDetail($id){
        $model = $this->findModel($id);
        return $this->render('detail',[
            'model'=>$model,
        ]);
    }
    protected function findModel($id)
    {
        if (($model = Job::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'],100);
            $list[$key]['url'] = Yii::$app->urlManager->createUrl(['job/detail','id'=>$value['id']]);
        }
        return $list;
    }
}
