//
//  WA_AddPlayerVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/7/19.
//

import UIKit

import SVProgressHUD
import AppLovinSDK
import FirebaseAnalytics
import FirebaseCore
import FirebaseRemoteConfig
import MTGSDKNewInterstitial
import MTGSDKBidding
import MTGSDK
import Alamofire

class WA_AddPlayerVC: WA_RootVC {

    
    let activityView = UIActivityIndicatorView()
    
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    var remoteConfig: RemoteConfig!
    var isadshow:Bool = false
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    

    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    var adLoadTime: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let param = MTGBiddingRequestParameter(placementId: "1651004", unitId: "3520023", basePrice: nil)
        
        MTGBiddingRequest.getBidWith(param) { bidResponse in
            if bidResponse.success{
                self.bidToken = bidResponse.bidToken
                bidResponse.notifyWin()
                self.newInterstitialAdManager = MTGNewInterstitialBidAdManager(placementId: "1651004", unitId: "3520023", delegate: self)
                self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
               
                self.startAdCheck()
            }else{
                self.navigationController?.popViewController(animated: true)
            }
        }

        Analytics.logEvent("in_release", parameters: nil)

    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.navigationController?.navigationBar.isHidden = true

    }
    
    //    /定时加载
    func startAdCheck() {
        
        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)
        
        let issureready = newInterstitialAdManager!.isAdReady()
        
        if issureready {
            
            self.newInterstitialAdManager?.show(from: self)
            self.setPostSHOW()
            
            
        } 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.wallpapaer.hd.live.app",
            "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.wallpapaer.hd.live.app",
            "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)")
                }
            }
        
    }


}
//extension WA_AddPlayerVC: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
//    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//        if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
////            contentImageV.image = selectedImage
//          }
//          
//          picker.dismiss(animated: true, completion: nil)
//    }
//    
//    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//        picker.dismiss(animated: true, completion: nil)
//    }
//}
extension WA_AddPlayerVC:MTGNewInterstitialBidAdDelegate{
    
    //    func newInterstitialBidAdShowSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
    //        print("广告展示成功")
    //    }
    
    func newInterstitialBidAdResourceLoadSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("资源加载成功，表示可播放状态")
    }
    
    func newInterstitialBidAdLoadSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("广告加载成功")
        StartManager.shared.succeed = true
//        StartManager.shared.loadTime = self.adLoadTime
        StartManager.shared.adPlatform = "mbridge"
        StartManager.shared.countryCode = ALSdk.shared().configuration.countryCode
        StartManager.shared.adId = "3520023"
StartManager.shared.platformResponseTime = 0
//        StartManager.shared.ecpm = Float(ad.revenue)
        StartManager.shared.dsp = ""
        StartManager.shared.network = ""
    }
    
    
    func newInterstitialBidAdLoadFail(_ error: any Error, adManager: MTGNewInterstitialBidAdManager) {
        
        print("-----\(error)")
        //        print(" 广告加载失败")
        self.navigationController?.popViewController(animated: true)
    }
    
    func newInterstitialBidAdShowSuccess(withBidToken bidToken: String, adManager: MTGNewInterstitialBidAdManager) {
        
        print("广告展示成功")
    }
    
    
    func newInterstitialBidAdShowFail(_ error: any Error, adManager: MTGNewInterstitialBidAdManager) {
        print("广告展示失败")
        self.navigationController?.popViewController(animated: true)
    }
    
    func newInterstitialBidAdPlayCompleted(_ adManager: MTGNewInterstitialBidAdManager) {
        
        print("广告播放完全播放回调")
    }
    
    
    func newInterstitialBidAdEndCardShowSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("视频播放完成后展示结果页")
    }
    
    func newInterstitialBidAdClicked(_ adManager: MTGNewInterstitialBidAdManager) {
        
        print("广告被点击")
    }
    
    // 广告被关闭
    func newInterstitialBidAdDidClosed(_ adManager: MTGNewInterstitialBidAdManager) {
        print("广告被关闭")
        self.navigationController?.popViewController(animated: true)
    }
}
