//
//  APIReportManager.swift
//  PhoneManager
//
//  Created by edy on 2025/5/21.
//

import Foundation
import DeviceKit
import AppTrackingTransparency
import AdSupport

struct APIReportManager{

    static let shared = APIReportManager()
    
    let bundleId = "com.speakeasy.ai.ap"
    let hostUrl = "https://rp.sayyedandroid.online/speakeasysp?pkg=com.speakeasy.ai.ap"
    
    // 开始上报
    func startReport(type:APIReportEnum,ext:[String:Any] = [:]){
        
        let data = getdataBody(action: type.name, ext: ext)
        let bp = getbpBody()
        
        let content = [
            "data":data,
            "bp":bp
        ]
        
        Print("上报数据",content)
        
        if let json = content.toJSONString(){
            guard let aesString = AESCrypto.encryptGCM(json) else{
                return
            }
            reportAPIRequest(for: aesString)
        }

    }
    
    
    private func reportAPIRequest(for aesStr:String){
        
        HttpRequest.postBodyWithString(to: hostUrl, bodyValue: aesStr) { result in
            switch result {
            case .success(let jsonString):
                Print("上报成功",jsonString)
            case .failure(let failure):
                Print("请求异常",failure.localizedDescription)
            }
        }

    }
    
    
    private func getdataBody(action:String,ext:[String:Any]) ->[String:Any]{
        
        var dic = [
            "action":action,
        ] as? [String:Any]
        
        if ext.count > 0{
            dic?["ext"] = ext
        }
        
        return dic ?? [:]
    }
    
    private func getbpBody() ->[String:String]{
  
        let body = [
            "\(bundleId)_3": "\(Device.current)", //手机型号
            "\(bundleId)_4": "Apple", // 手机厂商
            "\(bundleId)_5": UIDevice.current.systemVersion, //系统版本号
            "\(bundleId)_8": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "", // APP版本号
            "\(bundleId)_9": DeviceIDManager.shared.deviceID, //UUID
            "\(bundleId)_10":getIDFA(), //iafa
            "\(bundleId)_13": "iOS", // platform
            "\(bundleId)_14": Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "", //版本号
            "\(bundleId)_15": "AppStore", //渠道标识
            "\(bundleId)_24": isDebug() ? "debug" : "release", //环境  debug：开发环境 release：正式环境
            "\(bundleId)_34": TimeZone.current.identifier, //手机本地时区
            "\(bundleId)_35": DeviceIDManager.shared.deviceID //UUID
        ]
        return body
    }
    
    // 使用编译时条件的辅助函数
    private func isDebug() -> Bool {
        #if DEBUG
        return true
        #else
        return false
        #endif
    }
    
    /// 获取IDFA
    func getIDFA() -> String {
        if #available(iOS 14, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
            switch status {
            case .authorized:
                return ASIdentifierManager.shared().advertisingIdentifier.uuidString
            case .denied, .restricted, .notDetermined:
                requestIDFAPermission { staus in
                    
                }
                return ""
            @unknown default:
                return ""
            }
        } else {
            // iOS 14以下版本
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                return ASIdentifierManager.shared().advertisingIdentifier.uuidString
            }
            return ""
        }
    }
    
    /// 请求IDFA权限
    func requestIDFAPermission(completion: @escaping (ATTrackingManager.AuthorizationStatus) -> Void) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                DispatchQueue.main.async {
                    completion(status)
                }
            }
        } else {
            completion(.authorized)
        }
    }
    
}


enum APIReportEnum{
    // 广告上报枚举
    // app启动
    case app_start
    case app_notification_click
    // 归因上报枚举
    case source_atrribute
    case source_atrribute_error
    // 订阅枚举
    case apple_billing_error
    case apple_billing_click
    case apple_billing_consume
    case apple_billing_success

    
    case page_show(String) // 页面展示上报枚举
    
}

extension APIReportEnum{
    
    var name: String {
        switch self {
        // 归因上报枚举
        case .source_atrribute: return "source_atrribute"
        case .source_atrribute_error: return "source_atrribute_error"
        case .app_start: return "app_start"
        case .app_notification_click: return "app_notification_click"
            
        // 订阅枚举
        case .apple_billing_error: return "apple_billing_error"
        case .apple_billing_click: return "apple_billing_click"
        case .apple_billing_consume: return "apple_billing_consume"
        case .apple_billing_success: return "apple_billing_success"
            
        case .page_show(let className):
            return "page_show_\(className)" // 页面展示上报枚举，使用类名作为标识
        }
    }
}


extension UIViewController {
    static func swizzleViewDidAppear() {
        guard let originalMethod = class_getInstanceMethod(UIViewController.self, #selector(viewDidAppear(_:))),
              let swizzledMethod = class_getInstanceMethod(UIViewController.self, #selector(swizzled_viewDidAppear(_:))) else { return }
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

    @objc func swizzled_viewDidAppear(_ animated: Bool) {
        // Call the original viewDidAppear
        swizzled_viewDidAppear(animated)
        // Report class name
        reportPageAppear(className: String(describing: type(of: self)))
    }

    func reportPageAppear(className: String) {
        // Your reporting logic here
        print("Page appeared: \(className)")
        APIReportManager.shared.startReport(type: .page_show(className))
    }
}
