//
//  WA_4KVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/11.
//

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

class WA_4KVC: WA_RootVC {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    var wallpapers = [WA_3DModel]()
    
    var currentPage: Int = 1 // 当前页数
    let pageSize: Int = 10 // 每页加载的数量
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
//    var MKArr = [WallpaperModel]()
    
    // 存储不同类型的壁纸数组
    var newestWallpapers: [WallpaperData] = []
    var popularWallpapers: [WallpaperData] = []
    var FlowersWallpapers: [WallpaperData] = []
    var SuperheroesWallpapers: [WallpaperData] = []
    var ChristmasWallpapers: [WallpaperData] = []
    
    
    var remoteConfig: RemoteConfig!
    
    var isadshow:Bool = false
    
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    
    @IBOutlet weak var nameLabel: UILabel!
    var type:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.createInterstitialAd()
        Analytics.logEvent("in_4k", parameters: nil)
        self.view.backgroundColor = .white
        setCollectionView()

        setRefresh()
        
        if StartManager.shared.superHero == true{
//             return dataimag.count
//            cell.typeImagV.image = UIImage(named: "\(self.dataimag[indexPath.row])")
            if self.type == 1{
                self.nameLabel.text = "4K"
//                 self.wallpapers.count
            }else if type == 2{
                self.nameLabel.text = "Newest"
            }else if type == 3{
                self.nameLabel.text = "Popular Wallpapers"
            }else if type == 4{
                self.nameLabel.text = "Superheroes"
            }else if type == 5{
                self.nameLabel.text = "Christmas Wallpapers"
            }else{
                self.nameLabel.text = "Flowers"
            }
        }else{
//             return dataimaghero.count
//            cell.typeImagV.image = UIImage(named: "\(self.dataimaghero[indexPath.row])")
            if self.type == 1{
                self.nameLabel.text = "4K"
//                 self.wallpapers.count
            }else if type == 2{
                self.nameLabel.text = "Newest"
            }else if type == 3{
                self.nameLabel.text = "Popular Wallpapers"
            }else if type == 4{
                self.nameLabel.text = "Christmas Wallpapers"
            }else{
                self.nameLabel.text = "Flowers"
            }
        }


    }
    
    @IBAction func backbtn(_ sender: Any) {
//        if self.isadshow == true{
//            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.5) {
//                
//                if self.interstitialAd.isReady {
//                    self.interstitialAd.show()
//                    Analytics.logEvent("details_load_success", parameters: nil)
//                    self.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{
//                    self.navigationController?.popViewController(animated: true)
//                }
//            }
//        }else{
//            self.navigationController?.popViewController(animated: true)
//        }
        
        let issureready = newInterstitialAdManager?.isAdReady()
        if  self.isadshow == true{
            if ((issureready) != nil) {
                newInterstitialAdManager?.show(from: self)
            }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()
//        footer.beginRefreshing()
        
        
    }
    // 下拉刷新
       @objc func refreshData() {
           currentPage = 1
           setJsondata()
           settypeNetwork()
       }
       
       // 上拉加载更多
       @objc func loadMoreData() {
           currentPage += 1
           setJsondata()
           settypeNetwork()
       }
    
    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")
        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()
            }
        }
//        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)")
                }
            }
        }
        
    }
    
    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")
        
    }
    func setJsondata(){
        // 读取 JSON 文件并解析
        if let path = Bundle.main.path(forResource: "4k", 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.")
        }
    }
    
    func settypeNetwork(){
        // 读取 JSON 文件路径
        guard let jsonFilePath = Bundle.main.path(forResource: "my_wallpaper", ofType: "json") else {
            fatalError("Unable to locate my_wallpaper.json file.")
        }

        // 读取 JSON 数据
        do {
            // 读取 JSON 数据
            let jsonData = try Data(contentsOf: URL(fileURLWithPath: jsonFilePath))
            
            // 尝试将 JSON 数据转换为 Swift 对象
            let decoder = JSONDecoder()
            let wallpaperModels = try decoder.decode([WallpaperModel].self, from: jsonData)
               
            // 遍历解析后的 WallpaperModel 对象数组
            for wallpaperModel in wallpaperModels {
                // 根据名称将数据放入不同的数组中
                switch wallpaperModel.name {
                case "Newest":
                    newestWallpapers = wallpaperModel.data
                case "Popular Wallpapers":
                    popularWallpapers = wallpaperModel.data
                case "Superheroes":
                    SuperheroesWallpapers = wallpaperModel.data
                case "Christmas Wallpapers":
                    ChristmasWallpapers = wallpaperModel.data
                case "Flowers":
                    FlowersWallpapers = wallpaperModel.data
                default:
                    break
                }
            }
            
        } catch {
            print("Error reading or parsing JSON file: \(error)")
        }
    }
    
    
    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_4KVC:JXSegmentedListContainerViewListDelegate{
    func listView() -> UIView {
        return view
    }
}
extension WA_4KVC: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)
    }
}
extension WA_4KVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if  StartManager.shared.superHero == true{
            if self.type == 1{
                return self.wallpapers.count
            }else if type == 2{
                return self.newestWallpapers.count
            }else if type == 3{
                return self.popularWallpapers.count
            }else if type == 4{
                return self.SuperheroesWallpapers.count
            }else if type == 5{
                return self.ChristmasWallpapers.count
            }else{
                return self.FlowersWallpapers.count
            }
        }else{
            if self.type == 1{
                return self.wallpapers.count
            }else if type == 2{
                return self.newestWallpapers.count
            }else if type == 3{
                return self.popularWallpapers.count
            }else if type == 4{
                return self.ChristmasWallpapers.count
            }else{
                return self.FlowersWallpapers.count
            }
        }


        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WA_WallpaperCollectionCell", for: indexPath)as!WA_WallpaperCollectionCell
        if StartManager.shared.superHero == true{
            if self.type == 1{
                cell.model = self.wallpapers[indexPath.row]
            }else if type == 2{
                let model = self.newestWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else if type == 3{
                let model = self.popularWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else if type == 4{
                let model = self.SuperheroesWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else if type == 5{
                let model = self.ChristmasWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else{
                let model = self.FlowersWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }
        }else{
            if self.type == 1{
                cell.model = self.wallpapers[indexPath.row]
            }else if type == 2{
                let model = self.newestWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else if type == 3{
                let model = self.popularWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else if type == 4{
                let model = self.ChristmasWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }else{
                let model = self.FlowersWallpapers[indexPath.row]
                if let imageURL = URL(string: model.previewThumb ?? "") {
                    cell.wpImagV.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "Rectangle"))
                    }
            }
        }
        
        

        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = WA_DetailsVC()
        vc.type = self.type
        if self.type == 1{
            vc.model = self.wallpapers[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }else if type == 2{
            vc.modeltype = self.newestWallpapers[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }else if type == 3{
            vc.modeltype = self.popularWallpapers[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }else if type == 4{
            vc.modeltype = self.SuperheroesWallpapers[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }else if type == 5{
            vc.modeltype = self.ChristmasWallpapers[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }else{
            vc.modeltype = self.FlowersWallpapers[indexPath.row]
            navigationController?.pushViewController(vc, animated: true)
        }
        
    }
}
//if self.type == 1{
//    return self.wallpapers.count
//}else if type == 2{
//    return self.newestWallpapers.count
//}else if type == 3{
//    return self.popularWallpapers.count
//}else if type == 4{
//    return self.SuperheroesWallpapers.count
//}else if type == 5{
//    return self.ChristmasWallpapers.count
//}else{
//    return self.FlowersWallpapers.count
//}
//extension WA_4KVC: MAAdDelegate
//{
//    func createInterstitialAd()
//    {
//        interstitialAd = MAInterstitialAd(adUnitIdentifier: "880a042774979c3c")
//        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 = "880a042774979c3c"
//        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()
//        self.navigationController?.popViewController(animated: true)
//    }
//    
//    func didFail(toDisplay ad: MAAd, withError error: MAError)
//    {
//        // Interstitial ad failed to display. We recommend loading the next ad
//        interstitialAd.load()
//    }
//}
