<?php

namespace App\Services;

use App\Models\MenuPermission;
use Filament\Facades\Filament;
use Filament\Navigation\NavigationItem;

class MenuPermissionService
{
    /**
     * 过滤当前用户的菜单项
     */
    public static function filterUserNavigationItems(array $items): array
    {
        $user = Filament::getCurrentPanel()->auth()->user();
        if (!$user) {
            return $items;
        }

        $userId = $user->teacher_id ?? $user->id;

        return array_filter($items, function ($item) use ($userId) {
            $url = $item->getUrl();
            $menuKey = self::extractMenuKeyFromUrl($url);

            if (!$menuKey) {
                return true; // 如果无法识别菜单键，默认显示
            }

            return MenuPermission::isMenuVisible($userId, $menuKey);
        });
    }

    /**
     * 从URL中提取菜单键
     */
    private static function extractMenuKeyFromUrl(string $url): ?string
    {
        // 提取URL中的路径作为菜单键
        $path = parse_url($url, PHP_URL_PATH);

        if (!$path) {
            return null;
        }

        // 移除开头的斜杠并获取第一段路径
        $path = ltrim($path, '/');
        $segments = explode('/', $path);

        // 获取第一个路径段作为菜单键
        $menuKey = $segments[0] ?? null;

        // 特殊处理一些路径
        $menuMappings = [
            'admin' => null, // 跳过admin前缀
            'dashboard' => 'dashboard',
            'exam-history' => 'exam-history',
            'exam-analysis' => 'exam-analysis',
            'ocr-paper-grading' => 'ocr-paper-grading',
            'intelligent-exam-generation' => 'intelligent-exam-generation',
            'knowledge-graph' => 'knowledge-graph',
            'student-management' => 'student-management',
            'teacher-management' => 'teacher-management',
        ];

        return $menuMappings[$menuKey] ?? $menuKey;
    }

    /**
     * 为新用户初始化默认菜单权限
     */
    public static function initializeDefaultMenus(string $userId): void
    {
        $defaultMenus = [
            'dashboard' => ['label' => '仪表盘', 'group' => '管理', 'sort' => 0],
            'exam-history' => ['label' => '考试历史', 'group' => '管理', 'sort' => 1],
            'exam-analysis' => ['label' => '考试分析', 'group' => '分析', 'sort' => 2],
            'ocr-paper-grading' => ['label' => 'OCR试卷批改', 'group' => '工具', 'sort' => 3],
            'intelligent-exam-generation' => ['label' => '智能出卷', 'group' => '工具', 'sort' => 4],
            'knowledge-graph' => ['label' => '知识图谱', 'group' => '分析', 'sort' => 5],
            'student-management' => ['label' => '学生管理', 'group' => '管理', 'sort' => 6],
            'teacher-management' => ['label' => '老师管理', 'group' => '管理', 'sort' => 7],
        ];

        foreach ($defaultMenus as $key => $data) {
            MenuPermission::updateOrCreate(
                [
                    'user_id' => $userId,
                    'menu_key' => $key,
                ],
                [
                    'menu_label' => $data['label'],
                    'menu_group' => $data['group'],
                    'is_visible' => true,
                    'sort_order' => $data['sort'],
                ]
            );
        }
    }

    /**
     * 获取用户的菜单统计信息
     */
    public static function getUserMenuStats(string $userId): array
    {
        $stats = MenuPermission::where('user_id', $userId)
            ->selectRaw('COUNT(*) as total')
            ->selectRaw('SUM(CASE WHEN is_visible = 1 THEN 1 ELSE 0 END) as visible')
            ->selectRaw('SUM(CASE WHEN is_visible = 0 THEN 1 ELSE 0 END) as hidden')
            ->first();

        return [
            'total' => $stats->total ?? 0,
            'visible' => $stats->visible ?? 0,
            'hidden' => $stats->hidden ?? 0,
        ];
    }
}
