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

import UIKit
import MJExtension
import MTGSDKNewInterstitial
import MTGSDKBidding
import MTGSDK
import Alamofire


class WA_playerRankVC: WA_RootVC {
    @IBOutlet weak var collectionView: UICollectionView!
    var wallpapers = [WA_3DModel]()
    
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    
    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    var adLoadTime: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let param = MTGBiddingRequestParameter(placementId: "1650177", unitId: "3519003", basePrice: nil)
        
        MTGBiddingRequest.getBidWith(param) { bidResponse in
            if bidResponse.success{
                self.bidToken = bidResponse.bidToken
                bidResponse.notifyWin()
                self.newInterstitialAdManager = MTGNewInterstitialBidAdManager(placementId: "1650177", unitId: "3519003", delegate: self)
                StartManager.shared.ecpm = Float(bidResponse.price)
                self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                
                self.startAdCheck()
                
                
            }else{
                
                self.navigationController?.popViewController(animated: true)
                
                
            }
        }
        let layout = CustomLayout()
        collectionView.collectionViewLayout =  layout
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib(nibName: "WA_RankCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "WA_RankCollectionViewCell")
        setJsondata()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
       
    }
    
    
    
    //    /定时加载
    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("广告未准备好，继续检查...")
        }
        
    }
    
    
    
    func setJsondata(){
        // 读取 JSON 文件并解析
        if let path = Bundle.main.path(forResource: "rank", 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])!
                    self.wallpapers = wallpapersarr
                    
                }
            } catch {
                print("Error reading JSON file:", error.localizedDescription)
            }
        } else {
            print("JSON file not found.")
        }
        
    }
    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_playerRankVC:MTGNewInterstitialBidAdDelegate{
    
    //    func newInterstitialBidAdShowSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
    //        print("广告展示成功")
    //    }
    
    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 = "3519003"
        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)
    }
}

extension WA_playerRankVC:UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return wallpapers.count // 你可以设置你的图片数量
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WA_RankCollectionViewCell", for: indexPath) as! WA_RankCollectionViewCell
        
        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)
        
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let collectionView = collectionView else { return }
        
        let itemHeight = collectionView.bounds.height * 2.5 / 3
        let currentOffset = scrollView.contentOffset.y
        let targetOffset = targetContentOffset.pointee.y
        
        let currentItemIndex = round(currentOffset / itemHeight)
        let targetItemIndex = targetOffset > currentOffset ? currentItemIndex + 1 : currentItemIndex - 1
        
        let newOffsetY = targetItemIndex * itemHeight
        targetContentOffset.pointee.y = newOffsetY
        
    }
    
}



