<?php
namespace app\admin\controller;
use app\admin\model\PermissionModel;
use app\admin\model\StaffRoleModel;
use think\Controller;
use think\facade\Cookie;
use think\facade\Request;

/**
 * 控制器基类
 * 验证用户是否登录，
 * 验证用户的管理权限
 * Class Base
 * @package app\admin\controller
 */

class Base extends Controller
{
    //登录检测
    protected function initialize(){
        $this->check();
    }

    private function check(){

        dd("123");
        $single = new SingleSign();
        try {
            $user = $single->getUserInfo();
            Cookie::set('user',$user['ukey']);
            $user['user_id'] = $single->getUserId($user);
            session('user', $user);
            $sUser['name']  = $user['name'];
            $sUser['is_admin'] = $user['is_admin'] === true ? true : false;
            $sUser['user_id'] = $user['user_id'];

            //保存加密串到redis
            $single->saveKey($user['ukey'],$sUser);
        } catch ( \Exception $e){
            $this->redirect('/login');
        }
        if(!$user['is_admin']){
            $this->authCheck($user['user_id']);
        }
    }

    //检测当前用户对当前url是否具备权限
    private function authCheck($user_id){
        //通过uid查询roleid通过roleid查询权限列表
        $permissions = StaffRoleModel::getStaffRolesById($user_id);

        $permissions = explode(',',$permissions);

        //获取当前访问路由
        $path = Request::pathinfo() ?: '/';

        if($path !== '/'){
            //检测是否存在数字,如果存在数字则删除最后一个/之后的所有数据
            if(preg_match('/[0-9]+/',$path)){
                $path = substr($path,0,strrpos($path,'/'));
            }
            //过滤权限
            if($path != 'reset'){
                //查询当前路由信息
                $permission = PermissionModel::field('id,nav_url')->get(['nav_url'=>$path]);

                if(isset($permission->id)){
                    if(!in_array($permission->id,$permissions) || $permission == null){
                        $this->error('你没有访问'.$path."操作的权限",'/','close',2);
                    }
                } else {
                    $this->error($path,'/','close',2);
                }
            }
        }
    }
}
