//
//  AppDelegateEx.swift
//  PhoneManager
//
//  Created by edy on 2025/5/19.
//

import Foundation
import UIKit
import AdjustSdk
import UserNotifications

extension AppDelegate{
    
    func setupDynamicShortcuts() {
        let shortcutItem = UIApplicationShortcutItem(
            type: "com.app.phonemanager.iap.distance",
            localizedTitle: "🎁 Unlock Special Offers",
            localizedSubtitle: "A Special Offer Just for You!",
            icon: UIApplicationShortcutIcon(systemImageName: "chevron.right"), //UIApplicationShortcutIcon(templateImageName: "icon_gift_sa"), //UIApplicationShortcutIcon(systemImageName: "star.fill"),
            userInfo: nil
        )
        UIApplication.shared.shortcutItems = [shortcutItem]
    }
    
    
    // 处理快捷方式点击
    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        // 处理快捷方式点击事件
        switch shortcutItem.type {
        case "com.app.phonemanager.iap.distance":
            // 执行相应操作
            IAPManager.share.config()
            IAPManager.share.showYearPage = true
            if IAPManager.share.isHotLaunch{
                // 热启动走这里
                switch IAPManager.share.subscriptionType {
                case .none,.week:
                    let vc:PayDistanceViewController = PayDistanceViewController()
                    let nav:BaseNavViewController = BaseNavViewController(rootViewController: vc)
                    nav.modalPresentationStyle = .fullScreen
                    guard let rt = UIViewController.topMostViewController() else { return }
                    rt.present(nav, animated: true)
                default:
                    let vc : PayCompletedViewController =  PayCompletedViewController()
                    guard let rt = UIViewController.topMostViewController() else { return }
                    vc.modalPresentationStyle = .fullScreen
                    rt.present(vc, animated: true)
                }
            }
            completionHandler(true)
        default:
            completionHandler(false)
        }
    }
    
}


extension AppDelegate:AdjustDelegate{
    
    // 因变化时触发函数
    func adjustAttributionChanged(_ attribution: ADJAttribution?) {
        
        guard let attribution = attribution else { return }
        
        reportAdjsutADJAttribution(attribution)
       
    }
    
    func reportAdjsutADJAttribution(_ attribution: ADJAttribution){
        
        let cost_amount = attribution.costAmount?.intValue
        let network = attribution.network
        
        var pram = [
            "tracker_token":attribution.trackerToken ?? "",
            "tracker_name":attribution.trackerName ?? "",
            "campaign":attribution.campaign ?? "",
            "adgroup":attribution.adgroup ?? "",
            "creative":attribution.creative ?? "",
            "click_label":attribution.clickLabel ?? "",
            "cost_type":attribution.costType ?? "",
            "cost_currency":attribution.costCurrency ?? "",
            "cost_amount":cost_amount ?? 0,
            "network":network ?? "",
        ] as [String:Any]
        
        if let json = attribution.jsonResponse as? NSDictionary{
            let convertDic =  self.convertToSwiftDictionary(json)
            pram["first_session_time"] = convertDic["first_session_time"]
            pram["is_reattributed"] = convertDic["is_reattributed"]
            pram["engagement_time"] = convertDic["engagement_time"]
            pram["installed_at"] = convertDic["installed_at"]
        }
        Print("归因变化上报",pram)
        APIReportManager.shared.startReport(type: .source_atrribute,ext: pram)
    }
    
    func configFackBook(){
        
    }
}


extension AppDelegate:UNUserNotificationCenterDelegate{

       
       // 当应用在前台时收到通知
       func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
           // 允许在前台显示通知
           completionHandler([.banner, .sound])
       }
       
       // 处理通知点击事件
       func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
           // 获取通知的标识符
           let identifier = response.notification.request.identifier
           let date = Date().string("yyyy-MM-dd HH:mm:ss")
           
           APIReportManager.shared.startReport(type: .app_notification_click, ext: ["name":identifier,"click_time":date])
           // 根据不同的通知类型执行不同的操作
           switch identifier {
           case "notification_24h", "notification_72h":
               print("用户点击了首次安装通知")
               // 这里可以跳转到相应的页面
           case "weekly_sunday":
               print("用户点击了每周通知")
           case "inactive_8d", "inactive_10d":
               print("用户点击了未活跃通知")
           case "first_install":
               print("用户点击了首次安装通知")
               UserDefaults.standard.set(true, forKey: "user_click_first_install_alert")
           case  "first_install_alert":
               print("用户点击了首次安装后的二次")
           default:
               break
           }
           
           // 完成处理
           completionHandler()
       }
}
