//
//  QSLCentralEventManager.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/10/13.
//

import Foundation
import UIKit
import AppTrackingTransparency
import AdSupport
import StoreKit
import AdServices

class QSLCentralEventManager {
    // 中台
    static let centralUrl = "https://project-api.atmob.com"
    
    static let appKey = "a3794176067047728826578522a34e5f"
    
    static let bundleId = "com.manbu.shouji"
    
    static let event_push = "/central/open/v1/event/push"
    
    static let ssid_detail = "/central/open/v1/ssid/detail"
    
    static let shared = QSLCentralEventManager()
    
    private init() {}

}

extension QSLCentralEventManager {

    func uploadEvent(eventType: String, eventName: String, eventProps: [String:Any]) {
        
        let timestamp = Int(Date.milliStamp) ?? 0
        var currentPropos = eventProps;
        currentPropos["$snid"] = QSLDeviceTool.shared.sessionId

        baseEventUpload(param: ["ak":QSLCentralEventManager.appKey,"cp":baseDic(),"ft":timestamp, "es":[["ti":timestamp, "ty":eventType, "ev":eventName,"pr":currentPropos]]])
    }
    
    func uploadEvent(eventType: String, eventName: String, eventPropsArr: [[String:Any]]) {
  
        let timestamp = Int(Date.milliStamp) ?? 0
        
        baseEventUpload(param: ["ak":QSLCentralEventManager.appKey,"cp":baseDic(),"ft":timestamp, "es":eventPropsArr])
    }
    
    func baseDic() -> [String:Any]{
        // 获取包名
        var bundleId = QSLCentralEventManager.bundleId
        if let bundleIdentifier = Bundle.main.bundleIdentifier {
            bundleId = bundleIdentifier
        }

        var cpDict : [String : Any] = ["$aplf":2, "$chnl":"Appstore"]
        cpDict["$pkg"] = bundleId
        cpDict["$aver"] = QSLDeviceTool.shared.appVersionName
        cpDict["$avec"] = QSLDeviceTool.shared.appVersionCode
        cpDict["$modl"] = QSLDeviceTool.shared.phoneModel
        cpDict["$osv"] = QSLDeviceTool.shared.OSVersion
        cpDict["$idfa"] = QSLDeviceTool.shared.idfa
        cpDict["$idfv"] = QSLDeviceTool.shared.idfv
        
        return cpDict
    }
    
    func baseEventUpload(param: [String:Any]) {
        QSLCentralNetwork().request(.eventPush(dict: param)) { response in
            debugPrint("上报事件成功")
        } fail: { code, error in
            debugPrint("上报事件失败")
        }
    }
}
