//
//  AppDelegate.swift
//  QuickSearchLocation
//
//  Created by mac on 2024/4/10.
//

import UIKit
import AMapFoundationKit
import IQKeyboardManagerSwift
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        QSLTools.shared.isOpen = false
        UIApplication.shared.shortcutItems = []
        
        Thread.sleep(forTimeInterval: 0.5)
        IQKeyboardManager.shared.enable = true
        AMapServices.shared().apiKey = QSLConfig.MapKey
        QSLDeviceTool.shared.configure(autoRefresh: true)
        
        configNoti()
        
        return true
    }

    func configNoti(){
        UNUserNotificationCenter.current().delegate = self
    }
    
    // MARK: UISceneSession Lifecycle
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    }

    // 当 App 即将终止（退出）时调用
    func applicationWillTerminate(_ application: UIApplication) {
        print("App 即将退出")
        // 仅在 App 被用户主动退出或系统正常终止时触发（强制杀死进程时可能不调用）
        // 可在此做最后的数据保存（操作需快速完成，系统可能限制时间）
        ///埋点app退出
        
        QSEventHandle.gravityPush(eventName: QSLGravityConst.app_exit, eventProps: ["id": 02002])
    }
    
}

extension AppDelegate : UNUserNotificationCenterDelegate{
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        UserDefaults.standard.set(token, forKey: "deviceToken")
        
        UIPasteboard.general.string = token
        
        print("notification token: \(token)")

        QSLNetwork().request(.notiTokenReport(dict: ["deviceToken":token])) { response in
            
        } fail: { code, error in

        }
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("Foreground notification received: \(userInfo)")
        
        if(userInfo.keys.contains("urlScheme")){
            dealwithUserifo(scheme: userInfo["urlScheme"] as! String)
        }
        
        // 显示通知
        completionHandler([.alert, .sound, .badge])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo
        print("Notification tapped: \(userInfo)")
        
        if(userInfo.keys.contains("urlScheme")){
            dealwithUserifo(scheme: userInfo["urlScheme"] as! String)
        }
        
        completionHandler()
    }
    
    func dealwithUserifo(scheme: String){
        //这里要判断是否已经处于首页 如果在首页直接打开 不在首页等进首页再打开
        if(QSLTools.shared.isOpen){
            //处理urlScheme
            QSLTools.shared.urlScheme = ""
            QSLTools.shared.dealwithScheme(scheme)
            return
        }
        
        QSLTools.shared.urlScheme = scheme
    }
}

