//
//  AppDelegate.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/3.
//

import UIKit
import CocoaDebug

class AppDelegate: UIResponder, UIApplicationDelegate {

    public var allowOrentitaionRotation : Bool = false
    
    public var userInfo : [AnyHashable:Any]?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // 通知
        JGInforCollectionAuth.jCollectionAuth({ authInfo in
            authInfo.isAuth = true
        })
        
        let entity = JPUSHRegisterEntity()
        entity.types = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 5
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        #if DEBUG
        JPUSHService.setup(withOption: launchOptions, appKey: JPushKey, channel: "App Store", apsForProduction: false)
        #else
        JPUSHService.setup(withOption: launchOptions, appKey: JPushKey, channel: "App Store", apsForProduction: true)
        #endif
    
        return true
    }

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if allowOrentitaionRotation == true {
            return .allButUpsideDown
        }
        return .allButUpsideDown
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        JPUSHService.resetBadge()
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    // 注册通知
    func application(_ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("deviceToken:\(tokenString)")
        JPUSHService.registerDeviceToken(deviceToken)
        USER.deviceToken = tokenString
        print("registrationID:\(JPUSHService.registrationID())")
        USER.regId = JPUSHService.registrationID()
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("did fail to register for remote notification with error ", error)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
        print("收到通知", userInfo)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
    }
    
    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
}

extension AppDelegate : JPUSHRegisterDelegate {
    @available(iOS 12.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification) {
        if notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true {
            // 从通知页面进入应用
            print("ios12从通知页面进入应用")
        }else{
            // 从通知设置进入应用
            print("ios12从通知设置进入应用")
        }
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
                                 withCompletionHandler completionHandler: ((Int) -> Void)) {
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true {
            JPUSHService.handleRemoteNotification(userInfo)
            ACCEPTORDERTOOL.open(userInfo: userInfo)
            TOOL.playVoiceWith(userInfo: userInfo)
            print("ios10 前台")
        }
        completionHandler(0)
      }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: (() -> Void)) {
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true {
//            self.userInfo = userInfo
            JPUSHService.resetBadge()
            UIApplication.shared.applicationIconBadgeNumber = 0
            JPUSHService.handleRemoteNotification(userInfo)
            print("ios10 后台")
        }
        completionHandler()
      }
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]?) {
        print("通知授权状态\(status)")
        if status != .statusAuthorized {
            NOTIAUTHTOOL.requestNotiAuthRelay.accept(nil)
        }else{
            NOTIAUTHTOOL.cancelNotiAuthRelay.accept(nil)
        }
    }

}
