//
//  WA_limitsVCViewController.swift
//  wallpaper_project


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


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 ecpmprice:Double?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    
    
    var idstring:String = "n66bdc1e78a5d9"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        requestPhotoLibraryPermission()
        
        // 初始化 Remote Config
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        self.idstring = getRandomString() ?? "n66bdc1e78a5d9"
        // 设置最小获取间隔（开发期间可以设置较小的值）
        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()
        
        
        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 3) {
            self.loadTopAD()
        }
        
        
      
    }
    
    func loadTopAD(){
        let extra: [String: Any] = [
                 kATAdLoadingExtraMediaExtraKey: "custom_values"
             ]
        ATAdManager.shared().loadAD(withPlacementID: self.idstring, extra: extra, delegate: self)
        self.fetchRemoteConfig()
        
    }
    
    
    
    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)

        
        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
                            let tt = UserDefaults.standard
                           print("-------\(tt.bool(forKey: "iswindows"))")
                            DispatchQueue.main.async {
                                if valueversion == localVersion {
                                    let userDefaults = UserDefaults.standard
                                    if userDefaults.bool(forKey: "iswindows"){
                                        
                                        let appDelegate = UIApplication.shared.delegate
                                        appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
                                    }else{
                                        
                                        
                                        WA_TabbarCommon.TabBarController()
                                    }
                                    StartManager.shared.superHero = false
                                } else {
                                    if valueopen {
//                                        self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                                        self.startAdCheck()
                                        StartManager.shared.superHero = true
                                    } else {
                                        let userDefaults = UserDefaults.standard
                                        if userDefaults.bool(forKey: "iswindows"){
                                            let appDelegate = UIApplication.shared.delegate
                                            appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
                                        }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.")
                        let userDefaults = UserDefaults.standard
                        if userDefaults.bool(forKey: "iswindows"){
                            let appDelegate = UIApplication.shared.delegate
                            appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
                        }else{
                            
                            
                            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 ATAdManager.shared().interstitialReady(forPlacementID: self.idstring)
        {
            ATAdManager.shared().showInterstitial(withPlacementID: self.idstring, in: self, delegate: self)
            adLoadTime = elapsedTimeInMilliseconds // 记录加载
            adCheckTimer?.invalidate()
            self.activityView.stopAnimating()
            if StartManager.shared.idfaid == ""{
                self.fetchIDFAUntilSuccess()
            }else{
                setPostSHOW()
                StartManager.shared.shelfNumber = "开屏show"
            }
        }else if elapsedTimeInMilliseconds >= 10000{
            adCheckTimer?.invalidate()
            let userDefaults = UserDefaults.standard
            if userDefaults.bool(forKey: "iswindows"){
                let appDelegate = UIApplication.shared.delegate
                appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
            }else{
                
                
                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 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:ATInterstitialDelegate{
    func didFinishLoadingAD(withPlacementID placementID: String!) {
        print("----")
    }
    
    
    //    插页广告展示成功
    func interstitialDidShow(forPlacementID placementID: String, extra: [AnyHashable : Any]) {

        print("----成功")
        
    }
    
    /// 插页广告被点击
    func interstitialDidClick(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("----点击")
    }
    //    插页广告已关闭
    func interstitialDidClose(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("----关闭")
        
        WA_TabbarCommon.TabBarController()
    }
    // 完成加载广告
    func didFinishLoadingADSource(withPlacementID placementID: String!,extra: [AnyHashable : Any]?) {
   
        let networkID = extra?["network_firm_id"]
        
        let ecpm = extra?["adsource_price"]
        
        let country = extra?["country"]

        
        if let adsourcePriceString = extra?["adsource_price"] as? String,
           let adsourcePrice = Double(adsourcePriceString) {
            StartManager.shared.ecpm = Float(adsourcePrice) / 1000
            print("-----ecpm ID: \(StartManager.shared.ecpm)")
        } else {
            print("无法获取 adsource_price 或类型不匹配")
        }
        
        StartManager.shared.countryCode = country as? String
        StartManager.shared.network = network(networkID as! Int)
        StartManager.shared.shelfNumber = "开屏load"
        StartManager.shared.adId = self.idstring
        setPostload()
        
        
   
        
        
    print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(placementID)")
    
}
    
//    load失败
    func didFailToLoadAD(withPlacementID placementID: String!, error: (any Error)!) {
        print("----load失败")
        print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(String(describing: placementID))---error\(String(describing: error))")
        
    }
}
