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

namespace qcbase\controllers;

use qcbase\models\Auth;
use Yii;
use yii\helpers\Url;
use yii\data\ActiveDataProvider;
use qcbase\models\Menu;
use yii\db\Query;
use common\components\Tree;
use common\models\PermissionScope;
use common\models\User;
use yii\helpers\ArrayHelper;

/**
 * 角色控制器
 * 
 * 角色
 * 
 * @author hulimin http://blog.u-bo.com
 * @since 0.1
 */
class RoleController extends Controller
{
    public $model = '\qcbase\models\Auth';

    public function actions()
    {
        return [];
    }

    /**
     * 角色列表管理
     */
    public function actionIndex()
    {
        $roleList = Auth::getRoleList();

        $roleUser = User::getListByRole();

        foreach ($roleList as &$role) {
            $role['allUserStr'] = '';
            if (isset($roleUser[$role['name']]) && !empty($roleUser[$role['name']]['users'])) {
                $nameArr = ArrayHelper::getColumn($roleUser[$role['name']]['users'], 'realname');
                $role['allUserStr'] = implode(',', $nameArr);
            }
        }

        return $this->render('index', [
            'roleList' => $roleList
        ]);
    }

    /**
     * 新建角色
     */
    public function actionCreate()
    {
        $model = new Auth();
        $data = [];
        $request = Yii::$app->request;
        if ($model->load($request->post())) {
            $data = [
                'name' => $model->name,
                'description' => $model->description,
                'parent' => $request->post('parent'),
                'copy_role' => $request->post('copy_role'),
            ];
            $roles = $model->getRoles($model->name);
            if (empty($roles)) {
                if ($model->createRole(true, $data)) {
                    $result = 'success';
                    $message = '添加成功';
                } else {
                    $result = 'error';
                    $message = '角色添加失败';
                }
            } else {
                $result = 'error';
                $message = '角色名称已存在';
            }
            Yii::$app->getSession()->setFlash($result, $message);
            return $this->flash();
        }
        return $this->render('create', [
            'model' => $model, 
            'action' => ['role/create'],
            'parent' => [],
        ]);
    }

    /**
     * 编辑角色
     */
    public function actionView()
    {
        $authManager = Yii::$app->authManager;
        $model = new Auth();
        $request = Yii::$app->request;
        $id = Yii::$app->request->get('id');
        $roleIfo = $model->getRoles($id);
        $model = Auth::find()
            ->where(['type' => \yii\rbac\Item::TYPE_ROLE, 'name' => $id])
            ->one();
        if (empty($id) || !$model) {
            Yii::$app->getSession()->setFlash('error', '编辑的对象不存在');
            return $this->flash();
        }
        //获取父级
        $parent = (new Query)
            ->from($authManager->itemChildTable)
            ->where(['child' => $model->name])
            ->one();

        //var_dump($parent);
        return $this->render('create', [
            'model' => $model,
            'action' => ['role/update'],
            'parent' => $parent,
        ]);
    }

    /**
     * 更新角色
     */
    public function actionUpdate()
    {
        $model = new Auth();
        $data = [];
        $url = '';
        $request = Yii::$app->request;
        $id = Yii::$app->request->post('id');
        $count = Auth::find()
            ->where(['type' => \yii\rbac\Item::TYPE_ROLE, 'name' => $id])
            ->count();
        if (empty($id) || !$count) {
            Yii::$app->getSession()->setFlash('error', '要更新的对象不存在');
            return $this->flash();
        }
        if ($model->load($request->post())) {
            $data = [
                'name' => $model->name,
                'description' => $model->description,
                'parent' => $request->post('parent'),
                'old_parent' => $request->post('old_parent'),
                'old_role' => $request->post('old_role'),
            ];
            $countNew = Auth::find()
                ->where(['type' => \yii\rbac\Item::TYPE_ROLE, 'name' => $model->name])
                ->count();
            if ($countNew > 1) {
                $result = 'error';
                $message = '角色名已存在';
                $url = ['url' => ['role/view', 'id' => $id]];
            } else {
                if ($model->createRole(FALSE, $data, $id)) {
                    $result = 'success';
                    $message = '更新成功';
                    $url = ['url' => ['role/view', 'id' => $model->name]];
                } else {
                    $result = 'error';
                    $message = '更新失败';
                    $url = ['url' => ['role/view', 'id' => $id]];
                }
            }
            Yii::$app->getSession()->setFlash($result, $message);
            return $this->flash($url);
        }
        return $this->render($this->view, [
            'model' => $model,
            'action' => ['role/update'],
        ]);
    }

    /**
     * 角色删除
     */
    public function actionDelete()
    {
        $model = new Auth();
        $request = Yii::$app->request;
        $id = Yii::$app->request->get('id');
        $model = Auth::find()
            ->where(['type' => \yii\rbac\Item::TYPE_ROLE, 'name' => $id])
            ->one();
        if (empty($id) || !$model) {
            $result = 'error';
            $message = '要删除的对象不存在';
        } else {
            if ($model->delete()) {
                //删除角色的权限范围
                Yii::$app->db->createCommand()->delete(
                    '{{%role_permission_scope}}',
                    'role = :role',
                    [':role' => $model->name]
                )->execute();
                $result = 'success';
                $message = '删除成功';
            } else {
                $result = 'error';
                $message = '删除失败';
            }
        }
        Yii::$app->getSession()->setFlash($result, $message);
        return $this->flash();
    }

    /**
     * 显示节点菜单
     */
    public function actionShowAuthMenu()
    {
        $request = Yii::$app->request;

        $app_name = $request->get('app_name');
        //$role 非空时对据说授权
        $role = $request->get('role');
        //$user_id 非空时对用户授权
        $user_id = $request->get('user_id');

        $authList = [];
        $appArr = Menu::getAppList();
        $authList = Menu::getAuthTree($app_name, $role, 'menu_id');
        $roleScopes = PermissionScope::getRoleScope($role);

        //\common\components\Tool::dump($authList);
        //exit();


        return $this->render('auth-menu', [
            'app_name' => $app_name,
            'authList' => $authList,
            'app_list' => $appArr,
            'role' => $role,
            'user_id' => $user_id,
            'roleScopes' => $roleScopes,
        ]);
    }

    /**
     * 给角色,用户授权
     */
    public function actionAuth()
    {
        $request = Yii::$app->request;
        $role = $request->post('role');
        $app_name = $request->post('app_name');
        $permissions = $request->post('permissions', []);
        $permission_scopes = $request->post('permission_scopes', []);
        //\common\components\Tool::dump($permission_scopes);
        //exit();
        //数据校验
        if (empty($role) || empty($app_name)) {
            return $this->flash('缺少参数', 'error');
        }

        if (Auth::authRole($app_name, $role, $permissions) && Auth::authScope($app_name, $role, $permissions, $permission_scopes)) {
            return $this->flash('授权成功', 'success');
        }
        else {
            return $this->flash('授权失败', 'error');
        }

    }
}
