//
//  Applegate(JPush).swift
//  galaxy
//
//  Created by edy on 2024/3/27.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AuthenticationServices

extension AppDelegate: JPUSHRegisterDelegate {
    
    // 注册JPush服务
    func registerJPushService(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        
        let entity: JPUSHRegisterEntity =  JPUSHRegisterEntity()
        entity.types =  Int(JPAuthorizationOptions.alert.rawValue |
                            JPAuthorizationOptions.badge.rawValue  |
                            JPAuthorizationOptions.sound.rawValue  |
                            JPAuthorizationOptions.providesAppNotificationSettings.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        
        // Required
        // init Push
        // notice: 2.1.5 版本的 SDK 新增的注册方法，改成可上报 IDFA，如果没有使用 IDFA 直接传 nil
        //初始化极光推送服务，调用了本 API 后，开启 JPush 推送服务，将会开始收集上报 SDK 业务功能所必要的用户个人信息
        //        [JPUSHService setupWithOption:launchOptions appKey:appKey
        //                              channel:channel
        //                     apsForProduction:isProduction
        //                advertisingIdentifier:advertisingId];
        
#if DEBUG
        let isProduction = false
#elseif TESTENV
        let isProduction = true
#elseif TESTENV
        let isProduction = true
#else
        let isProduction = true
#endif
        JPUSHService.setup(withOption:launchOptions,
                           appKey:YhConstant.Jpush.appKey,
                           channel:"appStore",
                           apsForProduction: isProduction)
    }
    
    //系统获取Token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenStr = deviceToken.map{String(format:"%02.2hhx", arguments: [$0]) }.joined()
        print("deviceToken:\(deviceTokenStr)")
        JPUSHService.registerDeviceToken(deviceToken)
        YHLoginManager.shared.deviceTokenModel.deviceToken = deviceTokenStr
    }
    //获取token 失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { //可选
        print("did Fail To Register For Remote Notifications With Error: \(error)")
        
#if DEBUG
        YHHUD.flash(message: error.localizedDescription)
#elseif TESTENV
        YHHUD.flash(message: error.localizedDescription)
#else
#endif
        
    }
    
    //点推送进来执行这个方法
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
        
        // 转换到消息tab
        YHLoginManager.shared.needJumpToMsgTabFlag = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            goToMessagePage()
        })
        
    }
    
    //后台进前台
    func applicationWillEnterForeground(_ application: UIApplication) {
        DispatchQueue.main.async {
            // 请求消息页面通知权限通知
            NotificationCenter.default.post(name: YhConstant.YhNotification.didReqeustNotifyPermissionNotification, object: nil)
        }
        YHOSSManager.share.getOSSID()
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: ((Int) -> Void)) {
        
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
        // 显示通知时需要刷新消息列表和消息未读总数
        DispatchQueue.main.async {
            // 请求消息未读总数通知
            NotificationCenter.default.post(name: YhConstant.YhNotification.didRequestUnreadMsgTotalCountNotification, object: nil)
            // 请求消息列表通知
            NotificationCenter.default.post(name: YhConstant.YhNotification.didRequestUnreadMsgListNotification, object: nil)
            //更新首页消息
            NotificationCenter.default.post(name: YhConstant.YhNotification.didRevMsgNotifiction, object: nil)
        }
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: (() -> Void)) {
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 系统要求执行这个方法
        completionHandler()
        
        // 转换到消息tab
        YHLoginManager.shared.needJumpToMsgTabFlag = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
//            NotificationCenter.default.post(name: YhConstant.YhNotification.didRevMsgNotifiction, object: nil)
            goToMessagePage()
        })
    }
    
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification) {
        
    }
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]?) {
        
    }
}

extension AppDelegate {
    
    func handleAppleLoginUser() {
        
        if #available(iOS 13.0, *) {
            // 注意 存储用户标识信息需要使用钥匙串来存储 这里使用NSUserDefaults 做的简单示例
            let userIdentifier = UserDefaults.standard.value(forKey: "appleID") as? String
            if let userIdentifier = userIdentifier {
                let appleIDProvider =  ASAuthorizationAppleIDProvider()
                appleIDProvider.getCredentialState(forUserID: userIdentifier) {
                    credentialState, error in
                    
                    switch credentialState {
                    case .authorized:
                        // 授权状态有效
                        break
                    case .revoked:
                        // 苹果账号登录的凭据已被移除，需解除绑定并重新引导用户使用苹果登录
                        break
                    case .notFound:
                        // 未登录授权，直接弹出登录页面，引导用户登录
                        break
                    case .transferred:
                        // 授权AppleID提供者凭据转移
                        break
                    default:
                        break
                    }
                }
            }
        }
    }
}
