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

import Foundation
import DeviceKit

struct APIReportManager{

    static let shared = APIReportManager()
    
    let bundleId = "com.app.phonemanager"
    let hostUrl = "https://rp.sayyedandroid.online/phonemanagersp?pkg=com.app.phonemanager"
   // let DEBUG = true
    
    
    // 开始上报
    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":ADManager.shared.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
    }
    
}


enum APIReportEnum{
    // 广告上报枚举
    case ad_pull_start
    case ad_pull
    case ad_prepare_show
    case ad_show
    case ad_show_error
    case ad_limit_error
    case ad_click
    case ad_price
    // 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 Duplicates_show
    case Similar_show
    case Videos_show
    case SimilarScreenshots_show
    case Screenshots_show
    case SimilarVideos_show
    case Other_show
    case SecretSpace_show
    case Charging_show
    case Compress_show
    case EmailCleaner_show
    case Contacts_show
    
    case page_show(String) // 页面展示上报枚举
    
}

extension APIReportEnum{
    
    var name: String {
        switch self {
        // 广告上报枚举
        case .ad_pull_start: return "ad_pull_start"
        case .ad_pull: return "ad_pull"
        case .ad_prepare_show: return "ad_prepare_show"
        case .ad_show: return "ad_show"
        case .ad_show_error: return "ad_show_error"
        case .ad_limit_error: return "ad_limit_error"
        case .ad_click: return "ad_click"
        case .ad_price: return "ad_price"
        case .app_start: return "app_start"
        case .app_notification_click: return "app_notification_click"
            
        // 归因上报枚举
        case .source_atrribute: return "source_atrribute"
        case .source_atrribute_error: return "source_atrribute_error"
            
        // 订阅枚举
        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 .Duplicates_show: return "Duplicates_show"
        case .Similar_show: return "Similar_show"
        case .Videos_show: return "Videos_show"
        case .SimilarScreenshots_show: return "SimilarScreenshots_show"
        case .Screenshots_show: return "Screenshots_show"
        case .SimilarVideos_show: return "SimilarVideos_show"
        case .Other_show: return "Other_show"
        case .SecretSpace_show: return "SecretSpace_show"
        case .Charging_show: return "Charging_show"
        case .Compress_show: return "Compress_show"
        case .EmailCleaner_show: return "EmailCleaner_show"
        case .Contacts_show: return "Contacts_show"
        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))
    }
}
