<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace app\wendasns\admin;

use app\admin\AdminBaseController;
use app\wendasns\model\Group as byGroup;
use app\wendasns\model\GroupPermission;
use app\wendasns\model\GroupRank;

class Group extends AdminBaseController
{

    public function index()
    {
    	$type = input('get.type','default');
    	
		return view('index',['type'=>$type]);
    }

    public function list()
    {
		$limit = input('get.limit',20,'intval');
		$type = input('get.type','default');
    	$dm = byGroup::where('type',$type)->paginate($limit);

    	$data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }

	public function add()
	{
		$name = input('post.name','');
		$type = input('post.type','default');

		if(!$name){
			error('请填写用户组名称');
		}
		$dm = byGroup::where('name',$name)->where('type',$type)->find();
		if($dm){
			error('用户组名称已存在');
		}

		byGroup::create([
			'name'=>$name,
			'type'=>$type
		]);
		success('操作成功');
	}
	
	public function dorun()
	{
		$id = input('post.id',0,'intval');
		$name = input('post.name','');
		$auths = input('post.auths',[]);

		if(!$name){
			error('请填写用户组名称');
		}
		$dm = byGroup::where('name',$name)->where('id','<>',$id)->find();
		if($dm){
			error('用户组名称已存在');
		}
		
		$dm = byGroup::find($id);
		if(!$dm) error('用户组不存在');
		$dm->name = $name;
		$dm->save();
		
		if($dm->permissions){
			GroupPermission::where('group_id',$id)->where('type',$dm->type)->delete();
		}

		$permission = new GroupPermission;
		$list = [];
		foreach($auths as $k=>$v){
			$list[] = ['group_id'=>$id,'permission'=>$v,'type'=>$dm->type];
		}
		$permission->saveAll($list);
		
		success('操作成功');
	}

    public function edit()
    {
    	$id = input('get.id',0,'intval');
    	$dm = byGroup::find($id);
    	
    	if(!$dm){
    		error('用户组不存在');
    	}
    	$controller = [];
		foreach($dm->permissions as $item){
			$controller[] = $item->permission;
		}
    	
    	$rank = GroupRank::select();
    	
		return view('edit',['group'=>$dm,'controller'=>$controller,'rank'=>$rank]);
    }
    
    //删除
    public function remove()
    {
		$id = input('post.id',[]);
		if(is_array($id)){
			byGroup::destroy($id);
			GroupPermission::where('group_id','in',$id)->delete();
		}
		success('操作成功');
    }

}