//
//  QSLGravityManager.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/23.
//

import Foundation
import GravityEngineSDK

var gravityInstance: GravityEngineSDK?

class QSLGravityManager {

    func initGE() {
#if targetEnvironment(simulator)
        return;
#else

#endif
        // 引力引擎
        let config = GEConfig()
        
        config.appid = QSLGravityConst.appid
        config.accessToken = QSLGravityConst.accessToken

        GravityEngineSDK.start(with: config)
        let instance = GravityEngineSDK.sharedInstance(withAppid: config.appid)
        
        gravityInstance = instance

        // 开启自动采集
        instance?.enableAutoTrack(GravityEngineAutoTrackEventType.eventTypeAll)
        
        print("启动引力引擎")
        
        let idfa = QSLApi.params["idfa"] as? String ?? ""
        
        let idfv = QSLApi.params["idfv"] as? String ?? ""
        
        let version = QSLApi.params["appVersionCode"] as? Int ?? 100
        
        instance?.initializeGravityEngine(withAsaEnable: true, withCaid1: "", withCaid2: "", withSyncAttribution: true, withChannel: "AppStore", withSuccessCallback: { response in
            print("gravity engine initialize success, response is---", response)
            
            if let clickCom = response["click_company"] as? String {
                QSLGuideusersToCommentManager.commentShare.clickCompanyChannel = clickCom
            }
            
            self.requestConfig()
            
            // 检查订单
            QSLBaseManager.shared.initPayCheck()
            
            QSEventHandle.eventPush(eventName: QSLGravityConst.launch_show)
            
            if let clientId = gravityInstance?.getCurrentClientId() {
                QSLBaseManager.shared.uploadClientId(clientId: clientId)
            }
            
        }, withErrorCallback: { error in
            print("gravity engine initialize failed, and error is", error)
            
            // 检查订单
            QSLBaseManager.shared.initPayCheck()
            self.requestConfig()
        })
        
        //开始统计时长
        QSLStatisticsUserTimeManager.shared.startTracking()
    }
    
    func requestConfig(){
        var isAttr = false
        if((UserDefaults.standard.value(forKey: "QSAttribution")) != nil){
            if let attr = UserDefaults.standard.value(forKey: "QSAttribution") as? Bool {
                isAttr = attr
            }
        }
        QSLNetwork().request(.confGlobal(dict: ["attribution":isAttr,"clickCompany":QSLGuideusersToCommentManager.commentShare.clickCompanyChannel])) { response in
            var model = response.mapObject(QSLConfModel.self, modelKey: "data")
            model.loginPayEnable = false
            QSLCacheManager.cacheConfModel(model)
        } fail: { code, msg in
            if(QSLCacheManager.getModel() == nil){
                let model = QSLConfModel.init()
                QSLCacheManager.cacheConfModel(model)
            }
        }
    }
    
}
