<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-06-19
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\facade\Cache;
use app\admin\model\Adminrule;
use app\admin\model\Admingroup;
use Request;

class Sysmenu extends Base
{
	
	// 节点列表
	public function index()
	{
		if(Request::isPost()) {
			if(empty(Request::post('gid'))){
				$data = Adminrule::order('torder','id')->append(['haschild'])->select();
			} else {
				$rules = Adminrule::getRules(Request::post('gid'));
				$data['list']= $rules;
				if(input('?post.id')) {
					$checkrules = Admingroup::getFieldById(input('post.id'),'rules');
					if(!empty($checkrules)) {
						$data['checkedId'] = explode(',',$checkrules);  // 设置选定的权限
						foreach ($data['checkedId'] as $k => $v) {
							$data['checkedId'][$k] = (int)$v;
						}
					}
				}
			}
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
		}
		return $this->fetch();
	}

	// 添加节点
	public function add()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			$result = Adminrule::create($data,true);
			adminlog(2,'新增('.Adminrule::getLastsql().')',$result?1:0);
			if ($result) {
				Cache::clear('adminmenu');
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		return $this->fetch();
	}

	// 修改节点
	public function edit($id)
	{
		$info = Adminrule::get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
            $result = $info->allowField(true)->save($data);
            adminlog(2,'编辑('.Adminrule::getLastsql().')',$result?1:0);
			if ($result) {
				Cache::clear('adminmenu');
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
		return $this->fetch('',compact('info'));
	}

	// 删除节点
	public function del()
	{
		if(Request::isPost()){
			$data = Request::post();
			if(!captcha_check($data['captcha'])){
				$this->error(lang('captchafalse'));
			}
			$info = Adminrule::get($data['id'])->append(['haschild']);
			if($info->haschild) $this->error(lang('delfalse'));
			$result = $info->delete();
			adminlog(2,'删除('.Adminrule::getLastsql().')',$result?1:0);
			if ($result) {
				Cache::clear('adminmenu');
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	//数据验证方法:目录和菜单场景
	private function checkData($data)
	{
		if(isset($data['level'])) {
			$validate = new \app\admin\validate\Adminrule;
			if($data['level']<3) {
				if(!$validate->scene('directory')->check($data)) {
					$this->error($validate->getError());
				}
			} else {
				if(!$validate->check($data)) {
					$this->error($validate->getError());
				}
			}
		}
	}
}