<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-06-24
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\model;
use think\Model as Basemodel;
use app\admin\model\Admingroup;

class Adminrule extends Basemodel
{
	// 用户后台规则
	public static function getRules($gid)
	{
		$menu = [];
		$admingroup_info = Admingroup::get($gid);
		if(!empty($admingroup_info)) {
			$menus = self::when($admingroup_info['pid'] != 0,function($query) use ($admingroup_info){
				$query->whereIn('id',$admingroup_info['rules'])->where('status',0);
			})->order('torder')->withAttr('href',function($value,$data){
				return empty($data['name']) ? '':url($data['name']);
			})->withAttr('target',function($value) {
				return "_self";
			})->append(['href','target'])->visible(['id','pid','title','name','icon'])->select()->toArray();
		}
		return $menus;
	}

	// 获取下拉列表树数据
	public static function getRulestree()
	{
		$data = self::whereLevel('<',4)->order('torder','id')->field(['id','pid','title','name'])->withAttr('name',function($value,$data){
			return $data['title'];
		})->select()->toArray();
		$data = array_merge([['id' => 0,'pid' => -1,'name' => '顶级目录']],$data);
		return \rg\PHPTree::makeTree($data,['top_pv' => -1]);
	}
	// 权限树
	public static function getAuthtree($rules='')
	{
		if(empty($rules)) {
			$data = self::whereStatus(0)->withAttr('spread',function($value,$data){
				return true;
			})->append(['spread'])->order('torder','id')->field(['id','pid','title','name'])->select()->toArray();
		} else {
			$rules_a = explode(',', $rules);
			$data = self::whereStatus(0)->withAttr('spread',function($value,$data){
				return true;
			})->withAttr('checked',function($value,$data) use($rules_a){
				if(in_array($data['id'], $rules_a) && $data['level']==4) {
					return true;
				} else {
					return false;
				}
			})->append(['checked','spread'])->order('torder','id')->field(['id','pid','title','name','level'])->select()->toArray();
		}
		
		return \rg\PHPTree::makeTree($data);
	}

	// 判断是否有子孙
	public function getHaschildAttr($value,$data)
	{
		$haschild = $this->wherePid($data['id'])->count();
		return $haschild ? true : false;
	}
}