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

namespace home\actions;

use Yii;
use yii\data\ActiveDataProvider;
use common\models\Common;
use common\models\PermissionScope;

/**
 * 前台公用的首页动作类
 * 
 * @author Strief 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;
	/**
	 * @var string 当前操作所渲染的布局 
	 */
	public $layout;
	/**
	 * @var array 筛选
	 */
	public $map;
    /**
	 * @var bool 是否开启权限范围控制
	 */
	public $enableScopeAccess = true;
    /**
	 * @var array 范围控制字段,默认有user_id，如果有多个，采用or的关系
     */
    public $scopeAccessFields = ['user_id'];


    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);
			}
		}

		if ($this->map !== null) {
			$query->where($this->map);	
		}

        //权限范围过滤
        if ($this->enableScopeAccess) {
            $permission = Common::getActionPermission($this);
            $scopeUser = PermissionScope::getScopeUser($permission);
            if (!empty($scopeUser)) {
                $scopeMap = [];
                foreach($this->scopeAccessFields as $field) {
                    $scopeMap[] = [$field => $scopeUser];
                }
                $query->andWhere(array_merge(['or'], $scopeMap));
            }
        }


		//搜索
		$request     = Yii::$app->request;
		$category_id = $request->get('category_id');  //yxd 20141127增加  主表里面的类型id

		$keywords    = trim($request->get('keywords'));
		$status      = $request->get('status');
		$field       = $request->get('search_field');

		if (!empty($keywords) && !empty($field)) {
			$query->andwhere(['like', $field, $keywords]);
		}
		if ($status != '') {
			$query->andWhere(['status' => (int)$status]);
		}
        if (!empty($category_id)) {
			$query->andWhere("FIND_IN_SET(category_id,:ids)", [':ids' => $category_id]);
		}

		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 15,
			],
		]);

		//修改当前动作的布局
		if($this->layout !== null){
			$this->controller->layout = $this->layout;
		}
	
        return $this->controller->render($this->view, [
			'get' => $request->get(),
			'model' => new $this->model,
			'models' => $provider->models,
			'pages' => $provider->pagination,
		]);
    } 
		
}
