<?php
namespace app\admin\controller;

use app\admin\AdminBaseController;
use app\admin\model\Role as byRole;
use app\admin\model\Admin;

class Role extends AdminBaseController
{
	public function index()
	{
		return view();
    }

	public function edit()
	{
		$id = input('get.id',0,'intval');
		$dm = byRole::find($id);
		$menu = config('adminmenu');
		return view('edit',['role'=>$dm,'log'=>$menu]);
    }
    
	//管理员管理
	public function list()
	{
    	$limit = input('get.limit',20,'intval');

    	$dm = byRole::order('create_time', 'desc')->paginate($limit);
    	$dm->append(['list']);
    	
    	$dm->withAttr('list',function($value, $data) {
    		$ar = explode(',',$data['auths']);
    		foreach($ar as $v){
    			$res[$v] = 1;
    		}
        	return $res;
        });
        
    	$data = $dm->toArray();
    	success('ok', $data['data'], ['count'=>$data['total']]);
    }
    
    public function dorun()
    {
    	$id = input('post.id',0,'intval');
    	$name = input('post.name','');
    	$auths = input('post.auths',[]);
    	if(empty($name)){
    		error('请填写组名');
    	}
    	$dm = byRole::where('name',$name)->where('id','<>',$id)->find();
    	if($dm){
    		error('已有相同组');
    	}
    	$auths = array_unique($auths);
    	$data = [
    		'name' => $name,
    		'auths' => implode(',',$auths)
    	];
    	
    	if($id>0){
    		$data['id'] = $id;
    		byRole::update($data);
    	}else{
    		byRole::create($data);
    	}
    	success('操作成功');
    }

    public function remove()
    {
    	$ar = input('post.id',[]);
    	$id = array_shift($ar);
    	$dm = byRole::find($id);
    	if($dm->type=='system'){
    		error('系统默认组禁止操作');
    	}
    	$dm->delete();
    	success('操作成功');
    }
}