<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Validate;
use app\bsadmin\model\Auth as AuthModel;
class Auth extends Base
{
    public function index()
    {
    	if (request()->isAjax()) {
    		$G=request()->get();
    		if (empty($G['aid'])) {
    			return $this->ajaxReturn('',0,AuthModel::getSelect(['pid'=>0]));
    		}else{
    			return $this->ajaxReturn('',0,AuthModel::getSelect(['pid'=>$G['aid']]));
    		}
    	}else{
	    	return View::fetch();
    	}
    }
    /**
     * 添加权限
     */
    public function addAuth()
    {
    	if (request()->isAjax()) {
            $D=request()->post();
	        $rule =   [
	            'title'  		=> 'require|max:50',
	            'alias'  		=> 'unique:auth',
	            'controller'  	=> 'requireIf:is_nav,0',
	            'fun'  			=> 'requireIf:is_nav,0',
	            'url'  			=> 'requireIf:is_nav,0',
	            'sort'  		=> 'require|number|integer|lt:100',
	        ];
	        $msg  =   [
	            'title.require' 	=> 'Title 不能为空', 
	            'title.max' 		=> 'Title 不能超过50个字符',
	            'controller.require'=> '控制器不能为空',
	            'fun.require' 		=> '操作不能为空',
	            'url.require' 		=> '路由不能为空',
	            'sort.require' 		=> '排序不能为空',
	            'sort.integer' 		=> '排序数据类型错误',
	            'sort.number' 		=> '排序数据类型错误',
	            'sort.lt' 			=> '排序最大为99',
	            'alias.unique' 		=> '别名已存在',
	        ];
	        $Validate=Validate::rule($rule)->message($msg);
	        $result = $Validate->check($D);
	        if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
	        $routeWhere=[];
	        switch ($D['method']) {
	            case 'get':
	                $routeWhere=['rule','get'];
	                break;
	            case 'post':
	                $routeWhere=['rule','post'];
	                break;
	            default:
	                $routeWhere=['rule','get','post'];
	                break;
	        }
	        $auth=new AuthModel;
            if ($D['is_nav']) {
                $route=$auth->where(['url'=>$D['url']])
                        ->whereIn('method',$routeWhere)
                        ->field('title')->find();
                if($route){return $this->ajaxReturn('<'.$route.'>路由已存在',-100);}
            }else{
                $auth->controller=  $D['controller'];
                $auth->fun      =   $D['fun'];
                $auth->url      =   $D['url'];
                $auth->method   =   $D['method'];
                $auth->code     =   $D['code'];
                $auth->param    =   $D['param'];
            }
            $auth->pid      =   $D['pid'];
            $auth->title    =   $D['title'];
            $auth->alias    =   $D['alias'];
	        $auth->status 	=	$D['status'];
            $auth->is_nav   =   $D['is_nav'];
	        $auth->show 	=	$D['show'];
	        $auth->icon 	=	$D['icon'];
	        $auth->sort 	=	$D['sort'];
	        if($auth->save()){
                if ($this->updateRouteFile()) {
                    return $this->ajaxReturn('保存成功');
                }else{
                    return $this->ajaxReturn('保存成功。更新路由失败，请手动更新');
                }
	        }else{
	            return $this->ajaxReturn('保存失败，请重试',-200);
	        }
    	}else{
            View::assign('auth',AuthModel::getCateList());
	    	return View::fetch();
    	}
    }
    /**
     * 编辑权限
     */
    public function editAuth($id)
    {
        if (request()->isAjax()) {
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:50',
                'alias'         => 'unique:auth',
                'controller'    => 'requireIf:is_nav,0',
                'fun'           => 'requireIf:is_nav,0',
                'url'           => 'requireIf:is_nav,0',
                'sort'          => 'require|number|integer|lt:100',
            ];
            $msg  =   [
                'title.require'     => 'Title 不能为空', 
                'title.max'         => 'Title 不能超过50个字符',
                'controller.require'=> '控制器不能为空',
                'fun.require'       => '操作不能为空',
                'url.require'       => '路由不能为空',
                'sort.require'      => '排序不能为空',
                'sort.integer'      => '排序数据类型错误',
                'sort.number'       => '排序数据类型错误',
                'sort.lt'           => '排序最大为99',
                'alias.unique'      => '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $routeWhere=[];
            switch ($D['method']) {
                case 'get':
                    $routeWhere=['rule','get'];
                    break;
                case 'post':
                    $routeWhere=['rule','post'];
                    break;
                default:
                    $routeWhere=['rule','get','post'];
                    break;
            }
            $auth=new AuthModel;
            $authData=AuthModel::where('aid',$id)->find();
            if ($D['is_nav']) {
                $route=$auth->where(['url'=>$D['url']])
                        ->whereIn('method',$routeWhere)
                        ->field('aid,title')->find();
                if($route and $route['aid']!=$id){return $this->ajaxReturn('<'.$route.'>路由已存在',-100);}
                $authData->controller=  '';
                $authData->fun      =   '';
                $authData->url      =   '';
                $authData->method   =   '';
                $authData->code     =   '';
                $authData->param    =   '';
            }else{
                $authData->controller=  $D['controller'];
                $authData->fun      =   $D['fun'];
                $authData->url      =   $D['url'];
                $authData->method   =   $D['method'];
                $authData->code     =   $D['code'];
                $authData->param    =   $D['param'];
            }
            if ($D['pid']) {
                $authData->pid      =   $D['pid'];
            }else{
                $authData->pid      =   0;
            }
            $authData->title    =   $D['title'];
            $authData->alias    =   $D['alias'];
            $authData->status   =   $D['status'];
            $authData->is_nav   =   $D['is_nav'];
            $authData->show     =   $D['show'];
            $authData->icon     =   $D['icon'];
            $authData->sort     =   $D['sort'];
            if($authData->save()){
                if ($this->updateRouteFile()) {
                    return $this->ajaxReturn('保存成功');
                }else{
                    return $this->ajaxReturn('保存成功。更新路由失败，请手动更新');
                }
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=AuthModel::getAuth(['aid'=>$id]);
            if ($Find) {
                View::assign('Find',$Find->toArray());
            }
            View::assign('auth',AuthModel::getCateList());
            return View::fetch('add_auth');
        }
    }
    public function delAuth($aid)
    {
        $AuthModel=AuthModel::where(['aid'=>$aid])->find();
        if($AuthModel->delete()){
            if ($this->updateRouteFile()) {
                return $this->ajaxReturn('已删除');
            }else{
                return $this->ajaxReturn('已删除。更新路由失败，请手动更新');
            }
        }else{
            return $this->ajaxReturn('删除失败，请重试',-200);
        }
    }
    /**
     * 设置权限状态
     */
    public function setAuthStatus($id,$status)
    {
        $authData=AuthModel::where('aid',$id)->find();
        $authData->status=$status;
        if ($authData->save()) {
            if ($this->updateRouteFile()) {
        		return $this->ajaxReturn();
            }else{
                return $this->ajaxReturn('保存成功。更新路由失败，请手动更新');
            }
        }else{
        	return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 设置权限菜单栏
     */
    public function setAuthShow($id,$show)
    {
        $authData=AuthModel::where('aid',$id)->find();
        $authData->show=$show;
        if ($authData->save()) {
            if ($this->updateRouteFile()) {
        		return $this->ajaxReturn();
            }else{
                return $this->ajaxReturn('保存成功。更新路由失败，请手动更新');
            }
        }else{
        	return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 设置权限排序
     */
    public function setAuthSort($id,$sort)
    {
        $authData=AuthModel::where('aid',$id)->find();
        $authData->sort=$sort;
        if ($authData->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 异步更新路由文件
     */
    public function updateRouteFileAjax()
    {
        if ($this->updateRouteFile()) {
            return $this->ajaxReturn('更新成功');
        }else{
            return $this->ajaxReturn('更新路由失败,请重试',-100);
        }
    }
    /**
     * [updateRouteFile 更新路由文件]
     * @return [type] [description]
     */
    protected function updateRouteFile()
    {
        try {
            $auth=AuthModel::field('pid,aid,title,controller,fun,is_nav,status,code')->select();
            $module=app('http')->getName();
            //读取不需要授权的权限
            $auth_not_verify=config('auth_not_verify');
            //权限
            $roleWrite="<?php\nreturn [\n";
            //路由
            $RouteWrite="<?php\nuse think\\facade\\Route;\n";
            foreach ($auth_not_verify as $k => $v) {
                    //不需要授权的路由
                    $RouteWrite.="//".$v['title']."\nRoute::rule('".$v['route']."','".$k."');\n";
            }
            foreach ($auth as $k => $v) {
                if (!$v['is_nav']) {
                    $ppid=$v['pid'];
                    $ptitle='';
                    if ($v['pid']) {
                        $pFind=AuthModel::where(['aid'=>$v['pid']])->field('pid,title')->find();
                        if($pFind){
                            $ppid=$pFind['pid'];
                            $ptitle=$pFind['title'];
                        }
                    }
                    //组装权限
                    $roleWrite.="//".$v['title']."\n'".$module."/".$v['controller']."/".$v['fun']."'=>['aid'=>".$v['aid'].",'pid'=>".$v['pid'].",'ppid'=>".$ppid.",'status'=>".$v['status'].",'title'=>'".$v['title']."','ptitle'=>'".$ptitle."'],\n";
                    //组装路由
                    $RouteWrite.="//".$v['title']."\n".$v['code']."\n";
                }
            }
            //路由
            $roleWrite.="];";
            //写入路由文件
            $RoutePath=app_path()."route/route.php";
            $RouteFile = fopen($RoutePath, "w") or die("Unable to open file!");
            fwrite($RouteFile, $RouteWrite);
            fclose($RouteFile);
            //写入权限配置文件
            $rolePath=app_path()."config/auth.php";
            $roleFile = fopen($rolePath, "w") or die("Unable to open file!");
            fwrite($roleFile, $roleWrite);
            fclose($roleFile);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
}
