<?php
namespace app\widget\manager;

use think\facade\{View, Cache};
use app\model\Category;

class Menu
{
    /**
     * 左侧菜单
     * milo
     * 2018-01-06
     */
    public function left($categoryId = 0)
    {
        $auth = session('auth');
        $authCates = array_filter(explode(',', $auth['cates']));
        $rules = Cache::get('group_rules_'.$auth['groupId']);
        $menuRules = $this->getMenuRules($rules);

        $current = strtolower(request()->controller());
        $current = str_replace('manager.', '', $current);
        $currentAction = strtolower($current.'/'.request()->action());
        // message 留言管理是否集成在内容管理中，后期开发中根据情况调整
        if(in_array($current, ['article', 'product', 'page'], true)){
            $current = 'content';
        }
        if($auth['groupId'] == 1) {
            $menus = $this->getMenus(Category::getList(false));
        } else {
            $menus = $this->getMenus(Category::getList(true, $authCates));
        }

        $data = [
            'rules'             => $menuRules,
            'categoryId'        => $categoryId,
            'menus'             => $menus,
            'current'           => $current,
            'currentAction'     => $currentAction
        ];
        return View::assign($data)->fetch('manager/widget/left');
    }

    /**
     * 过滤出权限菜单
     * @param $rules
     * @return array
     */
    private function getMenuRules($rules)
    {
        $menuRules = [];
        if (!empty($rules)) {
            foreach ($rules as $rule) {
                $hasChildren = $rule['hasChildren'] ?? false;
                if ($hasChildren) {
                    $rule['children'] = $this->getMenuRules($rule['children']);
                    if(count($rule['children']) > 0) {
                        $rule['status'] = 1;
                    }
                }
                if($rule['status'] > 0) {
                    $menuRules[] = $rule;
                }
            }
        }
        return $menuRules;
    }

    /**
     * 内容栏目菜单
     * @param $cates
     * @param int $parent_id
     * @return array
     */
    private function getMenus($cates,$parentId=0)
    {
        $menus = [];
        foreach($cates as $cate){
            if($cate['parent_id'] == $parentId){
                $children = $this->getMenus($cates,$cate['id']);
                if(!empty($children)){
                    $cate['children'] = $children;
                }
                if(!empty($cate['children']) || !empty($cate['manager'])){
                    $menus[] = $cate;
                }
            }
        }
        return $menus;
    }
}
