//
//  CommonFunc.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/19.
//

import UIKit

typealias callBack<T> = (T) -> ()

typealias callOperBack = (String) -> ()

let cWindow:UIWindow? = {
    
    if #available(iOS 13, *) {
        return UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first(where: { $0.isKeyWindow })
    } else {
        return UIApplication.shared.keyWindow ?? UIWindow()
    }
    
}()

func formatFileSize(_ bytes: Double) -> String {
    let units = ["B", "KB", "MB", "GB", "TB"]
    var size = bytes
    var unitIndex = 0

    // 循环计算合适的单位
    while size >= 1000 && unitIndex < units.count - 1 {
        size /= 1000
        unitIndex += 1
    }

    // 格式化输出
    return String(format: "%.2f %@", size, units[unitIndex])
}

func timeFormatter() -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "h:mma"  // 注意这里的格式
    formatter.amSymbol = "AM"
    formatter.pmSymbol = "PM"
    return formatter.string(from: Date())
}

func weekFormatter() -> String {
    
    let formatter = DateFormatter()
    formatter.dateFormat = "EEEE, MMMM d"  // 自定义格式
    return formatter.string(from: Date())
}


func PMAlert(title:String? = nil, messsage:String , action:[String] = [] ,complate:@escaping(( UIAlertController ,Int)->Void) = { v , idx in} ) -> Void {
    let alertview = UIAlertController(title: title, message: messsage, preferredStyle: .alert)
    guard let root = cWindow?.rootViewController else { return }
    root.present(alertview, animated: true)
    if action.count > 0 {
        for (i,title) in action.enumerated() {
            let action = UIAlertAction(title: title, style: .default) { action in
                complate(alertview,i)
            }
            alertview.addAction(action)
        }
    }else{
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            alertview.dismiss(animated: true)
        }
    }
}


// MARK: - 分享
public func PhoneShare(_ items:[Any] ,parent:UIViewController) -> Void {
    let shareVc = UIActivityViewController(
        activityItems: items,
        applicationActivities: nil
    )
    parent.present(shareVc, animated: true)
}



public func Print(_ items: Any...) {
    
    #if DEBUG
    print(items)
    #else
//    print(items)
    #endif
}
