<?php
declare (strict_types=1);

namespace app\service;

use app\model\UserRoleModel;
use think\facade\Config;

class PermissionService
{
    /**
     * 检查用户权限
     */
    public static function checkPermission(int $userId, string $controller, string $action): bool
    {
        // 检查是否在白名单中
        if (self::isInPermissionWhitelist($controller, $action)) {
            return true;
        }
        
        $roleId = getUserRoleId($userId);
        if (!$roleId) {
            return false;
        }
        
        // 超级管理员拥有所有权限
        if (self::isSuperAdmin($roleId)) {
            return true;
        }
        
        // 获取用户权限并检查
        $permissions = self::getUserPermissions($roleId);
        $permission = strtolower($controller . '.' . $action);
        
        return in_array($permission, $permissions);
    }
    
    /**
     * 获取用户权限列表
     */
    public static function getUserPermissions(int $roleId): array
    {
        $role = UserRoleModel::find($roleId);
        if (!$role || empty($role->privileges)) {
            return [];
        }
        
        if (!is_array($role->privileges)) {
            $privileges = json_decode($role->privileges, true);
            if (!is_array($privileges)) {
                return [];
            }
        } else {
            $privileges = $role->privileges;
        }

        // 转换为权限数组格式: controller.action
        $permissions = [];
        foreach ($privileges as $controller => $actions) {
            if (is_array($actions)) {
                foreach ($actions as $action) {
                    $permissions[] = strtolower($controller . '.' . $action);
                }
            }
        }
        
        return $permissions;
    }
    
    /**
     * 获取所有权限配置
     */
    public static function getAllPermissions(): array
    {
        return Config::get('permission.permissions', []);
    }
    
    /**
     * 获取超级管理员角色ID列表
     */
    public static function getSuperAdminRoleIds(): array
    {
        return Config::get('permission.super_admin_role_ids', []);
    }
    
    /**
     * 检查是否是超级管理员
     */
    public static function isSuperAdmin(int $roleId): bool
    {
        return in_array($roleId, self::getSuperAdminRoleIds());
    }
    
    /**
     * 获取登录白名单
     */
    public static function getLoginWhitelist(): array
    {
        return Config::get('permission.login_whitelist', []);
    }
    
    /**
     * 获取权限白名单
     */
    public static function getPermissionWhitelist(): array
    {
        return Config::get('permission.permission_whitelist', []);
    }
    
    /**
     * 检查是否在登录白名单中
     */
    public static function isInLoginWhitelist(string $controller, string $action): bool
    {
        $whitelist = self::getLoginWhitelist();
        
        // 检查控制器级别白名单
        $controllers = $whitelist['controllers'] ?? [];
        if (in_array($controller, $controllers)) {
            return true;
        }
        
        // 检查具体方法白名单
        $actions = $whitelist['actions'] ?? [];
        $current = $controller . '/' . $action;
        if (in_array($current, $actions)) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查是否在权限白名单中
     */
    public static function isInPermissionWhitelist(string $controller, string $action): bool
    {
        $whitelist = self::getPermissionWhitelist();
        
        // 检查控制器级别白名单
        $controllers = $whitelist['controllers'] ?? [];
        if (in_array($controller, $controllers)) {
            return true;
        }
        
        // 检查具体方法白名单
        $actions = $whitelist['actions'] ?? [];
        $current = $controller . '/' . $action;
        if (in_array($current, $actions)) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 根据控制器名获取权限配置
     */
    public static function getControllerPermissions(string $controller): array
    {
        return Config::get('permission.permissions.' . $controller, []);
    }
    
    /**
     * 格式化权限列表用于前端展示
     */
    public static function formatPermissionsForDisplay(): array
    {
        $permissions = self::getAllPermissions();
        $formatted = [];
        
        foreach ($permissions as $controller => $config) {
            $formatted[] = [
                'controller' => $controller,
                'module' => $config['module'] ?? $controller,
                'actions' => $config['actions'] ?? []
            ];
        }
        
        return $formatted;
    }
}