//
//  CCCommonFile.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/2/23.
//

import Foundation
import UIKit
import DeviceKit
//import SDWebImage
import SVProgressHUD
//import iosMath
//import SwifterSwift

//MARK: -  判断用户是否是vip
var isVip:Int = 1  //判断用户是否是vip

//MARK: -  固定参数
//屏幕宽度
let WIDTH = UIScreen.main.bounds.size.width;
//屏幕高度
let HEIGHT = UIScreen.main.bounds.size.height;

//屏幕宽度
let KScreenWidth = UIScreen.main.bounds.size.width;
//屏幕高度
let KScreenHeight = UIScreen.main.bounds.size.height;

//设置tabbar高度
let KTabbarHeight:CGFloat = 49.0

//获取状态栏的高度
let KStatusBarHeight = UIApplication.shared.statusBarFrame.size.height
//[[UIApplication sharedApplication] statusBarFrame].size.height;

//导航栏高度
let KNavigationBarHeight:CGFloat = 44.0

//安全区高度： Tabbar safe bottom margin.
let  KTabbarSafeBottomMargin:CGFloat = (IS_IPHONE_X ? 34.0 : 0.0)


let IS_IPHONE_X =  (UIScreen.instancesRespond(to: #selector(getter: UIScreen.main.currentMode)) ? CGSize(width: 1125, height: 2436).equalTo((UIScreen.main.currentMode?.size)!) : false)

//动态图片高度
let KDynamic_Cell_Orginal_Height:CGFloat = KHZSize(100)
let KDynamic_Image_Back_Height_One:CGFloat = KHZSize(196)
let KDynamic_Image_Back_Height_Two:CGFloat = KHZSize(148)
let KDynamic_Image_Back_Height_Three:CGFloat = KHZSize(198)
let KDynamic_Image_Back_Height_Four:CGFloat = KHZSize(296)

//附近的人
let KInvite_Cell_orginal_Height:CGFloat = KHZSize(100)

///1. 获得当前窗口
var KWindow: UIWindow? {
    get{
        var window:UIWindow? = nil
        UIApplication.shared.connectedScenes.forEach { us in
            if let uws = us as? UIWindowScene , uws.session.role.rawValue == "UIWindowSceneSessionRoleApplication" {
                window = uws.windows.first
            }
        }
        return window
        
//        if let windowsScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
//            return windowsScene.windows.first
//        }
//        else {
//            return nil
//        }
//        if let app = UIApplication.shared.delegate as? AppDelegate {
//            return app.window
//        }
//        return nil
    }
    
//    if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
//               let firstWindow = windowScene.windows.first{
//                if let delegate = windowScene.delegate as? UIWindowSceneDelegate,
//                   let window = delegate.window as? UIWindow{
//                    print(firstWindow)
//                    print(window)
//                }
//                if let key = windowScene.keyWindow{
//                    print(key)
//                }
//            }
}

var KAppDelegate: AppDelegate? {
    get{
        if let app = UIApplication.shared.delegate as? AppDelegate {
            return app
        }
        return nil
    }
}




// 底部安全高度
public let bottomSafeHeight: CGFloat = {
    let statusBarHeight = UIApplication.shared.statusBarFrame.height
    if statusBarHeight == 20.0 {
        return 0.0
    } else {
        return 34.0
    }
}()

// 底部抽屉栏高度
public let KTabbarH: CGFloat = {
    let statusBarHeight = UIApplication.shared.statusBarFrame.height
    if statusBarHeight == 20.0 {
        return 49.0
    }else {
        return 49.0 + 34.0
    }
}()
        
// 自动打卡时间
let KAutoSignClubTime:Double = 600

//通知
let Notification_Name_Public_Dymanic_Refresh:String = "notificationNamePublicDymanicRefresh"
let Notification_Name_Unread_Count:String = "notificationNameUnreadCount"

//key
let Total_Unread_Count_Key:String = "TotalUnreadCountKey"

//@available(iOS 11.0, *)
//@available(iOS 11.0, *)
//func KNavHeight() -> Float {
//
//    //导航栏高度也可以根据UINavigationController动态获取
//    var navh: Float = 44.0
//
//    if #available(iOS 12.0, *)
//    {
//        navh += Float((UIApplication.shared.delegate?.window?!.safeAreaInsets.top)!)
//    }else if IS_IPHONE_X
//    {
//        navh += Float((UIApplication.shared.delegate?.window?!.safeAreaInsets.top)!)
//    }else
//    {
//        navh += Float(UIApplication.shared.statusBarFrame.size.height)
//    }
//    return navh
//}

//判断屏幕尺寸是否是5.5尺寸及一下
let KScreenSizeNeedShrink: Bool = {
    
    var isShrink: Bool = false
    
    let device = Device.current
    if device == .iPhone4s || device == .iPhoneSE || device == .iPhone6 || device == .iPhone6s || device == .iPhone7
    {
        isShrink = true
    }
    
    return isShrink
}()





// Users/macpro/Desktop/KTLegalAdvice/KTLegalAdvice/KTImageBundle.bundle
//MARK: -  获取图片路径
func Kimage(imageName:String) -> UIImage {
    
    let bundlePath = Bundle.main.path(forResource: "KTImageBundle", ofType: "bundle")
    let successPath = bundlePath?.appendingFormat("/Image/%@", imageName) //这里不带png格式也可以读取到
    let image = UIImage.init(contentsOfFile: successPath!)
    
    return image!
}

//MARK: -  hex转rgb
func KColorFromRGB(rgbValue: UInt32,alpha: CGFloat) -> UIColor {
    
    let temp = UInt32(255.0)
    
    let red = ((rgbValue & 0xFF0000) >> 16) / temp
    let green = ((rgbValue & 0xFF00) >> 8) / temp
    let blue = (rgbValue & 0xFF) / temp
    
    return UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: alpha)
}

//MARK: -  控件按照屏宽比例尺寸
//横向
func KHZSize(_ h:CGFloat) -> CGFloat {
    
    return h*KScreenWidth/375.0
}

//纵向
func KVZSize(_ v:CGFloat) -> CGFloat {
    
    return v*KScreenHeight/667.0       //667.0
}

//MARK: -  字体
//PingFang-SC-Regular，PingFang-SC-Medium，PingFangSC-Light，PingFangSC-Medium

func KFont_Regular(_ size:CGFloat) -> UIFont {
    
    return UIFont(name: "PingFangSC-Regular", size: size) ?? UIFont.systemFont(ofSize: size)
}

func KFont_Medium(_ size:CGFloat) -> UIFont {
    
    return UIFont(name: "PingFangSC-Medium", size: size) ?? UIFont.systemFont(ofSize: size)
}


func KFont_Helvetica(_ size:CGFloat) -> UIFont {
    
    return UIFont(name: "Helvetica", size: size) ?? UIFont.systemFont(ofSize: size)
}

func KFont_Semibold(_ size:CGFloat) -> UIFont {
    
    return UIFont(name: "Semibold", size: size) ?? UIFont.systemFont(ofSize: size)
}

//DIN-Medium
func KFont_DIN_Medium(_ size:CGFloat) -> UIFont {
    
    return UIFont(name: "DIN-Medium", size: size) ?? UIFont.systemFont(ofSize: size)
}

func KFont_Light(_ size:CGFloat) -> UIFont {
    
    return UIFont(name: "PingFangSC-Light", size: size) ?? UIFont.systemFont(ofSize: size)
}


//MARK: -  文字颜色
let KTextColor_Zero = UIColor(hexString: "#000000")
let KTextColor_C5 = UIColor(hexString: "#C5C5D1")
let KTextColor_Three = UIColor(hexString: "#333333")
let KTextColor_Six = UIColor(hexString: "#666666")
let KTextColor_Eight = UIColor(hexString: "#888888")
let KTextColor_Nine = UIColor(hexString: "#999999")
let KTextColor_White = UIColor(hexString: "#ffffff")
let KTextColor_B3 = UIColor(hexString: "#B3B3B3")
let KTextColor_97 = UIColor(hexString: "#979797")
let KTextColor_bd = UIColor(hexString: "#BDBDBD")
let KTextColor_41 = UIColor(hexString: "#414141")
let KTextColor_C4 = UIColor(hexString: "#C4C4D0")
let KTextColor_63 = UIColor(hexString: "#636363")
let KTextColor_70 = UIColor(hexString: "#707070")
let KTextColor_F5 = UIColor(hexString: "#F5F5F5")
let KTextColor_89 = UIColor(hexString: "#898989")
let KTextColor_7B = UIColor(hexString: "#7B7B7B")
let KTextColor_74 = UIColor(hexString: "#7B7B7B")


//MARK: -  线条颜色
let KLineColor_F1 = UIColor(hexString: "#F1F1F1")
let KLineColor_F8 = UIColor(hexString: "#F8F8F8")
let KTLineColor_Zero = UIColor(hexString: "#000000")

let KColor_68 = UIColor(hexString: "#686872")


//MARK: -  其他颜色
//let KMain_Color = UIColor(hexString: "#111118")
let KMain_Color = UIColor(hexString: "#5326D6")
let KGreen_Color = UIColor(hexString: "#A3F311")
let KDeepOrange_Color = /*UIColor(hexString: "#f5806c")*/UIColor.orange
let KShallowOrange_Color = UIColor(hexString: "#fec0b3")
//let KNav_Text_Color = KTextColor_C5
let KNav_Text_Color = KDeepOrange_Color
let KMainRed_Color = UIColor(hexString: "#af0100")

func KGreen_Color(_ alpha:CGFloat) -> UIColor {
    
//    return UIColor(hexString: "#A3F311", alpha: alpha)
    return UIColor(hexString: "#A3F311")

}




//MARK: -  NotificationCenter 通知中心名称
let NOTIFICATION_NAME_REMOT_PUST = "remotePush"


//MARK: -  修改view四个圆角
//typealias是给现有的类型(包括系统和自定义的)进行重新命名
typealias KCornersRadius = (topLeft: CGFloat, topRight: CGFloat, bottomLeft: CGFloat, bottomRight: CGFloat)
//创建Path
func KCreatePath(bounds:CGRect, cornersRadius:KCornersRadius) -> CGPath {
    let minX = bounds.minX
    let minY = bounds.minY
    let maxX = bounds.maxX
    let maxY = bounds.maxY
    
    let topLeftCenterX = minX + cornersRadius.topLeft
    let topLeftCenterY = minY + cornersRadius.topLeft
    let topRightCenterX = maxX - cornersRadius.topRight
    let topRightCenterY = minY + cornersRadius.topRight
    let bottomLeftCenterX = minX + cornersRadius.bottomLeft
    let bottomLeftCenterY = maxY - cornersRadius.bottomLeft
    let bottomRightCenterX = maxX - cornersRadius.bottomRight
    let bottomRightCenterY = maxY - cornersRadius.bottomRight
    
    let path = CGMutablePath()
    path.addArc(center: CGPoint(x: topLeftCenterX, y: topLeftCenterY), radius: cornersRadius.topLeft, startAngle: CGFloat(Double.pi), endAngle: CGFloat(3 * Double.pi / 2.0), clockwise: false)
    path.addArc(center: CGPoint(x: topRightCenterX, y: topRightCenterY), radius: cornersRadius.topRight, startAngle: CGFloat(3 * Double.pi / 2.0), endAngle: 0, clockwise: false)
    path.addArc(center: CGPoint(x: bottomRightCenterX, y: bottomRightCenterY), radius: cornersRadius.bottomRight, startAngle: 0, endAngle: CGFloat(Double.pi / 2.0), clockwise: false)
    path.addArc(center: CGPoint(x: bottomLeftCenterX, y: bottomLeftCenterY), radius: cornersRadius.bottomLeft, startAngle: CGFloat(Double.pi / 2.0), endAngle: CGFloat(Double.pi), clockwise: false)
    path.closeSubpath()
    
    return path
}

//MARK: -  验证
//MARK: 验证邮箱
func validateEmail(email: String) -> Bool {
    if email.count == 0 {
        return false
    }
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    let emailTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
    return emailTest.evaluate(with: email)
}

//MARK: 验证手机号
func isPhoneNumber(phoneNumber:String) -> Bool {
    if phoneNumber.count == 0 {
        return false
    }
//    let mobile = "^1([3589][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$"
    //判断开头为1，总长11位
    let mobile = "^1\\d{10}$"

    let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile)
    if regexMobile.evaluate(with: phoneNumber) == true {
        return true
    }else
    {
        return false
    }
}

//MARK: 密码正则  6-8位字母和数字组合
func isPasswordRuler(password:String) -> Bool {
    let passwordRule = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,8}$"
    let regexPassword = NSPredicate(format: "SELF MATCHES %@",passwordRule)
    if regexPassword.evaluate(with: password) == true {
        return true
    }else
    {
        return false
    }
}


//获取当前版本号
let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
//获取历史版本号
let sandboxVersion = UserDefaults.standard.object(forKey: "CFBundleShortVersionString") as? String ?? ""

//版本比较
//        if currentVersion.compare(sandboxVersion) == ComparisonResult.orderedDescending {
//            //发现新版本 存储当前的版本到沙盒
//            UserDefaults.standard.set(currentVersion, forKey: "CFBundleShortVersionString")
//        }

//获取app信息
let infoDictionary : Dictionary = Bundle.main.infoDictionary!
//程序名称
let appDisplayName : String = infoDictionary["CFBundleDisplayName"] as! String
//版本号
let majorVersion :String = infoDictionary ["CFBundleShortVersionString"] as! String
//build号
let minorVersion :String = infoDictionary ["CFBundleVersion"] as! String

//获取设备信息
//ios版本
let iosVersion : NSString = UIDevice.current.systemVersion as NSString
//设备udid
let identifierNumber  = UIDevice.current.identifierForVendor
//设备名称
//let deviceName : String = UIDevice.current.name
//系统名称
//let systemName : String = UIDevice.current.systemName
//设备型号
let deviceModel = UIDevice.current.model
//设备区域化型号如A1533
let localizedModel = UIDevice.current.localizedModel



/// 屏幕宽度
func screenWidth() -> CGFloat {
    return UIScreen.main.bounds.size.width
}

/// 屏幕高度
func screenHeight() -> CGFloat {
    return UIScreen.main.bounds.size.height
}

/// 获取设备版本号
func deviceName() -> String {
    var systemInfo = utsname()
    uname(&systemInfo)
    let machineMirror = Mirror(reflecting: systemInfo.machine)
    let identifier = machineMirror.children.reduce("") { identifier, element in
        guard let value = element.value as? Int8, value != 0 else { return identifier }
        return identifier + String(UnicodeScalar(UInt8(value)))
    }
    switch identifier {
    case "iPod5,1":                                 return "iPod Touch 5"
    case "iPod7,1":                                 return "iPod Touch 6"
    case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
    case "iPhone4,1":                               return "iPhone 4s"
    case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
    case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
    case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
    case "iPhone7,2":                               return "iPhone 6"
    case "iPhone7,1":                               return "iPhone 6 Plus"
    case "iPhone8,1":                               return "iPhone 6s"
    case "iPhone8,2":                               return "iPhone 6s Plus"
    case "iPhone9,1":                               return "iPhone 7 (CDMA)"
    case "iPhone9,3":                               return "iPhone 7 (GSM)"
    case "iPhone9,2":                               return "iPhone 7 Plus (CDMA)"
    case "iPhone9,4":                               return "iPhone 7 Plus (GSM)"
        
    case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
    case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
    case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
    case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
    case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
    case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
    case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
    case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
    case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
    case "iPad6,7", "iPad6,8":                      return "iPad Pro"
    case "AppleTV5,3":                              return "Apple TV"
    case "i386", "x86_64":                          return "Simulator"
    default:                                        return identifier
    }
}

/// 获取iPhone名称
func iphoneName() -> String {
    return UIDevice.current.name
}

/// 获取app版本号
func appVersion() -> String {
    return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
}

/// 获取电池电量
func batteryLevel() -> CGFloat {
    return CGFloat(UIDevice.current.batteryLevel)
}

/// 当前系统名称
func systemName() -> String {
    return UIDevice.current.systemName
}

/// 当前系统版本号
func systemVersion() -> String {
    return UIDevice.current.systemVersion
}

/// 通用唯一识别码UUID
func UUID() -> String {
    return (UIDevice.current.identifierForVendor?.uuidString)!
}

/// 获取当前设备IP
func deviceIP() -> String? {
    var addresses = [String]()
    var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while (ptr != nil) {
            let flags = Int32(ptr!.pointee.ifa_flags)
            var addr = ptr!.pointee.ifa_addr.pointee
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                        if let address = String(validatingUTF8:hostname) {
                            addresses.append(address)
                        }
                    }
                }
            }
            ptr = ptr!.pointee.ifa_next
        }
        freeifaddrs(ifaddr)
    }
    return addresses.first
}

/// 私有方法
private func blankof<T>(type:T.Type) -> T {
    let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size)
    let val = ptr.pointee
    ptr.deinitialize(count: 0)
    return val
}

/// 获取总内存大小
func totalRAM() -> Int64 {
    var fs = blankof(type: statfs.self)
    if statfs("/var",&fs) >= 0{
        return Int64(UInt64(fs.f_bsize) * fs.f_blocks)
    }
    return -1
}

/// 获取当前可用内存
func availableRAM() -> Int64 {
    var fs = blankof(type: statfs.self)
    if statfs("/var",&fs) >= 0{
        return Int64(UInt64(fs.f_bsize) * fs.f_bavail)
    }
    return -1
}

/// 获取电池当前的状态，共有4种状态
func batteryState() -> String {
    let device = UIDevice.current
    if device.batteryState == UIDevice.BatteryState.unknown {
        return "unknown"
    } else if device.batteryState == UIDevice.BatteryState.unplugged {
        return "unplugged"
    } else if device.batteryState == UIDevice.BatteryState.charging {
        return "charging"
    } else if device.batteryState == UIDevice.BatteryState.full {
        return "full"
    }
    return ""
}

/// 获取当前语言
func deviceLanguage() -> String {
    return Locale.preferredLanguages[0]
}

func getCurrentVC() -> UIViewController?{
    
    var result:UIViewController?
    
    //获取默认的window
    var window:UIWindow = UIApplication.shared.keyWindow!
    
    if window.windowLevel != .normal
    {
        let windows = UIApplication.shared.windows
        for tmpWin in windows {
            
            if tmpWin.windowLevel == .normal {
                window = tmpWin
                break
            }
        }
    }
    
    //获取window的rootViewController
    result = window.rootViewController
    while (result?.presentedViewController != nil) {
        result = (result?.presentedViewController!)
    }
    
    if result!.isKind(of: UITabBarController.self) {
        
        result = (result as! UITabBarController).selectedViewController
    }
    
    if result!.isKind(of: UINavigationController.self) {
        result = (result as! UINavigationController).visibleViewController
    }
    
    return result
}


//MARK: -  获取当前时间
func KGetCurrentTime() -> String {
    let date = Date()
    let dateFormat = DateFormatter()
    dateFormat.dateFormat="yyyy-MM-dd HH:mm"
    let time: String = dateFormat.string(from: date)

    return time
}
