import UserNotifications

class NotificationManager {
    
    private var photos:Int{
        return PhotoManager.shared.photosAssets.count
    }
    private var videos:Int{
        return PhotoManager.shared.videoModels.count
    }
    private var similarScreen:Int{
        return PhotoManager.shared.filterSimilarScreenShotModels.count
    }
    private var similar:Int{
        return PhotoManager.shared.similarModels.count
    }
    
    private var duplicatesSize:String = "100 MB"
    
    func configNotifications(){
        if UserDefaults.standard.value(forKey: "app_install_date") == nil{
            // 第一次安装时间
            UserDefaults.standard.set(Date(), forKey: "app_install_date")
        }
        
        // 更新最后访问时间
        UserDefaults.standard.set(Date(), forKey: "app_last_visit_date")
        
        // 取消之前的未活跃通知
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["inactive_8d", "inactive_10d"])
        
        scheduleLocalNotifications()
    }
    
    // 调度本地通知
    func scheduleLocalNotifications() {
        // 请求通知权限
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
            if granted {
                // 创建并调度通知
                self.createNotifications()
            } else {
                print("通知权限未被授予: \(String(describing: error))")
            }
        }
    }
    
    // 创建并调度通知
    private func createNotifications() {
    
        // 1. 设置24小时和72小时的通知
//        scheduleOneTimeNotification(afterHours: 24, identifier: "notification_24h")
//        scheduleOneTimeNotification(afterHours: 72, identifier: "notification_72h")
        
        // 2. 设置每周日上午10点的通知（第4-60天）
        scheduleWeeklyNotification()
        
        // 3&4. 设置未打开应用的通知
//        scheduleInactiveNotification(days: 8, identifier: "inactive_8d")
//        scheduleInactiveNotification(days: 10, identifier: "inactive_10d")
    }
    
    
    
    
    // 设置一次性通知
    func scheduleOneTimeNotification(afterHours: Int, identifier: String) {
        let content = UNMutableNotificationContent()
        content.title = "Arrange the photos in a secret space to gain more space!"
        content.body =  "\(PhotoManager.shared.similarModels.count) photos are placed in the \"Secret Space\" to free up more storage space"
        content.sound = UNNotificationSound.default
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(afterHours * 3600), repeats: false)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("添加\(afterHours)小时通知失败: \(error)")
            }
        }
    }
    
    // 设置每周上午10点通知
    private func scheduleWeeklyNotification() {
        let content = UNMutableNotificationContent()
        content.title = "One click release of space"
        content.body = "Prepare the equipment for the new week →"
        content.sound = UNNotificationSound.default
        
        var dateComponents = DateComponents()
        dateComponents.weekday = 1 // 周日
        dateComponents.hour = 10
        dateComponents.minute = 0
        
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
        let request = UNNotificationRequest(identifier: "weekly_sunday", content: content, trigger: trigger)
        
        // 检查是否在4-60天的范围内
        let installDate = UserDefaults.standard.object(forKey: "app_install_date") as? Date ?? Date()
        let daysSinceInstall = Calendar.current.dateComponents([.day], from: installDate, to: Date()).day ?? 0
        
        if daysSinceInstall >= 4 && daysSinceInstall <= 60 {
            UNUserNotificationCenter.current().add(request) { error in
                if let error = error {
                    print("添加每周通知失败: \(error)")
                }
            }
        }
    }
    
    // 设置未活跃通知
    func scheduleInactiveNotification(days: Int, identifier: String) {
        let content = UNMutableNotificationContent()
        
        content.title = "Your phone has not been cleaned for \(days) days!"
        content.body = days == 8 ? "\(PhotoManager.shared.screenShotAssets.count) screenshots to be cleaned, click Clean Now →" : "Immediately return to view similar images on your phone."
        content.sound = UNNotificationSound.default
        
        // 获取最后访问时间，如果没有则使用当前时间
        let lastVisitDate = UserDefaults.standard.object(forKey: "app_last_visit_date") as? Date ?? Date()
        
        // 从最后访问时间开始计算
        let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: TimeInterval(days * 24 * 3600), 
            repeats: false
        )
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("添加未活跃通知失败: \(error)")
            }
        }
    }
    
    // 添加首次安装完成的推送
     func scheduleFirstInstallNotification() {
        let content = UNMutableNotificationContent()
        content.title = "You can free up more storage space!"
        content.body = " \(self.videos) videos and \(self.photos) photos are waiting in the \"video&others\" section."
        content.sound = UNNotificationSound.default
        
        // 设置30秒后推送
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "first_install", content: content, trigger: trigger)
        Print("开始创建推送")
         
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("添加首次安装通知失败: \(error)")
            }else{
                print("添加首次安装通知成功")
            }
        }
    }
    
    
    func scheduleFirstInstallAlertClickNotification() {
       let content = UNMutableNotificationContent()
        let size = getTotalSize(source:PhotoManager.shared.filterSimilarScreenShotModels)
        
        var sizeStr = "100 M"
        let sizeKB : Double = size/1000
        if sizeKB < 1000{
            sizeStr = String(format: "%.2lf KB" ,sizeKB)
        }else if sizeKB < (1000 * 1000) && sizeKB > 1000{
            sizeStr = String(format: "%.2lf MB" ,sizeKB/1000)
        }else{
            sizeStr = String(format: "%.2lf GB" ,sizeKB/(1000 * 1000))
        }
        
       content.title = "More space is waiting to be cleared up"
        
       content.body = "\(self.similarScreen) photos are waiting to be cleaned up in Similar Screenshots, approximately \(sizeStr)."
       content.sound = UNNotificationSound.default
       
       // 设置30秒后推送
       let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
       let request = UNNotificationRequest(identifier: "first_install_alert", content: content, trigger: trigger)
       Print("开始创建推送")
        
       UNUserNotificationCenter.current().add(request) { error in
           if let error = error {
               print("添加首次安装通知失败: \(error)")
           }else{
               print("点击首次安装通知的通知成功")
               UserDefaults.standard.setValue(false, forKey: "user_click_first_install_alert")
           }
       }
   }
    
    func getTotalSize(source:[[AssetModel]]) ->Double{
        return source.flatMap{$0}.reduce(0){$0+$1.assetSize}
    }
    


    // 取消所有通知
    func cancelAllLocalNotifications() {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        print("所有本地通知已被取消")
    }


    
}


// 扩展 Array
extension Array {
    // 安全获取元素的方法
    func safeGet(index: Int) -> Element? {
        // 检查索引是否在有效范围内
        guard index >= 0 && index < self.count else {
            print("Index \(index) is out of bounds for array of size \(self.count).")
            return nil // 返回 nil 表示越界
        }
        return self[index] // 返回对应的元素
    }
    
    mutating func removeStr(_ objc:String) -> Array {
        for (i,v) in self.enumerated() {
            if  let value = v as? String,
                value == objc {
                return self.remove(at: i) as? Array ?? []
                break
            }
        }
        return self
    }
}


extension Date {
    /// 将 Date 转换为指定格式的字符串
    /// - Parameter format: 日期格式字符串
    /// - Returns: 格式化后的日期字符串
    func toString(format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
    
    func getDateString(format:String = "yyyy-MM-dd HH:mm") ->String{
        
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = format
        dateFormatter.locale = .current
        let dateStr = dateFormatter.string(from: self)
        return dateStr
    }
}
