<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=utf-8");
class BaseController extends Controller
{
    public function __construct()
    {
    	
        parent::__construct();
        if (!session('?admin')) {
            $last_visit = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            cookie('last_visit', $last_visit, 7200);
            $this->redirect('Login/login');die;
        }

        // 检测权限
        $controller = strtolower(CONTROLLER_NAME);
        $method = ACTION_NAME;
        $one_auth = $controller.'_node';// 一级菜单权限
        $two_auth = $controller.'_'.$method.'_node';// 二级菜单/操作权限
        
        if (!in_array($one_auth, session('auth'))) {
            $this->error('没有访问权限');die;
        }
        
        if (!in_array($two_auth, session('auth'))) {
            $this->error('没有访问权限');die;
        }

        $this->assign("admin", session("admin"));
        $this->assign('nav', $controller);

        // 获取菜单
        $this->auth_menu();
    }

    /**
     * 获取权限菜单
     */
    private function auth_menu()
    {
        $one_menu_list = M('node')->field('id, title, auth_name')->where(array('pid' => 0, 'status' => 1, 'level' => 1))->select();

        $two_menu_list = M('node')->field('pid, title, auth_name, url')->where('pid <> 0 AND status = 1 AND level = 2')->select();

        // 获取一级菜单权限
        foreach ($one_menu_list as $k => &$vo) {
            if (!in_array($vo['auth_name'], session('auth'))) {
                unset($one_menu_list[$k]);continue;
            }
            $nav = split('_', $vo['auth_name'])[0];// 下拉展示控件
            $vo['nav'] = $nav;

            // 获取二级菜单权限
            $vo['menu_list'] = array();
            foreach ($two_menu_list as $vv) {
                if (!in_array($vv['auth_name'], session('auth'))) {
                    continue;
                }
                if ($vv['pid'] == $vo['id']) {
                    $vo['menu_list'][] = $vv;
                }
            }
        }
        
        $this->assign('menu_list', $one_menu_list);
    }

}