//
//  QSLStatisticsUserTimeManager.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/7/30.
//

import Foundation
import UIKit
import GravityEngineSDK

class QSLStatisticsUserTimeManager {
    static let shared = QSLStatisticsUserTimeManager()
    private let userDefaults = UserDefaults.standard
    private var backgroundTaskID: UIBackgroundTaskIdentifier?
    private var timer: Timer?
    private var sessionStartTime: Date?
    
    // MARK: - 键名常量
    private struct Keys {
        static let totalUsage = "GETotalUsageTime"
        static let lastUploadTime = "GELastUploadTime"
    }
    
    // 累计使用时长（秒）
    private var totalUsageTime: TimeInterval {
        get { userDefaults.double(forKey: Keys.totalUsage) }
        set { userDefaults.set(newValue, forKey: Keys.totalUsage) }
    }
    
    // MARK: - 生命周期监听
    func startTracking() {
        NotificationCenter.default.addObserver(self,
            selector: #selector(appDidBecomeActive),
            name: UIApplication.didBecomeActiveNotification,
            object: nil)
        
        NotificationCenter.default.addObserver(self,
            selector: #selector(appWillResignActive),
            name: UIApplication.willResignActiveNotification,
            object: nil)
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleTrackResult),
            name: Notification.Name("GravityEngineTrackResult"),
            object: nil
        )
    }
    
    @objc func handleTrackResult()  {
        print("数据商城成功----")
    }
    
    @objc private func appDidBecomeActive() {
        sessionStartTime = Date()
        startPeriodicUpload()
    }
    
    @objc private func appWillResignActive() {
        saveCurrentSession()
        beginBackgroundTask()
    }
    
    // MARK: - 数据记录逻辑
    private func saveCurrentSession() {
        guard let start = sessionStartTime else { return }
        totalUsageTime += Date().timeIntervalSince(start)
        sessionStartTime = nil
    }
    
    // MARK: - 定期上传
    private func startPeriodicUpload() {
        // 每隔5分钟检查上传（与SDK的上传间隔分开）
        timer = Timer.scheduledTimer(withTimeInterval: 300, repeats: true) { [weak self] _ in
            self?.uploadUsageData()
        }
    }
    
    private func uploadUsageData() {
        saveCurrentSession()
        
        let properties: [String: Any] = [
            "total_usage_seconds": totalUsageTime,
            "last_upload_time": Date().timeIntervalSince1970
        ]
        
        // 通过GravityEngine上报事件
        gravityInstance?.track(QSLGravityConst.usage_collect_accumulatedTime, properties: properties)
        print("时长上报成功")
        self.totalUsageTime = 0  // 重置累计时长
        self.userDefaults.set(Date().timeIntervalSince1970, forKey: Keys.lastUploadTime)
        /*GravityEngine.shared.track("app_usage", properties: properties) { success, error in
            if success {
                print("时长上报成功")
                self.totalUsageTime = 0  // 重置累计时长
                self.userDefaults.set(Date().timeIntervalSince1970, forKey: Keys.lastUploadTime)
            } else {
                print("上报失败: \(error?.localizedDescription ?? "")")
            }
        }*/
    }
    
    // MARK: - 后台任务
    private func beginBackgroundTask() {
        backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.endBackgroundTask()
        }
    }
    
    private func endBackgroundTask() {
        if let taskID = backgroundTaskID {
            UIApplication.shared.endBackgroundTask(taskID)
            backgroundTaskID = .invalid
        }
    }
}
