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

namespace home\actions;

use Yii;
use common\models\Common;
use common\models\PermissionScope;

/**
 * 前台公用的查看动作类
 * 
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */

class View extends \yii\base\Action
{
	/**
	 * @var class 当前操作所属模型 
	 */
    public $model; 
	/**
	 * @var string 当前操作视图名称
	 */
    public $view = 'create';
	/**
	 * @var string 模型的场景 
	 */
	public $scenario = 'default';
	/**
	 * @var string 当前操作所渲染的布局 
	 */
	public $layout;
    /**
	 * @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;

		$id = (int)Yii::$app->request->get('id');
		if (empty($id) || !$model = call_user_func([$this->model, 'findOne'] ,$id)) {
			Yii::$app->getSession()->setFlash('error', '编辑的对象不存在');
			return $this->controller->flash();
		}

        //权限范围过滤
        if ($this->enableScopeAccess) {
            $permission = Common::getActionPermission($this);
            $scopeUser = PermissionScope::getScopeUser($permission);
            $canView = false;
            if (!empty($scopeUser)) {
                foreach($this->scopeAccessFields as $field) {
                    if (in_array($model->$field, $scopeUser)) {
                        $canView = true;
                        break;
                    }
                }
            }
            else {
                $canView = true;
            }
            if (!$canView) {
                Yii::$app->getSession()->setFlash('error', '没有权限编辑');
                return $this->controller->flash();
            }
        }

        $model->scenario = $this->scenario;

		//修改当前动作的布局
		if ($this->layout !== null) {
			$this->controller->layout = $this->layout;
		}

        return $this->controller->render($this->view, [
			'model' => $model,
			'action' => [$this->controller->id.'/update'],
		]);
    } 
		
}
