<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace qcbase\actions;

use Yii;
use yii\data\ActiveDataProvider;

/**
 * 后台公用的首页动作类
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Index extends \yii\base\Action
{
	/**
	 * @var string 当前操作模型
	 */
    public $model;
	/**
	 * @var string 当前视图
	 */
    public $view = 'index';
	/**
	 * @var array 关联with 
	 */
	public $with;
	/**
	 * @var array 排序 
	 */
	public $order;

    public function run()
    {
		$this->model === null && $this->model = $this->controller->model;

		$query = call_user_func([$this->model, 'find']);

		//排序，默认按照索引倒序排列
		if ($this->order !== null) {
			$query->orderBy($this->order);
		}
		elseif($pks = call_user_func([$this->model, 'primaryKey'])) {
			$query->orderBy([$pks[0] => SORT_DESC]);
		}

		if ($this->with !== null) {
			foreach ($this->with as $with) {
				$query->with($with);
			}
		}

		//搜索
		$request = Yii::$app->request;
		$keywords = $request->get('keywords');
		if (!empty($keywords)) {
			$field = $request->get('search_field');
			$query->where(['like', $field, $keywords]);
		}

		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 20,
			],
		]);
	
        return $this->controller->render($this->view, [
			'get' => $request->get(),
			'model' => new $this->model,
			'models' => $provider->models,
			'pages' => $provider->pagination,
		]);
    } 
		
}
