//
//  QSLBaseManager.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/4.
//

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

class QSLBaseManager {
    
    static let shared = QSLBaseManager()
    
    var userModel = QSLUserModel()
    
    private init() {}
    
    public func initConfig() {
        
        if let model = QSLCacheManager.getModel() {
            self.userModel = model
            QSLApi.updateToken(token: self.userModel.authToken)
        }
        
        initializeSystem()
        initIDFA()
        initPayCheck()
    }
}

extension QSLBaseManager {
    
    // 更新用户模型
    func updateUser(model: QSLUserModel) {
        
        self.userModel = model
        self.userModel.isMine = true
        QSLCacheManager.cacheModel(userModel)
    }
    
    // 登录更新模型
    func loginUpdateUser(authToken: String, phone: String) {
        QSLApi.updateToken(token: authToken)
        userModel.authToken = authToken
        userModel.phone = phone
        userModel.remark = "自己"
        userModel.isMine = true
        QSLCacheManager.cacheModel(userModel)
    }
    
    // 保存用户id
    func saveUserId(id: String) {
        
        userModel.userId = id
        QSLCacheManager.cacheModel(userModel)
    }
    
    // 保存vip时间
    func saveVipExpiredTime(time: Int) {
        
        if time != 0 {
            self.userModel.vipEndTimestamp = Date(timeIntervalSince1970: TimeInterval(time / 1000))
        } else {
            self.userModel.vipEndTimestamp = nil
        }
    }
    
    // 是否登录状态
    func isLogin() -> Bool {
        
        if userModel.authToken != "" {
            return true
        }
        return false
    }
    
    // 是否为vip
    func isVip() -> Bool {
        
        if userModel.vipEndTimestamp?.compare(NSDate.now) == .orderedDescending {
            return true
        }
        return false
    }
    
    // 退出登录
    func logOut() {
        
        print("用户退出登录")
        
        QSLCacheManager.clearCache()
        QSLApi.updateToken(token: "")
        self.saveVipExpiredTime(time: 0)
        self.userModel.phone = ""
        self.userModel.authToken = ""
        self.userModel.userId = ""
        self.userModel.remark = "自己"
        self.userModel.memberModel = QSLMemberModel()
        
        // 发送通知
        NotificationCenter.default.post(name: QSLNotification.QSLLogout, object: nil)
    }
}

extension QSLBaseManager {
    
    // 检查漏单
    func initPayCheck() {
        
        if let order = QSLCacheManager.getOrderModel() {
            if order.receiptData.count > 0 {
                if !order.isFinish {
                    QSLVipManager.shared.orderModel = order
                    QSLVipManager.shared.openAppRePay(receiptData: order.receiptData) { status, number in
                        
                    }
                }
            }
        }
    }
    
    // 上报 clientId
    func uploadClientId(clientId: String) {
        
        QSLNetwork().request(.deviceInfoUpload(dict: ["clientId": clientId])) { response in
            
            debugPrint("上报设备信息成功")
        } fail: { code, error in
           
            debugPrint("上报设备信息失败")
        }
    }
}

extension QSLBaseManager {
    
    func initializeSystem() {
        
        // 获取 APP 名称
        if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
            QSLApi.getAppName(appName: appName)
        } else {
            print("App名称未找到")
        }
        
        // 获取包名
        if let bundleIdentifier = Bundle.main.bundleIdentifier {
            QSLApi.getPackageName(packageName: bundleIdentifier)
            debugPrint("Bundle ID: \(bundleIdentifier)")
        } else {
            debugPrint("Unable to retrieve bundle identifier")
        }
        
        // 获取版本号
        if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            debugPrint("App Version: \(appVersion)")
            QSLApi.getAppVersionName(appVersionName: appVersion)
            
            let array = appVersion.components(separatedBy: ".")
            var appVersionCode = ""
            for i in array {
                appVersionCode.append(i)
            }
            if appVersionCode.count < 3 {
                appVersionCode.append("0")
            }
            QSLApi.getAppVersionCode(appVersionCode: Int(appVersionCode) ?? 100)
        } else {
            debugPrint("Unable to retrieve app version")
        }
        
        if let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String {
            debugPrint("当前的Build号: \(buildNumber)")
        }
        
        // 获取系统版本
        let osVersion = String(format: "%@%@", UIDevice.current.systemName, UIDevice.current.systemVersion)
        QSLApi.getOSVersion(osVersion: osVersion)
            
        // 获取 设置uuid 并更新
        if let uuid = UIDevice.current.identifierForVendor?.uuidString {
            QSLApi.getIDFV(newIDFV: uuid)
            debugPrint("IDFV ID: \(uuid)")
        } else {
            debugPrint("获取 IDFV ID 参数失败")
        }
    }
    
    func initIDFA() {
        
        DispatchQueue.global().asyncAfter(deadline: .now() + 0.1){
            if #available(iOS 14.0, *) {
                // 用户请求授权获得IDFA权限
                ATTrackingManager.requestTrackingAuthorization { status in
                    
                    if status == .authorized {
                        
                        debugPrint("授权成功")
                        // 用户已授权
                        let idfa = ASIdentifierManager.shared().advertisingIdentifier
                        debugPrint("IDFA: \(idfa.uuidString)")
                        QSLApi.getIDFA(newIDFA: idfa.uuidString)
                        
                        self.initGE()
                    } else {
                        
                        debugPrint("无法获取idfa")
                        self.initGE()
                    }
                }
            } else {
                
                // 检查用户是否授权应用使用广告标识符
                if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                    // 获取 IDFA
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier
                    QSLApi.getIDFA(newIDFA: idfa.uuidString)
                    debugPrint("IDFA: \(idfa)")
                    
                    self.initGE()
                } else {
                    debugPrint("用户拒绝广告追踪")
                    
                    self.initGE()
                }
            }
        }
    }
    
    // 引力引擎初始化
    func initGE() {
        
        DispatchQueue.main.async {
            if gravityInstance == nil {
                let gravity = QSLGravityManager()
                gravity.initGE()
            }
        }
        
        
        //苹果初始化归因
        QSAppleAdHandle.initQSC()
    }
}
