<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\models;

use Yii;
use qcbase\models\Auth;

/**
 *
 * 前台菜单导航
 *
 * @author HuLimin http://blog.u-bo.com
 * @since 0.1
 */
class Menu extends \qcbase\models\Menu
{

    /**
     * 获取控制器菜单数组,一级
     * @author HuLimin  
     * @param type $module 模块名称$this->module->id
     */
    public static function getMainMenus($appName = 'admin', $module = '')
    {
        $module = empty($module) ? Yii::$app->controller->module->id : trim($module);
        $mainMenus = Yii::$app->session->get('MAIN_MENU_LIST' . $module);
        if (empty($mainMenus)) {
            $isSuperAdmin = Yii::$app->session->get('isSuperAdmin');
            $requestedRoute = Yii::$app->requestedRoute;
            // 获取主菜单
            $where['parent_id'] = 0;
            $where['status'] = 1;
            $where['app_name'] = $appName;
            //获取一级主菜单
            $mainMenus = static::getMenu($where);
            $mainMenus = \yii\helpers\ArrayHelper::index($mainMenus, 'menu_id');

            //非超级管理员获取权限
            $auth_urls = [];
            if (!$isSuperAdmin) {//检测是否为系统超级管理员
                $auth_urls = Auth::getAuthMenuByUser();
            }

            foreach ($mainMenus as $key => &$item) {
                // 判断主菜单权限
                $mainChildMenus = static::getChildAccessMenu($item['child_ids'], ['is_auth' => 1, 'action' => ['index', 'list', 'inbox', 'outbox']], 'auth_url,is_auth,action'); //主菜单的子节点

                if (!$isSuperAdmin && !Auth::checkMenuAccess($mainChildMenus)) {
                    unset($mainMenus[$key]);
                    continue; //继续循环
                }
                //修改URL 获取第一个子菜单URL(根据排序menu_id asc sort asc)
                $params = [];
                $mainUrl = [];
                if (!$isSuperAdmin) {//检测是否为系统超级管理员
                    $params = ['in', 'auth_url', $auth_urls];
                }
                $item['url'] = '#';
                $mainUrl = static::find()
                    ->select('auth_url,module,controller,action,sort,menu_id')
                    ->where(['menu_id' => explode(',', $item['child_ids']), 'action' => ['list', 'index', 'inbox', 'outbox']])
                    ->andWhere($params)
                    ->orderBy(['sort' => SORT_ASC, 'menu_id' => SORT_ASC])
                    ->asArray()
                    ->one();
                if (!empty($mainUrl)) {
                    $item['url'] = $mainUrl['module'] == 'home' ? '/' . $mainUrl['controller'] . '/' . $mainUrl['action'] : '/' . $mainUrl['auth_url'];
                }
                if (strtolower($requestedRoute) == strtolower($item['url'])) {
                    $mainMenus[$key]['class'] = 'active';
                }
            }


            // 根据当前Route获取父级菜单并赋予hover效果

            if (!empty($requestedRoute)) {
                $menuInfo = static::find()
                    ->select("parent_ids,menu_id")
                    ->where(['like', 'auth_url', Yii::$app->requestedRoute])
                    ->orderBy(['sort' => SORT_ASC,'menu_id' => SORT_ASC])
                    ->asArray()
                    ->one();

                $parent_ids = !empty($menuInfo['parent_ids']) ? $menuInfo['parent_ids'] : $menuInfo['menu_id'];
                foreach ($mainMenus as $mainValue) {
                    if (in_array($mainValue['menu_id'], explode(',', $parent_ids))) {
                        $mainMenus[$mainValue['menu_id']]['class'] = 'active';
                    }
                }
            }
            Yii::$app->session->set('MAIN_MENU_LIST' . $module, $mainMenus);
        }
        return $mainMenus;
    }

    /**
     * 获取子菜单
     * 
     * @param type $parent_id  父级菜单ID
     * @param type $topId     一级菜单ID
     * @return type
     */
    public static function childMenu($parent_id = 0, $topId = 0)
    {
        $auth_urls = \Yii::$app->session->get('auth_urls_user');
        $auth_urls = empty($auth_urls) ? Auth::getAuthMenuByUser() : $auth_urls;
        $isSuperAdmin = Yii::$app->session->get('isSuperAdmin');
        $map = [
            'parent_id' => $parent_id,
            'app_name' => 'home',
            'status' => 1,
            'action' => ['index', 'list', 'init', 'inbox', 'outbox']
        ];
        $order = [
            'sort' => SORT_ASC,
            'menu_id' => SORT_ASC
        ];
        //所有子级菜单
        $itemNav = [];
        $secondMenus = static::getMenu($map, $order, '*');
        if (!empty($secondMenus)) {
            foreach ($secondMenus as $k => $secondVo) {
                if (!$isSuperAdmin) {//检测是否为系统超级管理员
                    // 判断主菜单权限
                    $childMenus = static::getChildAccessMenu($secondVo['child_ids'], ['action' => ['index', 'list', 'init', 'inbox', 'outbox']], 'auth_url,is_auth,action'); //主菜单的子节点
                    if (!$isSuperAdmin && !Auth::checkMenuAccess($childMenus)) {
                        unset($secondMenus[$k]);
                        continue; //继续循环
                    }
                }
                //修改URL 获取第一个子菜单URL(根据排序menu_id asc sort asc)
                $params = [];
                if (!$isSuperAdmin) {//检测是否为系统超级管理员
                    $params = ['in', 'auth_url', $auth_urls];
                }

                //默认当前自己的URL
                $url = $secondVo['module'] == 'home' ? '/' . $secondVo['controller'] . '/' . $secondVo['action'] : '/' . $secondVo['module'] . '/' . $secondVo['controller'] . '/' . $secondVo['action'];
//                if ($secondVo['is_auth'] == 1) {
//                    $url = $secondVo['module'] == 'home' ? '/' . $secondVo['controller'] . '/' . $secondVo['action'] : '/' . $secondVo['auth_url'];
//                } else {


                $mainUrl = static::find()
                    ->select('auth_url,module,controller,action,sort,menu_id')
                    ->where(['menu_id' => explode(',', $secondVo['child_ids']), 'action' => ['index', 'list', 'inbox', 'outbox']])
                    ->orderBy(['sort' => SORT_ASC, 'menu_id' => SORT_ASC]);
                if (!empty($params)) {
                    $mainUrl = $mainUrl->andWhere($params);
                }
                $mainUrl = $mainUrl->asArray()->one();
                if (!empty($mainUrl)) {
                    $url = $mainUrl['module'] == 'home' ? '/' . $mainUrl['controller'] . '/' . $mainUrl['action'] : '/' . $mainUrl['auth_url'];
                }
//                }

                $itemNav[$k] = [
                    'label' => $secondVo['name'],
                    'url' => [$url, 'nav_id' => $topId]
                ];
                $itemNav[$k]['items'] = static::childMenu($secondVo['menu_id'], $topId);
            }
        }
        return $itemNav;
    }

    /**
     * 获取所有子菜单权限接到
     *
     * @param type $child_ids 子菜单ID
     * @return type
     */
    public static function getChildAccessMenu($child_ids = 0, $map = ['is_auth' => 1], $field = "*", $column = false)
    {
        $accessMenu = [];
        $accessMenu = static::find()
            ->select($field)
            ->where($map)
            ->orderBy(['sort' => SORT_ASC, 'menu_id' => SORT_ASC])
            ->andWhere(['menu_id' => explode(',', $child_ids)])
            ->asArray();
        if ($column) {
            $accessMenu = $accessMenu->column();
        } else {
            $accessMenu = $accessMenu->all();
        }
        return $accessMenu;
    }

    public static function getTrueLink($id = 0)
    {
        $map = [
            'parent_id' => $id
        ];
        $order = [
            'sort' => SORT_ASC,
            'menu_id' => SORT_ASC
        ];
        //所有子级菜单
        $itemNav = [];
        $secondMenus = static::getMenu($map, $order, '*');
    }
}
