<?php
namespace app\common\model;

/**
 * 后台菜单
 * Class AdminMenu
 * @package app\common\model
 */
class AdminMenu extends Base {

    /**
     * 根据权限获得后台菜单
     * @param bool $rules 权限字符串
     * @param int $is_dev 开发者模式标识
     * @return mixed
     */
    public function getMenu($member,$isDev=0){

        //系统按照权限组对后台菜单进行了缓存
        $menus  =   cache("ZZ_AUTH_".$member->group_id);
        if(empty($menus)){
            $map[0] =['hide','=',0];
            $map[1] =['status','=',1];
            $map[2] =['pid','=',0];
            //如果开启开发者模式，读取权限内所有后台菜单
            if(!$isDev){
                $map[3] =['is_dev','=',0];
            }
            //超级管理员$adminAuthId为空
            if($member->id!=1){
                $map[4] =['id','in',$member->adminAuth->rules];
            }
            //获取一级菜单
            $menus=$this->where($map)->order('sort asc')->select()->toArray();
            foreach ($menus as $key=>$item){
                $map[2] =['pid','=',$item['id']];
                //获取二级菜单
                $child=$this->where($map)->order('sort asc')->select()->toArray();
                if($child){
                    $menus[$key]['child']=$child;
                }
            }
            cache("ZZ_AUTH_".$member->group_id,$menus);
        }
        return $menus;
    }

    public function parent(){
        return $this->belongsTo('AdminMenu','pid');
    }

    /**
     * 清除缓存
     * @param $member
     */
    public function removeCache($member){
        cache("ZZ_AUTH_".$member->group_id,null);
    }
}