//
//  AV_MinePlayerVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/21.
//

import UIKit


import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig


class AV_MinePlayerVC: AV_RootVC {
    
    
    var retryAttempt = 0.0
    var interstitialAd: MAInterstitialAd!
    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    var adLoadTime: Int = 0
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        self.createInterstitialAd()
        startAdCheck()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        
    }
    ///定时加载
    func startAdCheck() {
        //        createInterstitialAd()
        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)
        
        if interstitialAd.isReady {
            interstitialAd.show()
            adLoadTime = elapsedTimeInMilliseconds // 记录加载
            adCheckTimer?.invalidate()
            setShow()
        } else if elapsedTimeInMilliseconds >= 10000 { // 10000 毫秒 = 10 秒
            adCheckTimer?.invalidate()
            self.navigationController?.popViewController(animated: true)
            
        } else {
            print("广告未准备好，继续检查...")
        }
    }
    
    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.countdown.day.daycount",
            "gaid": StartManager.shared.idfaid ?? "",
            "dataId": "",
            "shelfNumber":"日历添加和返回",
            "succeed": StartManager.shared.succeed,
            "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.countdown.day.daycount",
            "gaid": StartManager.shared.idfaid ?? "",
            "dataId": "",
            "shelfNumber":"日历添加和返回",
            "succeed": StartManager.shared.succeed,
            "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 setShow() {
        let idfa = StartManager.shared.idfaid
        let adId = StartManager.shared.idTwoAD
        let ecpm = StartManager.shared.idTwoprice

        AdLoader.shared.showAd(idfa: idfa, adId: adId, ecpm: ecpm) { result in
            switch result {
            case .success(let closeTime): break
//                let seconds = millisecondsToSeconds(milliseconds: closeTime)
//                DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
//                    closeADWindow()
//                }
            case .failure(let error):
                print("Error:--- \(error)")
            }
        }
    }
}
extension AV_MinePlayerVC: MAAdDelegate
{
    func createInterstitialAd()
    {
        interstitialAd = MAInterstitialAd(adUnitIdentifier: "8fccdfa964b52e26")
        interstitialAd.delegate = self
        
        // Load the first ad
        interstitialAd.load()
    }
    
    // MARK: MAAdDelegate Protocol
    
    func didLoad(_ ad: MAAd)
    {
        // Interstitial ad is ready to be shown. 'interstitialAd.isReady' will now return 'true'
        
        // Reset retry attempt
        retryAttempt = 0
        StartManager.shared.succeed = true
        //        StartManager.shared.loadTime = self.adLoadTime
        StartManager.shared.adPlatform = "MAX"
        StartManager.shared.countryCode = ALSdk.shared().configuration.countryCode
        StartManager.shared.adId = "8fccdfa964b52e26"
        StartManager.shared.platformResponseTime = ad.requestLatency
        StartManager.shared.ecpm = Float(ad.revenue)
        StartManager.shared.dsp = ad.dspName
        StartManager.shared.network = ad.networkName
        StartManager.shared.idTwoprice = Float(ad.revenue)
        print("----idTwo\(Float(ad.revenue))")
        setPostload()
    }
    
    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError)
    {
        // Interstitial ad failed to load
        // We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds)
        
        retryAttempt += 1
        let delaySec = pow(2.0, min(6.0, retryAttempt))
        
        DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
            self.interstitialAd.load()
        }
    }
    
    func didDisplay(_ ad: MAAd)
    {
        // Pause your app's background audio
    }
    
    func didClick(_ ad: MAAd) {}
    
    func didHide(_ ad: MAAd)
    {
        // Resume your app's background audio
        // Interstitial ad is hidden. Pre-load the next ad
        interstitialAd.load()
        self.navigationController?.popViewController(animated: true)
        
    }
    
    func didFail(toDisplay ad: MAAd, withError error: MAError)
    {
        // Interstitial ad failed to display. We recommend loading the next ad
        interstitialAd.load()
    }
}
