<?php
namespace app\admin\controller;
use think\App;
use think\facade\Session;
use think\facade\View;
use think\facade\Request;
 
class rule extends Base{

	//Rule首页
    public function index(){
		return View::fetch();
    }
	
	//添加节点
    public function add(){
		$list=\app\admin\model\AuthRule::rule();
		$list=$list->toArray();
		$list = $this->treeMenu($list);
		
		View::assign('list',$list);
		return View::fetch();
    }

    public function edit(){
		$list=\app\admin\model\AuthRule::rule();
		$list=$list->toArray();
		$list = $this->treeMenu($list);

		$id=Request::param('id');
		$info=\app\admin\model\Common::info($id,'auth_rule','');

		View::assign('list',$list);
		View::assign('info',$info);
		return View::fetch();
    }

	function treeMenu($cate,$joinStr = '┝',$pid=0,$level=0){
		$arr = array();
		foreach($cate as $k => $v){
			if($v['pid'] == $pid) {
				$kong='';
				for($i=0;$i<$level;$i++){
					$kong.='　';	
				}
				$joinStr =$level==0 ? '':''.$kong.'┝ '; //判断是否是第一级分类
				$v['level'] = $level + 1;
				$v['name'] =$joinStr.$v['name'];
				$arr[] = $v;
				unset($cate[$k]); //删除该节点，减少递归的消耗
				$arr = array_merge($arr, $this->treeMenu($cate, $joinStr, $v['id'], $level + 1));
			}
		}
		return $arr;
	}
	
	//添加节点
    public function save(){
		IS_AJAX(Request::isAjax());
		$info=\app\admin\model\AuthRule::save_rule();
		$data =['ok' =>1,'msg' =>'成功'];
		return json($data);
    }
	
	//layui列表获取数据
    public function rule_list(){
		$list=\app\admin\model\AuthRule::rule();
		$list=$list->toArray();
		$list = $this->treeMenu($list);

		$data['code']=0;
		$data['data']=$list;
		return json($data);
    }
	
	//权限组
    public function group(){

		$list=\app\admin\model\AuthRule::admin_index_left(0,1);
		foreach($list as $k=>$c){
			$list[$k]['data']=$this->index_left($c['id']);
		}

		$id=Request::param('id');
		if($id!=''){
			$info=\app\admin\model\Common::info($id,'auth_group','rid');
		}
		
		if($id==''){
			$info['id']='';
			$info['name']='';
			$info['rid']='';
		}

		View::assign('info',$info);
		View::assign(['id'=>$id,'list'=>$list]);
		return View::fetch();
	}

    public function index_left($pid){
		$list=\app\admin\model\AuthRule::admin_index_left($pid,1);
		return $list;
	}


	//layui列表获取数据
    public function group_list(){
		$list=\app\admin\model\AuthRule::group();

		$data['code']=0;
		$data['data']=$list;
		return json($data);
    }
	
    public function save_group(){
		$tdata=Request::param();
		
		$tdata['rid']=isset($tdata['rid'])? $tdata['rid'] :'';	
		$value = [
                'name' =>$tdata['name'],
                'rid'=>$tdata['rid'],
        ];
		
		$validate=new \app\admin\validate\Rule();

        if(!$validate->check($value)) {
			$data =['error' =>'1','msg' =>$validate->getError()];
			return json($data);
        }

		$list=\app\admin\model\AuthRule::save_group();
		$data =['ok' =>1,'msg' =>'操作成功'];
		return json($data);
    }
	
	
}
