<?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 static function getAuthMenu($isDev=0,$member_group_id=0,$rules=''){
        $menuTree=cache("ADMIN_AUTH_MENU");

        if($menuTree&&isset($menuTree[$member_group_id][$isDev])){
            return $menuTree[$member_group_id][$isDev];
        }

        //系统按照权限组对后台菜单进行了缓存
        $map[0] =['hide','=',0];
        $map[1] =['status','=',1];
        $map[2] =['pid','=',0];
        //如果开启开发者模式，读取权限内所有后台菜单
        if(!$isDev){
            $map[3] =['is_dev','=',0];
        }
        if($member_group_id)
            $map[4] =['id','in',$rules];

        //获取一级菜单
        $menus=AdminMenu::where($map)->order('sort asc')->select()->toArray();
        foreach ($menus as $key=>$item){
            $map[2] =['pid','=',$item['id']];
            //获取二级菜单
            $child=AdminMenu::where($map)->order('sort asc')->select()->toArray();
            if($child){
                $menus[$key]['child']=$child;
            }
        }
        $menuTree=$menuTree?$menuTree:[];
        $menuTree[$member_group_id][$isDev]=$menus;
        cache("ADMIN_AUTH_MENU",$menuTree);


        return $menus;
    }

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

    /**
     * 添加，清除缓存
     * @param $data
     * @return bool|mixed
     */
    public function add($data)
    {
        $re=parent::add($data);
        if($re)
            AdminMenu::removeAuthMenuCache();
        return $re;
    }

    /**
     * 编辑，清除缓存
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        $re=parent::edit($data);
        if($re)
            AdminMenu::removeAuthMenuCache();
        return $re;
    }

    /**
     * 清除权限组菜单缓存
     * @param $member
     */
    public static function removeAuthMenuCache($member_group_id=false){
        if(!$member_group_id){
            cache("ADMIN_AUTH_MENU",null);
        }
        else{
            $adminAuthMenu=cache("ADMIN_AUTH_MENU");
            if(!$adminAuthMenu){
                return;
            }
            if(!isset($adminAuthMenu[$member_group_id])){
                return;
            }
            unset($adminAuthMenu[$member_group_id]);
            cache("ADMIN_AUTH_MENU",$adminAuthMenu);
        }
    }
}