//
//  WA_limitsVCViewController.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/18.
//

import UIKit
import SVProgressHUD
import Photos
import Alamofire
import AppLovinSDK
import FirebaseAnalytics
import FirebaseRemoteConfig
import MTGSDKNewInterstitial
import MTGSDKBidding
import MTGSDK


class WA_limitsVCViewController: WA_RootVC {
    @IBOutlet weak var retryBtn: UIButton!
    let activityView = UIActivityIndicatorView()
    
    @IBOutlet weak var resourceLabel: UILabel!
    
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    
    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    var adLoadTime: Int = 0
    
    var idad:String?
    var remoteConfig: RemoteConfig!
    
    var failureCount = 0
    
    private var retryTimer: Timer?
    private var retryAttempts = 0
    private let maxRetryAttempts = 3
    private let retryInterval: TimeInterval = 3
    
//    var ivAadManager:MTGNewInterstitialAdManager!
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    override func viewDidLoad() {
        super.viewDidLoad()

        requestPhotoLibraryPermission()
        
        // 初始化 Remote Config
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        
        
        self.resourceLabel.isHidden = false
        activityView.center = CGPoint(x: self.view.center.x + 10, y: self.view.bounds.size.height - 100 )
        // 停止后，隐藏菊花
        activityView.hidesWhenStopped = true
        activityView.color = .black;
        activityView.style = UIActivityIndicatorView.Style.whiteLarge
        
        self.view.addSubview(activityView)
        self.activityView.startAnimating()
        let param = MTGBiddingRequestParameter(placementId: "1638986", unitId: "3504682", basePrice: nil)
        
        MTGBiddingRequest.getBidWith(param) { bidResponse in
            if bidResponse.success{
                self.bidToken = bidResponse.bidToken
                bidResponse.notifyWin()
                self.newInterstitialAdManager = MTGNewInterstitialBidAdManager(placementId: "1638986", unitId: "3504682", delegate: self)
                self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                self.fetchRemoteConfig()
                
            }else{
                WA_TabbarCommon.TabBarController()
            }
        }
 
    }
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.retryBtn.isHidden = true

   

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            // 请求跟踪授权
            requestTrackingAuthorization { idfa in
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    StartManager.shared.idfaid = idfa
                    print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
                } else {
                    print("IDFA is not available or tracking authorization denied.")
                }
            }
        }

        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if UserDefaults.standard.object(forKey: "iswindows") != nil {
            if UserDefaults.standard.bool(forKey: "iswindows") {
                AppDelegate.shared.showOverlayWindow()
            } else {
                UserDefaults.standard.set(false, forKey: "iswindows")
            }
        } else {
            UserDefaults.standard.set(false, forKey: "iswindows")
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            // 请求跟踪授权
            requestTrackingAuthorization { idfa in
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    StartManager.shared.idfaid = idfa
                    print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
                } else {
                    print("IDFA is not available or tracking authorization denied.")
                }
            }
        }
        
    }
    

    
    func fetchRemoteConfig() {
            let localVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0"
            print("version ------- \(localVersion)")
            
            remoteConfig.fetch { [weak self] (status, error) in
                guard let self = self else { return }
                
                if status == .success {
                    self.retryAttempts = 0
                    print("Config fetched!")
                    self.remoteConfig.activate { changed, error in
                        if error == nil {
                            let js = self.remoteConfig.configValue(forKey: "isopen").jsonValue as! [String: Any]
                            let valueopen = js["isadopen"] as! Bool
                            let valueversion = js["version"] as! String
                            
                            DispatchQueue.main.async {
                                if valueversion == localVersion {
                                    WA_TabbarCommon.TabBarController()
                                    StartManager.shared.superHero = false
                                } else {
                                    if valueopen {
//                                        self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                                        self.startAdCheck()
                                        StartManager.shared.superHero = true
                                    } else {
                                        WA_TabbarCommon.TabBarController()
                                        StartManager.shared.superHero = false
                                    }
                                }
                            }
                            
                        }
                    }
                    
                } else {
                    print("Config not fetched")
                    if let error = error {
                        print("Error: \(error.localizedDescription)")
                    }
                    
                    self.retryAttempts += 1
                    if self.retryAttempts <= self.maxRetryAttempts {
                        // 取消之前的定时器
                        self.retryTimer?.invalidate()
                        // 启动新的定时器
                        self.retryTimer = Timer.scheduledTimer(withTimeInterval: self.retryInterval, repeats: false) { [weak self] _ in
                            self?.fetchRemoteConfig()
                        }
                    } else {
                        print("Max retry attempts reached. Stopping retries.")
                        WA_TabbarCommon.TabBarController()
                    }
                }
            }
        }
    
//    /定时加载
    func startAdCheck() {
//        createInterstitialAd()
//        newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
        
        adCheckStartTime = Date()
        adCheckTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(checkAdStatus), userInfo: nil, repeats: true)
    }
    
    @objc func checkAdStatus() {
        let elapsedTime = Date().timeIntervalSince(adCheckStartTime!)
        let elapsedTimeInMilliseconds = Int(elapsedTime * 1000)
//        self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
        let issureready = newInterstitialAdManager!.isAdReady()
        
        if issureready {
//            interstitialAd.show()
            newInterstitialAdManager?.show(from: self)
            Analytics.logEvent("open_load_success", parameters: nil)
            adLoadTime = elapsedTimeInMilliseconds // 记录加载
            adCheckTimer?.invalidate()
            self.activityView.stopAnimating()
//            if StartManager.shared.idfaid == ""{
//                self.fetchIDFAUntilSuccess()
//            }else{
//                self.setPostSHOW()
//            }
        } else if elapsedTimeInMilliseconds >= 10000 { // 10000 毫秒 = 10 秒
            adCheckTimer?.invalidate()
            WA_TabbarCommon.TabBarController()
            Analytics.logEvent("open_load_fail", parameters: nil)
            self.activityView.stopAnimating()

        } else {
            print("广告未准备好，继续检查...")
        }
        
    }
    
    
    
    ///获取相册权限
    func requestPhotoLibraryPermission() {
        
        // 检查相册权限状态
        let status = PHPhotoLibrary.authorizationStatus()
        // 根据权限状态进行处理
        switch status {
        case .authorized:
            // 用户已授权访问相册
            print("相册权限已授权")
        case .denied, .restricted:
            // 用户已拒绝访问相册或权限受限
            print("相册权限已拒绝或受限，请在设置中开启权限")
        case .notDetermined:
            // 用户尚未作出选择，请求相册权限
            PHPhotoLibrary.requestAuthorization { [weak self] (newStatus) in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        // 用户授权访问相册
                        print("用户已授权访问相册")
                    } else {
                        // 用户未授权访问相册
                        print("用户未授权访问相册")
                    }
                }
            }
        @unknown default:
            // 处理未知权限状态
            print("未知的相册权限状态")
        }
    }
    
//    
//    // 停止监听网络状态
//    func stopListeningNetwork() {
//        NetworkReachabilityManager.default?.stopListening()
//    }
    
    
    
    
  
    
//    func setPostload(){
//        let url = "http://111.9.47.226:38080/top_selection/save_ad_load_log"
//        let parameters:[String : Any] = [
//            "deviceId": StartManager.shared.devicID ?? "",
//            "localIp": StartManager.shared.localIP ?? "",
//            "remoteIp": StartManager.shared.publicIP ?? "",
//            "linkId": "",
//            "packageName": "com.wallpapaer.hd.live.app",
//            "gaid": StartManager.shared.idfaid ?? "",
//            "dataId": "",
//            "shelfNumber":"开屏加载",
//            "succeed": StartManager.shared.succeed,
//            "loadTime":StartManager.shared.loadTime ?? "",
//            "adPlatform": StartManager.shared.adPlatform ?? "",
//            "countryCode": StartManager.shared.countryCode ?? "",
//            "adId": StartManager.shared.adId ?? "",
//            "platformResponseTime": StartManager.shared.platformResponseTime ?? "",
//            "getIpResponseTime": StartManager.shared.getIpResponseTime ?? "",
//            "ecpm": StartManager.shared.ecpm ?? "",
//            "dsp": StartManager.shared.dsp ?? "",
//            "network": StartManager.shared.network ?? "",
//            "showStatus": 0,
//            "washParam": true,
//        ]
//        
//        
//        let headers: HTTPHeaders = [
//            "Content-Type": "application/json"
//        ]
//        
//        NetworkManager.shared.postRequest(url: url, parameters: parameters, headers: headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
//    
//    
//    func setPostSHOW(){
//        let url = "http://111.9.47.226:38080/top_selection/save_ad_show_log"
//        let parameters:[String : Any] = [
//            "deviceId": StartManager.shared.devicID ?? "",
//            "localIp": StartManager.shared.localIP ?? "",
//            "remoteIp": StartManager.shared.publicIP ?? "",
//            "linkId": "",
//            "packageName": "com.wallpapaer.hd.live.app",
//            "gaid": StartManager.shared.idfaid ?? "",
//            "dataId": "",
//            "shelfNumber":"开屏展示",
//            "succeed": StartManager.shared.succeed,
//            "loadTime":StartManager.shared.loadTime ?? "",
//            "adPlatform": StartManager.shared.adPlatform ?? "",
//            "countryCode": StartManager.shared.countryCode ?? "",
//            "adId": StartManager.shared.adId ?? "",
//            "platformResponseTime": StartManager.shared.platformResponseTime ?? "",
//            "getIpResponseTime": StartManager.shared.getIpResponseTime ?? "",
//            "ecpm": StartManager.shared.ecpm ?? "",
//            "dsp": StartManager.shared.dsp ?? "",
//            "network": StartManager.shared.network ?? "",
//        ]
//        
//        let headers: HTTPHeaders = [
//            "Content-Type": "application/json"
//        ]
//        
//        NetworkManager.shared.postRequest(url: url, parameters: parameters, headers: headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
//    
//    
//    func fetchIDFAUntilSuccess() {
//        DispatchQueue.global(qos: .background).async {
//            var idfaObtained = false
//            
//            while !idfaObtained {
//                let semaphore = DispatchSemaphore(value: 0)
//                
//                requestIDFA { idfa in
//                    if let idfa = idfa {
//                        print("Got IDFA: \(idfa)")
//                        // 执行成功获取 IDFA 后的处理方法
//                        //                        self.performActionWithIDFA(idfa)
//                        StartManager.shared.idfaid = idfa
////                        self.setPostSHOW()
//                        idfaObtained = true
//                    } else {
//                        print("Failed to get IDFA, retrying...")
//                        DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 1.0) {
//                            semaphore.signal()
//                        }
//                    }
//                }
//                
//                semaphore.wait()
//            }
//        }
//    }
    
}

extension WA_limitsVCViewController:MTGNewInterstitialBidAdDelegate{
    
//    func newInterstitialBidAdShowSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
//        print("广告展示成功")
//    }
    
    func newInterstitialBidAdResourceLoadSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("资源加载成功，表示可播放状态")
    }
    
    func newInterstitialBidAdLoadSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("广告加载成功")
    }

    
    func newInterstitialBidAdLoadFail(_ error: any Error, adManager: MTGNewInterstitialBidAdManager) {
       
        print("-----\(error)")
//        print(" 广告加载失败")
    }
    
    func newInterstitialBidAdShowSuccess(withBidToken bidToken: String, adManager: MTGNewInterstitialBidAdManager) {
      
        print("广告展示成功")
    }
    
    
    func newInterstitialBidAdShowFail(_ error: any Error, adManager: MTGNewInterstitialBidAdManager) {
        print("广告展示失败")
    }
    
        func newInterstitialBidAdPlayCompleted(_ adManager: MTGNewInterstitialBidAdManager) {

            print("广告播放完全播放回调")
        }
    
    
        func newInterstitialBidAdEndCardShowSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
            print("视频播放完成后展示结果页")
        }
    
        func newInterstitialBidAdClicked(_ adManager: MTGNewInterstitialBidAdManager) {
   
            print("广告被点击")
        }
    
        // 广告被关闭
        func newInterstitialBidAdDidClosed(_ adManager: MTGNewInterstitialBidAdManager) {
//            print("广告被关闭")
            WA_TabbarCommon.TabBarController()
        }

//
//    /**
//     * 在取消展示广告后并将控件返回到您的应用时调用
//     * @param converted - 视频是否播放完整
//     */
//    func newInterstitialAdDismissed(withConverted converted: Bool, adManager: MTGNewInterstitialAdManager) {
////        log(NSStringFromSelector(#function))
//    }
//
//    // 广告被关闭
//    func newInterstitialAdDidClosed(_ adManager: MTGNewInterstitialAdManager) {
////        log(NSStringFromSelector(#function))
//    }
//
//    /**
//     * 如果设置了插屏奖励，您将收到此回调
//     * @param rewardedOrNot 是否达到了可奖励状态
//     * @param alertWindowStatus 支持的类型列表
//     * 注意：您可以根据该回调决定是否给予奖励
//     */
//    func newInterstitialAdRewarded(_ rewardedOrNot: Bool, alertWindowStatus: MTGNIAlertWindowStatus, adManager: MTGNewInterstitialAdManager) {
////        log(NSStringFromSelector(#function))
//    }
    
}


//extension WA_limitsVCViewController: MAAdDelegate
//{
//    func createInterstitialAd() {
//        
//        let randomString = getRandomString()
//
//        if StartManager.shared.adId == nil{
//            StartManager.shared.adId = randomString ?? "789b377f3ac14010e"
//            interstitialAd = MAInterstitialAd(adUnitIdentifier:  StartManager.shared.adId!)
//            print("adid-----\(StartManager.shared.adId ?? "gggg")")
//        }else{
//            interstitialAd = MAInterstitialAd(adUnitIdentifier:  StartManager.shared.adId!)
//            print("adid-----\(StartManager.shared.adId ?? "gggg")")
//        }
//        
//        interstitialAd.delegate = self
//        self.idad = randomString
//        
//        // Load the first ad
//        interstitialAd.load()
//    }
//    
//    
//    // MARK: MAAdDelegate Protocol
//    
//    /// 当广告加载成功时调用的方法
//    func didLoad(_ ad: MAAd) {
//        // 重试尝试次数重置为0
//        retryAttempt = 0
//        // 记录广告加载成功的相关信息
//        //        StartManager.shared.shelfNumber = "开屏加载"
//        StartManager.shared.succeed = true
//        StartManager.shared.loadTime = self.adLoadTime
//        StartManager.shared.adPlatform = "MAX"
//        StartManager.shared.countryCode = ALSdk.shared().configuration.countryCode
//        StartManager.shared.adId = self.idad
//        StartManager.shared.platformResponseTime = ad.requestLatency
//        StartManager.shared.ecpm = Float(ad.revenue)
//        StartManager.shared.dsp = ad.dspName
//        StartManager.shared.network = ad.networkName
//        
//        let logMessage = """
//            deviceId: \(StartManager.shared.devicID ?? "")
//            localIp: \(StartManager.shared.localIP ?? "")
//            "remoteIp": \(StartManager.shared.publicIP ?? ""),
//            "linkId": "",
//            "packageName": "com.wallpapaer.hd.live.app",
//            "gaid": \(StartManager.shared.idfaid ?? ""),
//            "dataId": "",
//            "shelfNumber": "开屏展示",
//            "succeed": \(StartManager.shared.succeed),
//            "loadTime": \(StartManager.shared.loadTime ?? 0),
//            "adPlatform": \(StartManager.shared.adPlatform ?? ""),
//            "countryCode": \(StartManager.shared.countryCode ?? ""),
//            "adId": \(StartManager.shared.adId ?? ""),
//            "platformResponseTime": \(StartManager.shared.platformResponseTime ?? 0.0),
//            "getIpResponseTime": \(StartManager.shared.getIpResponseTime ?? 0.0),
//            "ecpm": \(StartManager.shared.ecpm ?? 0.0),
//            "dsp": \(StartManager.shared.dsp ?? ""),
//            "network": \(StartManager.shared.network ?? "")
//            """
//        
//        AppDelegate.shared.addLogMessage(logMessage)
//        
//        self.setPostload()
//        
//    }
//    
//    /// 当广告加载失败时调用的方法
//    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
//        // 广告加载失败，建议进行重试
//        // 使用指数递增的延迟时间进行重试，最大延迟时间为 64 秒
//        retryAttempt += 1
//        let delaySec = pow(2.0, min(6.0, retryAttempt))
//        DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
//            self.interstitialAd.load()
//        }
//    }
//    
//    /// 当广告显示时调用的方法
//    func didDisplay(_ ad: MAAd) {
//        // 暂停您的应用的背景音频
//    }
//    
//    /// 当用户点击广告时调用的方法
//    func didClick(_ ad: MAAd) {
//        // 用户点击广告
//    }
//    
//    /// 当广告隐藏时调用的方法
//    func didHide(_ ad: MAAd) {
//        // 恢复您的应用的背景音频
//        // 广告隐藏后，预加载下一个广告
//        interstitialAd.load()
//        WA_TabbarCommon.TabBarController()
//    }
//    
//    
//    /// 当广告无法显示时调用的方法
//    func didFail(toDisplay ad: MAAd, withError error: MAError) {
//        // 广告无法显示，建议加载下一个广告
//        interstitialAd.load()
//    }
//    
//    
//    
//    
//}

