//
//  WA_RankingVC.swift
//  wallpaper_project


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

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()
        loadTopAD()
    }
    func loadTopAD(){
        let extra: [String: Any] = [
                 kATAdLoadingExtraMediaExtraKey: "custom_values"
             ]
        ATAdManager.shared().loadAD(withPlacementID: "n66bdc1da370ec", extra: extra, delegate: self)
        self.fetchRemoteConfig()
        
    }
    
    
    @IBAction func addBtn(_ sender: Any) {
        self.isseleted = false
        
        
        if  self.isadshow == true{
            if ATAdManager.shared().interstitialReady(forPlacementID: "n66bdc1da370ec"){
                ATAdManager.shared().showInterstitial(withPlacementID: "n66bdc1da370ec", in: self, delegate: self)
                StartManager.shared.shelfNumber = "发布show"
                setPostSHOW()
                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)
                }
            }
            
        }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)

    }
    
  
    
    
    
    
}

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

        let issureready = newInterstitialAdManager?.isAdReady()
        if  self.isadshow == true{
           if ATAdManager.shared().interstitialReady(forPlacementID: "n66bdc1da370ec"){
                ATAdManager.shared().showInterstitial(withPlacementID: "n66bdc1da370ec", in: self, delegate: self)
               StartManager.shared.shelfNumber = "发布show"
               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)
        }
    }
    
}

extension WA_RankingVC:ATInterstitialDelegate{
//    插页广告展示成功
    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()
        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 didFinishLoadingAD(withPlacementID placementID: String!) {
        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))")
        
    }
    // 完成加载广告
    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 = "n66bdc1da370ec"
        setPostload()

    print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(placementID)")
    
}
}

