<?php

namespace App\Services;

use App\Models\SiteMenu;

class MenuService
{
    /**
     * 获取多级菜单
     *
     * @return array
     */
    public function getMultiLevelMenu(int $menu_location=0,int $dist_id = 0): array
    {
        // 一次性加载所有菜单项
        $menus = SiteMenu::where('show', 1) // 只显示状态为 1 的菜单
            ->where('dist_id', $dist_id)
            ->where('menu_location', $menu_location)
            ->orderBy('order', 'asc')
            ->get();

        // 构造多级菜单
        return $this->buildMenuTree($menus);
    }

    /**
     * 递归构造菜单树
     *
     * @param \Illuminate\Database\Eloquent\Collection $menus
     * @param int $parentId
     * @return array
     */
    private function buildMenuTree($menus, $parentId = 0): array
    {
        $menuTree = [];
        foreach ($menus as $menu) {
            if ($menu->parent_id == $parentId) {
                $menu->children = $this->buildMenuTree($menus, $menu->id);
                $menuTree[] = $menu->toArray();
            }
        }
        return $menuTree;
    }
}
