//
//  AppDelegate.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/19.
//

import UIKit
import AppIntents
import Photos
import GoogleMobileAds
import UserMessagingPlatform
import GoogleSignIn
import AdjustSdk
import FirebaseCore

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        setupDefault()
 
        window = UIWindow(frame: UIScreen.main.bounds)
        
        UserDefaults.standard.set(["en"], forKey: "AppleLanguages")
        UserDefaults.standard.synchronize()
        
        window?.backgroundColor = .white
        window?.overrideUserInterfaceStyle = .light
        
        let rootNav = BaseNavViewController(rootViewController: HomeViewController())
        window?.rootViewController = rootNav
        window?.makeKeyAndVisible()
        
        // 小组件数据 同步
        let battery = WidgetPublicModel.battery()
        let storage = WidgetPublicModel.UseDiskSpace() * 100
        widgetAppgourp.share.PushWidgetData(battery: Int(battery), storage: Int(storage))
    
    
        
        //初始化adjust
        let yourAppToken = "6mouvwgw7ksg"

        #if DEBUG
        let environment = ADJEnvironmentSandbox
        let adjustConfig = ADJConfig(
            appToken: yourAppToken,
            environment: environment)
        adjustConfig?.logLevel = ADJLogLevel.verbose
        #else
        let environment = ADJEnvironmentProduction
        let adjustConfig = ADJConfig(
            appToken: yourAppToken,
            environment: environment)
        adjustConfig?.logLevel = ADJLogLevel.suppress
        #endif
        adjustConfig?.delegate = self
        
        Adjust.initSdk(adjustConfig)
           
        
        // 获取内购价格
        IAPManager.share.fetchProducts { p in
            Print("获取内购商品信息",p as Any)
        }
        
        // 初始化广告SDK
        AdvManager.shared.initAdertisementSDK()
        FirebaseApp.configure()
        PMEmailManager.shareManager.restore()
        SettingConfiguration.share.initData()
        HapticManager.share.setupHapticEngine()
        
        // 相册基本资源加载
        PhotoManager.shared.config()
        // 设置app动态按钮
        setupDynamicShortcuts()
        
    
        Adjust.attribution { attribution in
            Print("获取当前归因信息",attribution as Any)
//            if let dic = attribution?.jsonResponse{
//                let pram = self.convertToSwiftDictionary(dic as NSDictionary)
//                APIReportManager.shared.startReport(type: .source_atrribute,ext: pram)
//            }
//            let pram = [
//                "tracker_token":attribution?.trackerToken ?? "",
//                "tracker_name":attribution?.trackerName ?? "",
//                "network":attribution?.network ?? "",
//                "campaign":attribution?.campaign ?? "",
//                "adgroup":attribution?.adgroup ?? "",
//                "creative":attribution?.creative ?? "",
//                "click_label":attribution?.clickLabel ?? "",
//                "cost_type":attribution?.costType ?? "",
//                "cost_amount":attribution?.costAmount ?? "",
//                "cost_currency":attribution?.costCurrency ?? "0"
//            ]
            
//            Print("归因字典",pram)
//            Print("归因json",attribution?.jsonResponse)
        }
        
        PMLoadingHUD.share.config()
        
        return true
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        // 保存单利中所有垃圾桶的数据
        saveDataToTrashDB(data: Singleton.shared.trashData)
        
        // 保存单利中所有垃圾桶的数据
        saveDataToKeepListhDB(data: Singleton.shared.keepList)
        
    }
    
    func saveDataToTrashDB(data : [TrashTypeEnum : [AssetModel]]){
        for (key,value) in data {
            for item in value {
                let success = TrashDatabase.shared.insert(localIdentifier: item.localIdentifier, assetSize: item.assetSize, createDate: item.createDate, mediaType: key.dbType)
                if !success {
                    Print("保存单利数据到数据库失败")
                }
            }
        }
        Singleton.shared.trashData = [:]
    }
    
    func saveDataToKeepListhDB(data : [TrashTypeEnum : [AssetModel]]){
        for (key,value) in data {
            let uniqueId = UUID().uuidString
            for item in value {
                let success = GroupDatabase.shared.insert(localIdentifier: item.localIdentifier, assetSize: item.assetSize, createDate: item.createDate, mediaType: key == TrashTypeEnum.video ? 2 : 1,groupId: uniqueId)
                if !success {
                    Print("保存保留列表数据失败")
                }
            }
        }
        Singleton.shared.keepList = [:]
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        NotificationCenter.default.post(name: Notification.Name("applicationDidBecomeActive"), object: nil)
        
        postContactNotification()
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        SettingConfiguration.share.saveData()
    }
    
    func postContactNotification(){
        // 通知联系人重复项改变
        let dataUpdated = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED)
        NotificationCenter.default.post(name: dataUpdated, object: nil, userInfo: nil)
        
        // 发起通知刷新重复联系人预览页面数据
        let dataUpdatePre = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED_PRE)
        NotificationCenter.default.post(name: dataUpdatePre, object: nil, userInfo: nil)
        
        // 发起通知刷新所有联系人页面数据
        let dataUpdateAll = Notification.Name(ContactAllView.CONTACT_ALL)
        NotificationCenter.default.post(name: dataUpdateAll, object: nil, userInfo: nil)
        
        // 发起通知刷新不完整联系人页面数据
        let dataUpdateInc = Notification.Name(ContactNormalIncomView.CONTACT_INCOM)
        NotificationCenter.default.post(name: dataUpdateInc, object: nil, userInfo: nil)
    }
    
 
    
    
    
    private func setupDefault() {
        
        NetStatusManager.manager.startNet { status in
            
            switch status {
            case .NoNet:
                break
            case .WIFI,.WWAN:
                if UserDef.shard.isFirstStart{
                    Print("首次启动获取网络上报")
                    APIReportManager.shared.startReport(type: .app_start)
                    UserDef.shard.saveFirstStart()
                }
                break
            }
        }
        
        if #available(iOS 13.0, *) {
            
            let window = UIApplication.shared.windows.first
            let topPadding = window?.safeAreaInsets.top ?? 0
            statusBarHeight = topPadding > 0 ? topPadding:20
            navHeight = navDefaultHeight + statusBarHeight
            navCenterY = 22 + statusBarHeight
        }else {
            
            statusBarHeight = UIApplication.shared.statusBarFrame.size.height
            navHeight = navDefaultHeight + statusBarHeight
            navCenterY = 22 + statusBarHeight
        }
        
        if #available(iOS 11.0, *) {
            
            safeHeight = UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0
            
        }else {
            safeHeight = 0
        }
    }
    
    
    func application(
            _ app: UIApplication,
            open url: URL,
            options: [UIApplication.OpenURLOptionsKey: Any] = [:]
        ) -> Bool {
            return GIDSignIn.sharedInstance.handle(url)
    }
    
    func convertToSwiftDictionary(_ nsDict: NSDictionary) -> [String: Any] {
        return nsDict as? [String: Any] ?? [:]
    }

    
}

