//
//  AppDelegate+LoadData.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/11.
//

import UIKit
import GoogleSignIn
import AdjustSdk
import FirebaseCore

/// adjust key
let ADJustToken = "o42w1u4moe80"

extension AppDelegate {
    
    func initData() -> Void {
        GIDSignIn.sharedInstance.configuration = GIDConfiguration(clientID: googleClent)
        SpeakKeyboardManager.share.monitor()
        SpeakSpeechSynthesizer.share.loadData()
        SpeakElePublicManager.share.loadData()
        _ = SpeakCache.cache
        SpeakDayEveryManager.manager.loadData(Date().toStr() ?? "")
        _ = SpeakLeassonData.data.leassionData
        SpeakAIVideoPlayManager.share.loadVideo()
        SpeakIAPConfigs.share.loadData()
        FirebaseApp.configure()
        Purchase()
    }
    
    
    private func Purchase() -> Void {
        IAPViewModel.share.checkSubscriptionState { issub, state, date in
            IAPViewModel.share.isSubscriptionVerify = true
            NotificationCenter.default.post(name: .subscriptionVerify, object: nil)
        }
        IAPViewModel.share.fetchProducts { product in // 初始化内购
            Print("内购列表\(product?.count ?? 0)")
        }
    }
}

extension AppDelegate {
    
    func MonitorNet() -> Void {
        SpeakNetStatusManager.manager.monitor { status in
            switch status {
            case .NoNet:
                break
            case .WIFI,.WWAN:
                self.Purchase()
                SpeakIAPConfigs.share.loadData()
                let hadStart = UserDefaults.standard.value(forKey: "report_app_first_start") as? Bool ?? false
                if hadStart == false {
                    UserDefaults.standard.set(true, forKey: "report_app_first_start")
                    APIReportManager.shared.startReport(type: .app_start)
                }
                break
            }
        }
    }
    
    func configADJust(){
        #if DEBUG
        let environment = ADJEnvironmentSandbox
        let adjustConfig = ADJConfig(
            appToken:ADJustToken,
            environment: environment)
        adjustConfig?.logLevel = ADJLogLevel.verbose
        #else
        let environment = ADJEnvironmentProduction
        let adjustConfig = ADJConfig(
            appToken: ADJustToken,
            environment: environment)
        adjustConfig?.logLevel = ADJLogLevel.suppress
        #endif
        adjustConfig?.delegate = self

        Adjust.initSdk(adjustConfig)

        Adjust.attribution { attribution in
            guard let attribution = attribution else{
                return
            }
            self.reportAdjsutADJAttribution(attribution)
        }
    }
    
}


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 convertToSwiftDictionary(_ nsDict: NSDictionary) -> [String: Any] {
        return nsDict as? [String: Any] ?? [:]
    }
}



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().toStr("yyyy-MM-dd HH:mm:ss")
       APIReportManager.shared.startReport(type: .app_notification_click, ext: ["name":identifier,"click_time":date])
       // 根据不同的通知类型执行不同的操作
       // 完成处理
       completionHandler()
    }
}
