<?php
/**
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Admin\Model;
use Think\Model;
/**
 * 权限规则模型
 */
class AuthRuleModel extends Model{
    const RULE_URL = 1;
    const RULE_MAIN = 2;
    /**
     * 获取规则数组供菜单及权限验证用
     * @param string  $type    返回项
     * @return array
     */
    public function getRuleArray(){
        if(!defined('UID')){$admin_info=session('admin_info');define('UID',$admin_info['id']);}
        $srulename='getRuleArray'.UID;
        $srulearray=S($srulename);
        if($srulearray)return $srulearray;
        if(!defined('IS_ROOT'))define('IS_ROOT',is_administrator(UID));
        $ruleData = IS_ROOT ? getcache('AuthRule') : $this->adminownrule();
		$newRuleArray = array();
		foreach ($ruleData as $ruleValue) {
			if ($ruleValue['show_status'] == 1) {
                $ruleValue['name'] = trim($ruleValue['name']);
                $ruleValue['icon']=urldecode($ruleValue['icon']);
                $newRuleArray[$ruleValue['id']] = $ruleValue;
			}
		}
		$Tree = new \Common\Vendor\Tree();
		$Tree->init($newRuleArray);
		$ruleData = $Tree->get_tree_array(0);
        if($ruleData)S($srulename,$ruleData,60*60*24);
		unset($newRuleArray);
        return $ruleData;            
    }
    private function adminownrule() {        
        if(!defined('UID')){$admin_info=session('admin_info');define('UID',$admin_info['id']);}
        $groupArray=UID?M('AuthGroupAccess')->where('uid='.UID)->field(true)->select():array();
		$ruleData = array();//该用户的所有权限		
		foreach ($groupArray as $groupVal) {
			$data = F("admin_rule_".$groupVal['group_id']);
			if (!$data) continue;
			$ruleData += $data;
		}return $ruleData;
	}
}