<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Validate;
use app\bsadmin\model\Auth as AuthModel;
use app\bsadmin\model\Role as RoleModel;
use app\bsadmin\model\Admin as AdminModel;
class Role extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if (empty($G['rid'])) {
                return $this->ajaxReturn('',0,RoleModel::getSelect());
            }else{
                return $this->ajaxReturn('',0,AdminModel::alias('admin')->where(['admin.role_id'=>$G['rid']])->field('admin.*,admin.nickname as title')->select());
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 修改角色
     */
    public function editRole($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
                'auth'      => 'require|array',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
                'auth.require'  => '请选择权限',
                'auth.array'    => '权限不正确',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $roleModel=RoleModel::where('rid',$id)->find();
            $roleModel->title   = $D['title'];
            $roleModel->auth    = implode(',',$D['auth']);
            if($roleModel->save()){
                if ($this->updateRoleFile($roleModel->rid)) {
                    return $this->ajaxReturn('保存成功');
                }else{
                    return $this->ajaxReturn('保存成功。更新权限菜单失败，请手动更新');
                }
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=RoleModel::getRole(['rid'=>$id]);
            if ($Find) {
                View::assign('Find',$Find->toArray());
            }
            $auth=AuthModel::getList()->toArray();
            View::assign('auth',getTree($auth,'aid'));
            return View::fetch('add_role');
        }
    }
    /**
     * 添加角色
     */
    public function addRole()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
                'auth'      => 'require|array',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
                'auth.require'  => '请选择权限',
                'auth.array'    => '权限不正确',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $roleModel=new RoleModel;
            $roleModel->title   = $D['title'];
            $roleModel->auth    = implode(',',$D['auth']);
            if($roleModel->save()){
                if ($this->updateRoleFile($roleModel->id)) {
                    return $this->ajaxReturn('保存成功');
                }else{
                    return $this->ajaxReturn('保存成功。更新角色缓存失败，请手动更新');
                }
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $auth=AuthModel::getList()->toArray();
            View::assign('auth',getTree($auth,'aid'));
            return View::fetch();
        }
    }
    /**
     * 删除角色
     */
    public function delRole($id)
    {
        $roleModel=RoleModel::where('rid',$id)->find();
        if (AdminModel::where(['role_id'=>$id])->count()) {
            return $this->ajaxReturn('该角色下还存在管理员，请先移除',-100);
        }else{
            if ($roleModel->delete()) {
                return $this->ajaxReturn();
            }else{
                return $this->ajaxReturn('删除失败，请重试',-100);
            }
        }
    }
    /**
     * 异步更新角色缓存
     */
    public function updateRoleFileAjax($id='')
    {
        if (intval($id)) {
            if ($this->updateRoleFile($id)) {
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('更新角色缓存失败，请手动更新');
            }
        }else{
            $RoleModel=RoleModel::field('rid')->select();
            foreach ($RoleModel as $v) {
                $this->updateRoleFile($v->rid);
            }
            return $this->ajaxReturn('保存成功');

        }
    }
    /**
     * [updateRoleFile 更新权限菜单文件]
     * @return [type] [description]
     */
    protected function updateRoleFile($id)
    {
        try {
            $Role=RoleModel::where(['rid'=>$id])->find();
            $auth=AuthModel::getMenuList([['aid','in',$Role->auth]])->toArray();
            //读取原有的权限菜单
            $auth_menu=Cache::get('role.auth_menu');
            if (!$auth_menu) $auth_menu=[];
            $roleConfig=config('role');
            $auth_menu[intval($id)]=json_encode(getTree($auth,'aid'),JSON_UNESCAPED_UNICODE);
            $roleConfig[intval($id)]=['title'=>$Role->title,'auth'=>explode(',', $Role->auth)];
            $roleConfigWrite="<?php\nreturn [\n";
            foreach ($roleConfig as $k => $v) {
                $roleConfigWrite.="$k=>['title'=>'".$v['title']."','auth'=>[".implode(',', $v['auth'])."]],\n";
            }
            $roleConfigWrite.="];";
            Cache::set('role.auth_menu',$auth_menu);
            //写入权限配置文件
            $roleConfigPath=app_path()."config/role.php";
            $roleConfigFile = fopen($roleConfigPath, "w") or die("Unable to open file!");
            fwrite($roleConfigFile, $roleConfigWrite);
            fclose($roleConfigFile);
            return true;
        } catch (\think\Exception $e) {
            return false;
        }
    }
}
