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

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


class WA_CommunityPlayerVC: WA_RootVC {

    @IBOutlet weak var tableView: UITableView!
    
    var MKArr = [WA_RakModel]()
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    var touchrelease:Bool = false
    var indexrow:Int?
    var isseleted:Bool = false
    let activityView = UIActivityIndicatorView()
    
    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()
//        self.createInterstitialAd()
        setNetwork()
        settableView()

        let param = MTGBiddingRequestParameter(placementId: "1650169", unitId: "3518993", basePrice: nil)
        
        MTGBiddingRequest.getBidWith(param) { bidResponse in
            if bidResponse.success{
                self.bidToken = bidResponse.bidToken
                bidResponse.notifyWin()
                self.newInterstitialAdManager = MTGNewInterstitialBidAdManager(placementId: "1650169", unitId: "3518993", delegate: self)
                StartManager.shared.ecpm = Float(bidResponse.price)
                self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                
                self.startAdCheck()
            }else{
//                WA_TabbarCommon.TabBarController()
                self.navigationController?.popViewController(animated: true)
            }
        }

    }
    
    func settableView(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "WA_RakingCell", bundle: nil), forCellReuseIdentifier: "WA_RakingCell")
    }
    
    func setNetwork(){
        if let path = Bundle.main.path(forResource: "rankJson", ofType: "json"),
           let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)),
           let rkModels = try? JSONDecoder().decode([WA_RakModel].self, from: jsonData) {
            MKArr = rkModels
        } else {
            print("Failed to read or parse JSON file.")
        }
    }
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        // 初始化 Remote Config
//        remoteConfig = RemoteConfig.remoteConfig()
        
        
      
       
    }
    //    /定时加载
    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("广告未准备好，继续检查...")
        }
        
    }
    
    @IBAction func addBtn(_ sender: Any) {
        self.isseleted = false
        
        let issureready = newInterstitialAdManager?.isAdReady()
        if  self.isadshow == true{
            if ((issureready) != nil) {
                newInterstitialAdManager?.show(from: self)
            }else{
                if isLoggedIn(){
                    let vc = WA_AddVC()
                    vc.modalPresentationStyle = .fullScreen
                    self.present(vc, animated: true)

                }else{
                    let vc = WA_LoginVC()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            
        }else{
            if isLoggedIn(){
                let vc = WA_AddVC()
                vc.modalPresentationStyle = .fullScreen
                self.present(vc, animated: true)

            }else{
                let vc = WA_LoginVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        
   


    }
    
    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_CommunityPlayerVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return MKArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "WA_RakingCell", for: indexPath)as!WA_RakingCell
        cell.model = MKArr[indexPath.row]
        cell.shView.isHidden = true
       
        return cell
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
    
}
extension WA_CommunityPlayerVC:MTGNewInterstitialBidAdDelegate{
    
    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 = "3518993"
StartManager.shared.platformResponseTime = 0
//        StartManager.shared.ecpm = Float(ad.revenue)
        StartManager.shared.dsp = ""
        StartManager.shared.network = ""


        setPostload()
    }
    
    
    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)
    }
}
