//
//  WA_LIVEVC.swift
//  wallpaper_project


import UIKit
import JXSegmentedView
import MJRefresh
import FirebaseAnalytics
import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig
import MTGSDKNewInterstitial
import MTGSDKBidding
import MTGSDK
import AnyThinkInterstitial

class WA_LIVEVC: WA_RootVC {
    
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    var wallpapers = [WA_3DModel]()
    
    var currentPage: Int = 1 // 当前页数
    let pageSize: Int = 10 // 每页加载的数量
    var isback:Bool = false
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
  
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    
    
    var remoteConfig: RemoteConfig!
    
    var isadshow:Bool = false
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.createInterstitialAd()
        self.view.backgroundColor = .white
        setCollectionView()
     
        Analytics.logEvent("in_live", parameters: nil)
        setRefresh()
    }
    
    
    @IBAction func back(_ sender: Any) {
        isback = true
        if  self.isadshow == true{
            if ATAdManager.shared().interstitialReady(forPlacementID: "n66bdc1be5c449"){
                ATAdManager.shared().showInterstitial(withPlacementID: "n66bdc1be5c449", in: self, delegate: self)
                StartManager.shared.shelfNumber = "动态页面壁纸show"
              setPostSHOW()
            }else{
                self.navigationController?.popViewController(animated: true)
            }
            
        }else{
            self.navigationController?.popViewController(animated: true)
        }
 
    }
    
    
    
    @objc func setRefresh(){
        refreshData()
 
        header.setRefreshingTarget(self, refreshingAction: #selector(WA_LIVEVC.setRefresh))
        // 现在的版本要用mj_header
        
        header.setTitle("pull-to-refresh", for: .idle)
        header.setTitle("Release updates", for: .pulling)
        header.setTitle("Refreshing...", for: .refreshing)
        self.collectionView.mj_header = header
        
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(WA_LIVEVC.loadMoreData))
        footer.setTitle("Pull up loading", for: .idle)
        footer.setTitle("Release Load", for: .pulling)
        footer.setTitle("Loading...", for: .refreshing)
        self.collectionView.mj_footer = footer
  
        
        header.beginRefreshing()
    }
    func setCollectionView(){
        collectionView.delegate = self
        collectionView.dataSource = self
        
        // 设置 collection view 的布局
               let layout = CustomCollectionViewFlowLayout()
               collectionView.collectionViewLayout = layout
            layout.scrollDirection = .vertical
        
        collectionView.register(UINib(nibName: "WA_WallpaperCollectionCell", bundle: nil), forCellWithReuseIdentifier: "WA_WallpaperCollectionCell")
        
    }
    
    // 下拉刷新
       @objc func refreshData() {
           currentPage = 1
           setJsondata()
       }
       
       // 上拉加载更多
       @objc func loadMoreData() {
           currentPage += 1
           setJsondata()
       }
    
    func setJsondata(){
        // 读取 JSON 文件并解析
        if let path = Bundle.main.path(forResource: "live", ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                
                // 使用 MJExtension 解析 JSON 数据
                let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: Any]]
                
                if let jsonArray = jsonArray {
                    // 使用 MJExtension 将 JSON 数组转换为模型数组
                    
                   let wallpapersarr = (WA_3DModel.mj_objectArray(withKeyValuesArray: jsonArray) as? [WA_3DModel])!
                    
                    if currentPage == 1 {
                                // 只取前10条数据
                                let firstTenWallpapers = Array(wallpapersarr.prefix(10))
                        self.wallpapers = firstTenWallpapers
                                collectionView.reloadData()
                                collectionView.mj_header?.endRefreshing()
                            } else {
                                // 上拉加载更多
                                let startIndex = currentPage * pageSize
                                let moreWallpapers = Array(wallpapersarr.prefix(startIndex))
                                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5){
                                    self.wallpapers = moreWallpapers
                                    self.collectionView.reloadData()
                                    self.collectionView.mj_footer?.endRefreshing()

                                        }
                            }
                }
            } catch {
                print("Error reading JSON file:", error.localizedDescription)
            }
        } else {
            print("JSON file not found.")
        }

    }
    
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        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: "n66bdc1be5c449", extra: extra, delegate: self)
        self.fetchRemoteConfig()
        
    }
    
    ///是否有广告
    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)")
                }
            }
        }
        
    }
    
    
   
    
    
  
    
    
}

extension WA_LIVEVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
    
        return self.wallpapers.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WA_WallpaperCollectionCell", for: indexPath)as!WA_WallpaperCollectionCell
        cell.model = self.wallpapers[indexPath.row]
        return cell
    } 
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = WA_LiveVideoVC()
        vc.model = self.wallpapers[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
        
    }
}


extension WA_LIVEVC: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()
        self.navigationController?.popViewController(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 = "n66bdc1be5c449"
        setPostload()
        
        
   
        
        
    print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(placementID)")
    
}
}
