<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
class Role extends BaseModel {
	protected $table = "dc_role";
	public $timestamps = false;

    //权限检测
    protected function hasRoot($code){
        //是否开启权限校验
        $status=intval(S("ENABLED_PRIVCHECK"))?intval(S("ENABLED_PRIVCHECK")):0;

        if($status<1){
            return 1;
        }
        //获取所有的权限代码
        //读取存储权限，若没有则查询
        $ROLE_CODES=S('ROLE_CODES');
        if($ROLE_CODES<0){
            $ROLE_CODES=\App\Models\Priv_codeModel::getAllcode();
            S("ROLE_CODES",$ROLE_CODES);
        }

        //不控制的权限通过
        if(!in_array($code,$ROLE_CODES)){
            return 1;
        }

        $admin_id=session('adminInfo.admin_id');      
        $role=\App\Models\System_root::getSupperRole();
        
        //验证是否有超级角色
        $roles=$this->where('admin_id',$admin_id)->where('role_id',$role)->first();
        if($roles&&$roles->toArray()){
            return 1;
        }
        //DB::connection()->enableQueryLog();

        //$queries = DB::getQueryLog();
      //  print_r($queries);
        //个人权限
        $prive_code=S('ROLE_PRIVS');
        if($prive_code<0){
            $prive_code=array();

            $data=\App\Models\Priv_codeModel::getAdminCode($admin_id);
            if($data<0){
                return -7030050022;//没有权限
            }

            foreach ($data as $k=>$v){
                $prive_code[]=trim($v['priv_code']);
            }
            $prive_code=array_unique($prive_code);
            S('ROLE_PRIVS',$prive_code);
        }
        if(in_array($code,$prive_code)){
            return 1;
        }
        return -7030050022;//没有权限
    }

    //获取管理员角色
    function getRole($where,$list=20){
        if(!empty($where)&&count($where)>0){
            $data = $this->where($where)->orderBy('create_at','desc')->paginate($list);
        }else{
            $data=$this->orderBy('create_at','desc')->paginate($list);
        }
        return $data->toArray();
    }
    //
    function getRoleBy($admin_id){
        $data=$this->select('role_name')->where('admin_id',$admin_id)->get();
        if(!$data){
            return '';
        }
        return $data->toArray();
    }
    function getRoleIn($ids){
        $data=$this->whereIn('admin_id',$ids)->get();
        if(!$data){
            return array();
        }
        return $data->toArray();
    }
    //查询管理员有有的角色
    function gethasRole($admin_id){
        $data=$this->select('role_id')
            ->where('admin_id',$admin_id)
            ->get();
        $arr=array();
        if(!$data){
            return $arr;
        }
        $data=$data->toArray();

        foreach ($data as $v){
            $arr[]=$v['role_id'];
        }
        return $arr;
    }
    //
    function addRole($data){
        $res=$this->insert($data);
        if(!$res){
            return -7050021922;//添加角色失败
        }
        return 1;
    }

}