//
//  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
import FacebookCore

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        UIViewController.swizzleViewDidAppear()
        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
        ADManager.shared.initAdertisementSDK()
        FirebaseApp.configure()
        PMEmailManager.shareManager.restore()
        SettingConfiguration.share.initData()
        HapticManager.share.setupHapticEngine()
        
        // 相册基本资源加载
        PhotoManager.shared.config()
        // 设置app动态按钮
        setupDynamicShortcuts()
        
        Adjust.attribution { attribution in
            
            guard let attribution = attribution else{
                return
            }
            self.reportAdjsutADJAttribution(attribution)
        }
        
        
        PMLoadingHUD.share.config()
        UNUserNotificationCenter.current().delegate = self

        ApplicationDelegate.shared.application(
                application,
                didFinishLaunchingWithOptions: launchOptions
            )
        
        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 applicationDidEnterBackground(_ application: UIApplication) {
        Print("进入后台")
        if UserDefaults.standard.value(forKey: "app_install_date_enterback") == nil{
               // 第一次安装时间
            UserDefaults.standard.set(Date(), forKey: "app_install_date_enterback")
               // 添加首次安装完成的推送
            Print("开始创建首次安装完成的推送")
            NotificationManager().scheduleFirstInstallNotification()
        }else{
            Print("无需创建")
        }
        
        if let firstAlert = UserDefaults.standard.value(forKey: "user_click_first_install_alert") as? Bool,firstAlert == true{
            Print("开始创建首次安装进入推送的推送")
            NotificationManager().scheduleFirstInstallAlertClickNotification()
        }
        
    }

    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()
                }
                ADManager.shared.getADConfig()
                ADManager.shared.getAppStoreVersion { value in
                    if let version = value{
                        ADManager.shared.onlineVersion = version
                    }
                }
                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 {
            ApplicationDelegate.shared.application(
                   app,
                   open: url,
                   sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                   annotation: options[UIApplication.OpenURLOptionsKey.annotation]
               )
            return GIDSignIn.sharedInstance.handle(url)
            
    }
    
    func convertToSwiftDictionary(_ nsDict: NSDictionary) -> [String: Any] {
        return nsDict as? [String: Any] ?? [:]
    }

    
}

