import Flutter
import UIKit
import BackgroundTasks
import UserNotifications

@main
@objc class AppDelegate: FlutterAppDelegate {
    private var pushChannel: FlutterMethodChannel?
    private var notificationDelegate: UNUserNotificationCenterDelegate?
    
    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.shishi.dingwei.refresh", using: nil) { task in
            // 处理后台任务
        }
        ///设置推送
        setupPushNotifications();
        
        ///通知flutter打开了应用
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
            self?.pushChannel?.invokeMethod("applicationDidFinishLaunchingWithOptions", arguments: "")
        }
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    override func applicationDidEnterBackground(_ application: UIApplication) {
        pushChannel?.invokeMethod("applicationDidEnterBackground", arguments: "")
    }
    
    /// 设置推送通知
    func setupPushNotifications() {
        let controller = window?.rootViewController as! FlutterViewController
        
        // 创建推送通道
        pushChannel = FlutterMethodChannel(
            name: "com.example.app/push_notification",
            binaryMessenger: controller.binaryMessenger
        )
        
        // 设置方法调用处理
        pushChannel?.setMethodCallHandler { [weak self] call, result in
            switch call.method {
            case "getDeviceToken":
                self?.getDeviceToken(result: result)
            case "requestPermission":
                self?.requestNotificationPermission(result: result)
            default:
                result(FlutterMethodNotImplemented)
            }
        }
        
        // 创建单独的通知代理
        let delegate = NotificationDelegate(pushChannel: pushChannel!)
        UNUserNotificationCenter.current().delegate = delegate
        self.notificationDelegate = delegate
        
        // 请求推送权限
        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert, .sound, .badge]
        ) { granted, error in
            if granted {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            } else if let error = error {
                print("Error: \(error.localizedDescription)")
            }
        }
    }
    
    
    /// 获取设备令牌
    private func getDeviceToken(result: @escaping FlutterResult) {
        if let token = UserDefaults.standard.string(forKey: "deviceToken") {
            result(token)
        } else {
            result(nil)
        }
    }
    
    /// 请求推送权限
    private func requestNotificationPermission(result: @escaping FlutterResult) {
        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert, .sound, .badge]
        ) { granted, error in
            DispatchQueue.main.async {
                if let error = error {
                    result(FlutterError(code: "notification_error", message: error.localizedDescription, details: nil))
                } else {
                    result(granted)
                }
            }
        }
    }
    
    /// 处理接收到的推送令牌
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        UserDefaults.standard.set(token, forKey: "deviceToken")
        
        // 将令牌发送到Flutter
        pushChannel?.invokeMethod("onTokenReceived", arguments: token)
        print("APNs token: \(token)")
    }
    
    /// 处理推送注册失败
    override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
        pushChannel?.invokeMethod("onTokenError", arguments: error.localizedDescription)
    }
}

// 单独的通知代理类
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
    private let pushChannel: FlutterMethodChannel
    
    init(pushChannel: FlutterMethodChannel) {
        self.pushChannel = pushChannel
        super.init()
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("Foreground notification received: \(userInfo)")
        
        // 将通知内容发送到Flutter
        pushChannel.invokeMethod("onNotificationReceived", arguments: userInfo)
        
        // 显示通知
        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)")
        
        // 将点击事件发送到Flutter
        pushChannel.invokeMethod("onNotificationTapped", arguments: userInfo)
        
        completionHandler()
    }
}
