//
//  WA_RankingVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/27.
//

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

class WA_RankingVC: 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?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.createInterstitialAd()
        setNetwork()
        settableView()

        activityView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - kSafeArea_Top - 44)
        // 停止后，隐藏菊花
        activityView.hidesWhenStopped = true
        activityView.color = .black
        activityView.style = UIActivityIndicatorView.Style.whiteLarge
        self.view.addSubview(activityView)

    }
    
    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.")
        }
    }
    
    ///是否有广告
    func fetchRemoteConfig() {
        let localVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0"
        remoteConfig.fetch{ (status, error) -> Void in
            if status == .success {
                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{
                                self.isadshow = false
                            }else{
                                if valueopen {
                                    self.isadshow = true
                                } else {
                                    self.isadshow = false
                                }
                            }
                        }
                    }
       
                }
                
            } else {
                print("Config not fetched")
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                }
            }
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        // 初始化 Remote Config
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        // Fetch 配置值
//        fetchRemoteConfig()
        let param = MTGBiddingRequestParameter(placementId: "1636950", unitId: "3501963", basePrice: nil)
        
        MTGBiddingRequest.getBidWith(param) { bidResponse in
            if bidResponse.success{
                self.bidToken = bidResponse.bidToken
                bidResponse.notifyWin()
                self.newInterstitialAdManager = MTGNewInterstitialBidAdManager(placementId: "1636950", unitId: "3501963", delegate: self)
                self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                self.fetchRemoteConfig()
                
            }else{
                WA_TabbarCommon.TabBarController()
            }
        }
    }
    
    
    @IBAction func addBtn(_ sender: Any) {
        self.isseleted = false
        
//        if self.isadshow == true{
//            if interstitialAd.isReady {
//                interstitialAd.show()
//                Analytics.logEvent("touchrelease_load_success", parameters: nil)
//                setPostSHOW()
//                let logMessage = """
//                    deviceId: \(StartManager.shared.devicID ?? "")
//                    localIp: \(StartManager.shared.localIP ?? "")
//                    "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)
//            }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)
//            }
//            
//        }
        
        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)
            }
        }
        
        
   
//        Analytics.logEvent("goin_release", parameters: nil)

    }
    
    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_RankingVC: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
        cell.reportBlcok = {
            // 创建一个 UIAlertController
            let alertController = UIAlertController(title: "report", message: "Report the content of this comment?", preferredStyle: .alert)
            
            // 添加一个取消按钮
            alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
            
            // 添加一个确定按钮
            alertController.addAction(UIAlertAction(title: "report", style: .default, handler: { action in
                // 点击确定按钮后执行的操作
                //                    print("点击了确定按钮")
                DispatchQueue.main.asyncAfter(deadline: .now()){
                    self.activityView.startAnimating()
                    
                    DispatchQueue.global().asyncAfter(deadline: .now() + 1.5){
                        DispatchQueue.main.asyncAfter(deadline: .now()){
                            self.activityView.stopAnimating()
                            SVProgressHUD.showInfo(withStatus: "Successfully submitted. Thank you for your feedback. We will review this comment again in the future")
                            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                                SVProgressHUD.dismiss()
                            }
                        }
                        
                        
                    }
                }
            }))
            
            // 在当前视图控制器中 present 显示提示框
            self.present(alertController, animated: true, completion: nil)
        }
        
        cell.blackBLcok = {
            // 创建一个 UIAlertController
            let alertController = UIAlertController(title: "Block", message: "Blacklisting comment content?", preferredStyle: .alert)
            
            // 添加一个取消按钮
            alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
            
            // 添加一个确定按钮
            alertController.addAction(UIAlertAction(title: "Block", style: .default, handler: { action in
                // 点击确定按钮后执行的操作
                //                    print("点击了确定按钮")
                DispatchQueue.main.asyncAfter(deadline: .now()){
                    self.activityView.startAnimating()
                    DispatchQueue.global().asyncAfter(deadline: .now() + 1.5){
                        DispatchQueue.main.asyncAfter(deadline: .now()){
                            self.activityView.stopAnimating()
                            let selectedModel = self.MKArr[indexPath.row]
                            self.MKArr.remove(at: indexPath.row)
                            self.tableView.deleteRows(at: [indexPath], with: .fade)
                            SVProgressHUD.showInfo(withStatus: "Successfully submitted. Thank you for your feedback. We will review this comment again in the future")
                            self.tableView.reloadData()
                            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                                SVProgressHUD.dismiss()
                                
                            }
                            
                        }
                    }
                }
            }))
            
            // 在当前视图控制器中 present 显示提示框
            self.present(alertController, animated: true, completion: nil)
        }
   
        return cell
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.isseleted = true
        self.indexrow = indexPath.row
//        if self.isadshow == true{
//            if interstitialAd.isReady {
//                interstitialAd.show()
//                Analytics.logEvent("touchrelease_load_success", parameters: nil)
//                setPostSHOW()
//
//            }else{
//                let vc = WA_RKDetailsVC()
//                vc.model = MKArr[indexPath.row]
//                self.navigationController?.pushViewController(vc, animated: true)
//            }
//        }else{
//            let vc = WA_RKDetailsVC()
//            vc.model = MKArr[indexPath.row]
//            self.navigationController?.pushViewController(vc, animated: true)
//        }
        let issureready = newInterstitialAdManager?.isAdReady()
        if  self.isadshow == true{
            if ((issureready) != nil) {
                newInterstitialAdManager?.show(from: self)
            }else{
                let vc = WA_RKDetailsVC()
                vc.model = MKArr[indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
        }else{
            let vc = WA_RKDetailsVC()
            vc.model = MKArr[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
extension WA_RankingVC: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("广告被关闭")
//        self.navigationController?.popViewController(animated: true)
                if self.isseleted == false{
                    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{
                    let vc = WA_RKDetailsVC()
                    vc.model = MKArr[indexrow!]
                    self.navigationController?.pushViewController(vc, animated: true)
                }
    }
}
//extension WA_RankingVC: MAAdDelegate
//{
//    func createInterstitialAd()
//    {
//        interstitialAd = MAInterstitialAd(adUnitIdentifier: "83802ca889ba09e6")
//        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 = "83802ca889ba09e6"
//        StartManager.shared.platformResponseTime = ad.requestLatency
//        StartManager.shared.ecpm = Float(ad.revenue)
//        StartManager.shared.dsp = ad.dspName
//        StartManager.shared.network = ad.networkName
//        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()
//        
//        if self.isseleted == false{
//            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{
//            let vc = WA_RKDetailsVC()
//            vc.model = MKArr[indexrow!]
//            self.navigationController?.pushViewController(vc, animated: true)
//        }
// 
//    }
//    
//    func didFail(toDisplay ad: MAAd, withError error: MAError)
//    {
//        // Interstitial ad failed to display. We recommend loading the next ad
//        interstitialAd.load()
//    }
//}
