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

import UIKit
import DDLogKit_Private
import DDPersistenceKit_Private

class AppDelegate: UIResponder, UIApplicationDelegate {

    public var allowOrentitaionRotation : Bool = false
        
    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 application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        handlePayCallbackURL(url)
        return true
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        JPUSHService.resetBadge()
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    // 注册通知
    func application(_ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
        
        // 将此设备deviceToken存进钥匙串
        if let data = DDKC.queryItem(credentials: DDKeychain.Credentials(itemKey: deviceId)) {
            let tokenString = String(data: data, encoding: .utf8)
            DDLog(message: "设备唯一标识:\(tokenString ?? "")")
            USER.deviceId = tokenString
        }else{
            let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
            DDLog(message: "设备唯一标识:\(tokenString)")
            USER.deviceId = tokenString
            
            let credentials = DDKeychain.Credentials(itemKey: deviceId,itemValue: tokenString)
            let _ = DDKC.addItem(credentials: credentials)
        }
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        DDLog(message: ("did fail to register for remote notification with error ", error))
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        JPUSHService.handleRemoteNotification(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 {
            // 从通知页面进入应用
            DDLog(message:"ios12从通知页面进入应用")
        }else{
            // 从通知设置进入应用
            DDLog(message:"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)
            if USER.isLogin == true {
                // 刷新个数,要在refreshToken之后
                MCOUNT.newestMessage()
                
                if GROUP.isOrderPushNotification(userInfo: userInfo) == true {
                    // 新订单的处理
                    TOOL.dealWithOrderPushNotification { userInfo in
                        TOOL.playAlertWith(userInfo: userInfo)
                        TOOL.playVoiceWith(userInfo: userInfo)
                    }
                }else{
                    // 普通通知弹框
                    if GROUP.isShowPopPushNotification(userInfo: userInfo) == true {
                        TOOL.dealWithOrderPushNotification { userInfo in
                            TOOL.playAlertWith(userInfo: userInfo)
                        }
                    }
                    // 普通声音
                    if GROUP.isBroadcastPushNotification(userInfo: userInfo) == true {
                        TOOL.playVoiceWith(userInfo: userInfo)
                    }
                    
                    completionHandler(1 << 1 | 1 << 2)
                }
            }
        }
        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 {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
      }
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]?) {
        DDLog(message:"通知授权状态\(status)")

        JPUSHService.registrationIDCompletionHandler { errorCode, registrationID in
            USER.regId = registrationID
            DDLog(message:"registrationID:\(JPUSHService.registrationID())")
        }
        
        if status != .statusAuthorized {
            NOTIAUTHTOOL.requestNotiAuthRelay.accept(nil)
        }else{
            NOTIAUTHTOOL.cancelNotiAuthRelay.accept(nil)
        }
    }

}

func handlePayCallbackURL(_ url: URL) {
    guard url.scheme?.lowercased() == "myappscheme" else { return }
    guard url.host?.lowercased() == "paycallback" else { return }
    let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    let orderNo = components?.queryItems?.first(where: { $0.name == "orderNo" })?.value
    var userInfo: [String: Any] = [:]
    if let orderNo = orderNo {
        userInfo["orderNo"] = orderNo
    }
    NotificationCenter.default.post(name: WebViewPayCallbackNotification, object: nil, userInfo: userInfo)
}
