//
//  UIViewController+Extension.swift
//  PhoneManager
//
//  Created by edy on 2025/3/21.
//

import UIKit

extension UIViewController {
    
    func setStatusBarStyle(style:UIStatusBarStyle) {
        
        guard let nav = self.navigationController as? BaseNavViewController else {return}
        
        nav.barStatyl = style
    }
    
    func setStatusBarHidden(isHidden:Bool) {
        
        guard let nav = self.navigationController as? BaseNavViewController else {return}
        
        nav.barHidden = isHidden
    }

    class func topMostViewController() -> UIViewController? {
        guard let rootViewController = UIApplication.shared.keyWindow?.rootViewController else {
            return nil
        }
        return self.topMostViewController(of: rootViewController)
    }

    private static func topMostViewController(of viewController: UIViewController) -> UIViewController {
        // 处理模态弹出的视图控制器
        if let presentedViewController = viewController.presentedViewController {
            return self.topMostViewController(of: presentedViewController)
        }
        
        // 处理 UINavigationController
        if let navigationController = viewController as? UINavigationController,
           let visibleViewController = navigationController.visibleViewController {
            return self.topMostViewController(of: visibleViewController)
        }
        
        // 处理 UITabBarController
        if let tabBarController = viewController as? UITabBarController,
           let selectedViewController = tabBarController.selectedViewController {
            return self.topMostViewController(of: selectedViewController)
        }
        
        // 处理子控制器
        for subview in viewController.view?.subviews ?? [] {
            if let childViewController = subview.next as? UIViewController {
                return self.topMostViewController(of: childViewController)
            }
        }
        
        return viewController
    }
    
}


