//
//  UIViewController+GDNavigation.swift
//  GDKit
//
//  Created by SJ on 2022/1/15.
//

import UIKit

// MARK: - 获取当前控制器
extension UIViewController {
    
    //    获取当前正呈现的UIViewController
    static var current:UIViewController? {
        let delegate  = UIApplication.shared.delegate as? AppDelegate
        var current = delegate?.window?.rootViewController
        
        while (current?.presentedViewController != nil)  {
            current = current?.presentedViewController
        }
        
        if let tabbar = current as? UITabBarController , tabbar.selectedViewController != nil {
            current = tabbar.selectedViewController
        }
        
        while let navi = current as? UINavigationController , navi.topViewController != nil  {
            current = navi.topViewController
        }
        return current
    }
    
    //获取UINavigationController的topViewController
    static var navTopViewController: UIViewController? {
        let delegate  = UIApplication.shared.delegate as? AppDelegate
        var current = delegate?.window?.rootViewController
        
        if let tabbar = current as? UITabBarController , tabbar.selectedViewController != nil {
            current = tabbar.selectedViewController
        }
        
        while let navi = current as? UINavigationController , navi.topViewController != nil  {
            current = navi.topViewController
        }
        return current
    }
    
    class func classFromString(_ className:String) -> UIViewController? {
        //1、获swift中的命名空间名
        var name = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String
        //2、如果包名中有'-'横线这样的字符，在拿到包名后，还需要把包名的'-'转换成'_'下横线
        name = name?.replacingOccurrences(of: "-", with: "_")
        //3、拼接命名空间和类名，”包名.类名“
        let fullClassName = name! + "." + className
        //通过NSClassFromString获取到最终的类，由于NSClassFromString返回的是AnyClass，这里要转换成UIViewController.Type类型
        guard let classType = NSClassFromString(fullClassName) as? UIViewController.Type else {
            //fatalError("转换失败")
            return nil
        }
        return classType.init()
    }
    
    func bs_popToRootViewController(animated: Bool) {
        let vcs = self.navigationController?.popToRootViewController(animated: true)
        if vcs != nil {
            self.tabBarController?.tabBar.isHidden = false
        }
    }
    
}

// MARK: - 创建RightBarButtonItem
extension UIViewController {
    
    public func bs_setupRightButton(title: String? = nil, color: UIColor? = nil, image: UIImage? = nil, font: UIFont? = nil, imageColor: UIColor? = nil, reset: Bool = false) {
        
        var button: UIButton?
        
        if let rightBarButtonItems = self.navigationItem.rightBarButtonItems,
           rightBarButtonItems.count > 0,
           reset == false {
            for view in rightBarButtonItems {
                if let rightButton = view.customView as? UIButton {
                    button = rightButton
                }
            }
            
        } else {
            let rightButton = UIButton(type: .custom)
            rightButton.frame = CGRect(x: 0, y: 0, width: 70, height: 44)
            rightButton.addTarget(self, action: #selector(clickedNavRight), for: .touchUpInside)
            rightButton.contentHorizontalAlignment = .right
            let rightItem = UIBarButtonItem(customView: rightButton)
            let negativeSeperator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
            negativeSeperator.width = -0
            self.navigationItem.rightBarButtonItems = [negativeSeperator,rightItem]
            button = rightButton
        }
        
        if font == nil {
            button?.titleLabel?.font = UIFont.PFSCM(ofSize: 16)
        } else {
            button?.titleLabel?.font = font
        }
        if var image = image {
            if let imageColor = imageColor {
                image = image.withRenderingMode(.alwaysTemplate)
                button?.tintColor = imageColor
            } else {
                image = image.withRenderingMode(.alwaysOriginal)
            }
            button?.setImage(image, for: .normal)
            button?.setImage(image, for: .highlighted)
        }
        button?.setTitle(title, for: .normal)
        button?.setTitleColor(color, for: .normal)
        
    }
    
    @objc func clickedNavRight() {
        
    }
    
}


// MARK: - 配置导航栏
extension UIViewController {
    
    public func bs_config() {
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        
        self.bs_setupNavigationAttributed(.white)
        self.bs_setupTitleAttributedAll()
        self.bs_setupLeftButton()
        self.bs_openPopGesture()
    }
    
    
    ///设置导航条属性
    func bs_setupNavigationAttributed(_ color: UIColor = UIColor.white) {
        //设置状态栏
        //UIApplication.shared.statusBarStyle = .default
        //self.preferredStatusBarStyle = .default
        
        self.navigationController?.navigationBar.barTintColor = color
        self.navigationController?.navigationBar.setBackgroundImage(UIImage.from(color: color), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage() //隐藏下划线
    }
    
    
    ///设置全局标题属性
    func bs_setupTitleAttributedAll(font: UIFont = UIFont.PFSCM(ofSize: 16), color: UIColor = .black) {
        let titleDict = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: color]
        self.navigationController?.navigationBar.titleTextAttributes = titleDict
    }
    
    ///设置独立标题属性
    func bs_setupTitleAttributed(title: String, font: UIFont = UIFont.PFSCM(ofSize: 16), color: UIColor = .black, reset: Bool = false) {
        var titleLabel: UILabel?
        if let label = self.navigationItem.titleView as? UILabel,
           reset == false {
            titleLabel = label
        } else {
            let label = UILabel()
            titleLabel = label
        }
        
        titleLabel?.font = font
        titleLabel?.textColor = color
        titleLabel?.text = title
        self.navigationItem.titleView = titleLabel
    }
    
    
    ///返回按钮
    func bs_setupLeftButton(title: String? = nil, color: UIColor? = nil, image: UIImage? = UIImage(named: "back_icon"), reset: Bool = false) {
        
        var button: UIButton?
        
        if let leftBarButtonItems = self.navigationItem.leftBarButtonItems,
           leftBarButtonItems.count > 0,
           reset == false {
            for view in leftBarButtonItems {
                if let leftButton = view.customView as? UIButton {
                    button = leftButton
                }
            }
            
        } else {
            let leftButton = UIButton(type: .custom)
            leftButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
            leftButton.addTarget(self, action: #selector(callBackAction), for: .touchUpInside)
            leftButton.contentHorizontalAlignment = .left
            leftButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
            let leftItem = UIBarButtonItem(customView: leftButton)
            let negativeSeperator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
            negativeSeperator.width = -0
            self.navigationItem.leftBarButtonItems = [negativeSeperator,leftItem]
            button = leftButton
        }
        
        var image = image
        if color != nil {
            image = image?.withRenderingMode(.alwaysTemplate)
        } else {
            image = image?.withRenderingMode(.alwaysOriginal)
        }
        button?.setImage(image, for: .normal)
        button?.setImage(image, for: .highlighted)
        button?.titleLabel?.font = UIFont.PFSCM(ofSize: 16)
        button?.setTitle(title, for: .normal)
        button?.setTitleColor(color, for: .normal)
        button?.tintColor = color
        
    }
    
    
    ///返回按钮响应
    @objc func callBackAction() {
        let selector = NSSelectorFromString("onCallBackAction")
        if self.responds(to: selector) == true {
            self.performSelector(onMainThread: selector, with: nil, waitUntilDone: false)
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    /**
     打开系统手势返回
     */
    @objc func bs_openPopGesture() {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    /**
     关闭系统手势返回
     */
    @objc func bs_closePopGesture() {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    ///修改导航栏背景色(全局)
    public func bs_navBackgroundColor(_ color: UIColor) {
        self.navigationController?.view.backgroundColor = color
        
        //解决iOS13后backgroundColor设置无效的问题，参考https://developer.apple.com/forums/thread/682420
        if #available(iOS 13.0, *) {
            let newAppearance = UINavigationBarAppearance()
            newAppearance.configureWithOpaqueBackground()
            newAppearance.backgroundColor = color
            newAppearance.shadowImage = UIImage()
            newAppearance.shadowColor = nil
            //newAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .medium)]
            let appearance = self.navigationController?.navigationBar ?? UINavigationBar.appearance()
            appearance.standardAppearance = newAppearance
            appearance.scrollEdgeAppearance = appearance.standardAppearance
        } else {
            bs_setupNavigationAttributed(color)
        }
    }
    
}
