//
//  AppDelegate.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/4/11.
//

import UIKit
import IQKeyboardManagerSwift    
import Photos
import SVProgressHUD
import AppLovinSDK
import FirebaseCore
import FirebaseAnalytics
import Alamofire

@main
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
    
    var window: UIWindow?
    let hasLaunchedBeforeKey = "hasLaunchedBefore"
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        IQKeyboardManager.shared.enable = true
        self.window?.frame = UIScreen.main.bounds
        UNUserNotificationCenter.current().delegate = self
        //                let vc = AV_RootTabbarVC()
        //                self.window?.rootViewController = AV_NAVVC(rootViewController: vc)
        
        let userDefaults = UserDefaults.standard
        let initConfig = ALSdkInitializationConfiguration(sdkKey: "NLQHJDx4rcfd5IqhZf9nad2tIqFSH8SSKP3DXD18sTKUvV6tBfrH9_RPCGb6hvEn3NPXJDmUQCnvnKgHIT7Qn4") { builder in
            builder.mediationProvider = ALMediationProviderMAX
        }
        
        if userDefaults.bool(forKey: hasLaunchedBeforeKey) {
//            let vc = AV_LaunchLimitesVC()
            if userDefaults.bool(forKey: "iswindows"){
                // 不是第一次启动
                let vc = AV_RootPlayerVC()
                self.window?.rootViewController = AV_NAVVC(rootViewController: vc)
                ALSdk.shared().initialize(with: initConfig) { sdkConfig in
                    // Start loading ads

                }
            }else{
                // 不是第一次启动
                let vc = AV_LaunchLimitesVC()
                self.window?.rootViewController = AV_NAVVC(rootViewController: vc)
                ALSdk.shared().initialize(with: initConfig) { sdkConfig in
                    // Start loading ads
                    vc.createInterstitialAd()

                }
            }
            
//            self.window?.rootViewController = AV_NAVVC(rootViewController: vc)
        } else {
            // 第一次启动
            let vc = AV_SelectGenderVC()
            self.window?.rootViewController = AV_NAVVC(rootViewController: vc)
            userDefaults.set(true, forKey: hasLaunchedBeforeKey)
            
            setdispatch()
            stePermissions()
            let currentDate = Date()
            // 使用 UserDefaults 存储日期
            let defaults = UserDefaults.standard
            defaults.set(currentDate, forKey: "savedDate")
            
            ALSdk.shared().initialize(with: initConfig) { sdkConfig in
      
            }
            
        }
        
        self.window?.makeKeyAndVisible()
        
        // 强制设置浅色模式
        if #available(iOS 13.0, *) {
            window?.overrideUserInterfaceStyle = .light
            
        }
        
        return true
    }
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }
    
    func stePermissions(){
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                print("Permission granted")
            } else if let error = error {
                print("Permission denied: \(error.localizedDescription)")
            }
        }
        requestPhotoLibraryPermission()
        setNetwork()
        // 使用示例
        let healthManager = HealthManager()

        // 请求授权
        healthManager.requestAuthorization { (success, error) in
            if success {
                print("HealthKit authorization granted")
                
            } else if let error = error {
                print("HealthKit authorization failed with error: \(error.localizedDescription)")
            }
        }
    }
    
    func requestPhotoLibraryPermission() {
        // 检查相册权限状态
        let status = PHPhotoLibrary.authorizationStatus()
        
        // 根据权限状态进行处理
        switch status {
        case .authorized:
            // 用户已授权访问相册
            print("相册权限已授权")
        case .denied, .restricted:
            // 用户已拒绝访问相册或权限受限
            print("相册权限已拒绝或受限，请在设置中开启权限")
        case .notDetermined:
            // 用户尚未作出选择，请求相册权限
            PHPhotoLibrary.requestAuthorization {  (newStatus) in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        // 用户授权访问相册
                        print("用户已授权访问相册")
                    } else {
                        // 用户未授权访问相册
                        print("用户未授权访问相册")
                    }
                }
            }
        case .limited:
            print("用户已授权此应用程序访问有限的照片库")
        @unknown default:
            // 处理未知权限状态
            print("未知的相册权限状态")
        }
    }
    
    func setNetwork(){
        // 创建一个URL对象
        if let url = URL(string: "https://www.baidu.com/") {
            // 创建一个URLSession对象
            let session = URLSession.shared
            
            // 创建一个网络请求任务
            let task = session.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("网络请求出错：\(error)")

                }
            }
            
            // 开始网络请求任务
            task.resume()
        } else {
            print("URL无效")
        }
    }
}

func setdispatch(){
    // 使用信号量控制并发任务
    let dispatchGroup = DispatchGroup()
    
    // 请求跟踪授权并处理 IDFA
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        requestTrackingAuthorization { idfa in
            DispatchQueue.main.async {
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    StartManager.shared.idfaid = idfa
                    print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
                } else {
                    print("IDFA is not available or tracking authorization denied.")
                }
                dispatchGroup.leave()
            }
        }
    }
    
    // 获取本地 IP 地址
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        if let localIP = getLocalIPAddress() {
            DispatchQueue.main.async {
                print("Local IP Address: \(localIP)")
                StartManager.shared.localIP = localIP
                dispatchGroup.leave()
            }
        } else {
            DispatchQueue.main.async {
                print("Local IP Address not available")
                dispatchGroup.leave()
            }
        }
    }
    
    // 获取远程 IP 地址
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        getPublicIPAddress { publicIP in
            DispatchQueue.main.async {
                if let publicIP = publicIP {
                    print("Public IP Address: \(publicIP)")
                    StartManager.shared.publicIP = publicIP
                    print("Stored Public IP Address: \(StartManager.shared.publicIP ?? "N/A")")
                } else {
                    print("Public IP Address not available")
                }
                dispatchGroup.leave()
            }
        }
    }
    
    // 获取设备 ID
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        let deviceID = UIDevice.current.identifierForVendor?.uuidString
        DispatchQueue.main.async {
            StartManager.shared.devicID = deviceID
            print("Device ID: \(StartManager.shared.devicID ?? "N/A")")
            dispatchGroup.leave()
        }
    }
    
    // 所有任务完成后的操作
    dispatchGroup.notify(queue: .main) {
        print("All tasks are completed.")
    }
}
