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

namespace common\models;

use Yii;
use yii\db\Query;
use qcbase\models\Auth;
use common\models\User;
use yii\helpers\ArrayHelper;

/**
 * 权限范围模型
 * This is the model class for table "{{%role_permission_scope}}".
 *
 * @property string $role 角色
 * @property string $permission 权限
 * @property integer $scope 范围
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class PermissionScope extends \yii\db\ActiveRecord
{
    const SCOPE_ALL = 1; //所有人范围
    const SCOPE_SELF = 2; //仅自己范围
    const SCOPE_DEPT = 3; //本部门范围
    const SCOPE_ROLE = 4; //自己和下属范围

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%role_permission_scope}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['role', 'permission', 'scope'], 'required'],
            [['scope'], 'integer'],
            [['role', 'permission'], 'string', 'max' => 64]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'role' => '角色',
            'permission' => '权限',
            'scope' => '范围',
        ];
    }

    /**
     * 返回权限数据范围
     */
    public static function getScopes()
    {
        $scopes = [
            self::SCOPE_ALL => ['name' => '所有', 'value' => self::SCOPE_ALL],
            self::SCOPE_SELF => ['name' => '仅自己', 'value' => self::SCOPE_SELF],
            self::SCOPE_DEPT => ['name' => '部门所有', 'value' => self::SCOPE_DEPT],
            self::SCOPE_ROLE => ['name' => '自己和下属', 'value' => self::SCOPE_ROLE],
        ];
        return $scopes;
    }

    /**
     * 获取某个角色的权限范围
     *
     * @param string $role 角色名称
     */
    public static function getRoleScope($role)
    {
        $scopes = (new Query)
            ->from(self::tableName())
            ->where(['role' => $role])
            ->indexBy('permission')
            ->all();

        return $scopes;
    }

    /**
     * 获取当前用户对应权限的范围所包含的用户
     *
     * @param string $permission 权限名称
     * @return array 返回权限范围内的用户，如果为空数组，则代表可以查看全部
     */
    public static function getScopeUser($permission, $userId = null)
    {
        $userId = ($userId === null) ? Yii::$app->user->id : $userId;
        $user = [];
        if (Yii::$app->session->get('isSuperAdmin')) {
            return $user;
        }

        //获取用户的角色
        $roles = Auth::getRolesByUser($userId);
        $roles = array_keys($roles);

        //获取对应角色对应权限的范围控制
        $scopes = static::find()
            ->select('scope')
            ->where(['role' => $roles, 'permission' => $permission])
            ->asArray()
            ->column();

        //如果根本没有设置权限的范围则返回false
        if (empty($scopes)) {
            return false;
        }
        //把所有角色的权限范围放到一个数组里，方便多个范围判断
        $scopes = array_unique($scopes);

        //如果有查看所有人范围直接返回
        if (in_array(self::SCOPE_ALL, $scopes)) {
            return $user;
        }

        if (in_array(self::SCOPE_SELF, $scopes)) {
            $user[] = $userId;
        }

        if (in_array(self::SCOPE_DEPT , $scopes)) {
            $user[] = $userId;
            $user = array_merge($user, User::getScopeDeptUsers($userId));
        }

        if (in_array(self::SCOPE_ROLE , $scopes)) {
            $user[] = $userId;
            $user = array_merge($user, User::getScopeRoleUsers($userId));
        }

        $user = array_unique($user);
        //\common\components\Tool::dump($user);

        return $user;
    }

    /**
     * 获取用户某个权限的数据范围
     *
     * @param string $permission 权限名称
     * @param int $userId 用户id
     */
    public static function getUserPermissionScope($permission, $userId = null)
    {
        $userId = ($userId === null) ? Yii::$app->user->id : $userId;

        //获取用户的角色
        $roles = Auth::getRolesByUser($userId);
        $roles = array_keys($roles);

        //获取对应角色对应权限的范围控制
        $scopes = static::find()
            ->select('scope')
            ->where(['role' => $roles, 'permission' => $permission])
            ->asArray()
            ->column();
        $scopes = array_unique($scopes);
        return $scopes;
    }

}
