//
//  AV_WaterKeyBordPlayerVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/21.
//

import UIKit

import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig


class AV_WaterKeyBordPlayerVC: AV_RootVC {
    @IBOutlet weak var waterImageV: UIImageView!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    
    @IBOutlet weak var cupuView: UIView!
    
    let cellWidth: CGFloat = 71
    let cellHeight: CGFloat = 71
    let cellSpacing: CGFloat = 12
    let dataimag = ["1","2", "3", "4", "5", "6","7","8"]
    let databigimag = ["1-1","2-2", "3-3", "4-4", "5-5", "6-6","7-7","8-8"]
    let drinkname = ["Water","Milk", "Tea", "Milky tea", "Beer", "Red wine","Fruit juice","Soup"]
    
    var rulerV = MLSliderRulerView()
    
    
    
    var retryAttempt = 0.0
    var interstitialAd: MAInterstitialAd!
    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    var adLoadTime: Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setcollectionV()
        rulerV = MLSliderRulerView(frame:cupuView.bounds)
        
        self.cupuView.addSubview(rulerV)
        startAdCheck()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        
    }
    ///定时加载
    func startAdCheck() {
        //        createInterstitialAd()
        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)
        
        if interstitialAd.isReady {
            interstitialAd.show()
            adLoadTime = elapsedTimeInMilliseconds // 记录加载
            adCheckTimer?.invalidate()
            setShow()
        } else if elapsedTimeInMilliseconds >= 10000 { // 10000 毫秒 = 10 秒
            adCheckTimer?.invalidate()
            self.navigationController?.popViewController(animated: true)
            
        } else {
            print("广告未准备好，继续检查...")
        }
    }
    
    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.countdown.day.daycount",
            "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.countdown.day.daycount",
            "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)")
            }
        }
        
    }
    
    func setcollectionV(){
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.collectionViewLayout = layout
        collectionView.register(UINib(nibName: "AV_AddWaterVCCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "AV_AddWaterVCCollectionViewCell")
    }
    
//    func setshow(){
//        let parameters:[String : Any] = [
//            "appid": "com.countdown.day.daycount",
//            "idfa":StartManager.shared.idfaid ?? "",
//            "id":StartManager.shared.idOneAD,
//            "ecpm":StartManager.shared.idOneprice ?? "",
//            
//        ]
//        NetworkManager.shared.postRequest(url: StartManager.shared.showurl, parameters: parameters, headers: StartManager.shared.headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//                if let status = data["status"] as? String, status == "Success" {
//                    if let needLoad = data["close"] as? Int {
//                        let seconds = millisecondsToSeconds(milliseconds: needLoad)
//                        
//                        DispatchQueue.main.asyncAfter(wallDeadline: .now() + seconds) {
//                            closeADWindow()
//                        }
//                    }
//                }
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//    }
    
    func setShow() {
        let idfa = StartManager.shared.idfaid
        let adId = StartManager.shared.idThreeAD
        let ecpm = StartManager.shared.idThreeprice

        AdLoader.shared.showAd(idfa: idfa, adId: adId, ecpm: ecpm) { result in
            switch result {
            case .success(let closeTime): break
//                let seconds = millisecondsToSeconds(milliseconds: closeTime)
//                DispatchQueue.main.asyncAzfter(deadline: .now() + seconds) {
//                    closeADWindow()
//                }
            case .failure(let error):
                print("Error:--- \(error)")
            }
        }
    }
}
extension AV_WaterKeyBordPlayerVC: UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataimag.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AV_AddWaterVCCollectionViewCell", for: indexPath) as! AV_AddWaterVCCollectionViewCell
        cell.imageV.image = UIImage(named: "\(self.dataimag[indexPath.row])")
        cell.nameLabel.text = self.drinkname[indexPath.row]
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: cellWidth, height: cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return cellSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: cellSpacing, bottom: 0, right: cellSpacing)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.waterImageV.image = UIImage(named: "\(indexPath.row + 1)-\(indexPath.row + 1)")
    }
    
}
extension AV_WaterKeyBordPlayerVC: MAAdDelegate
{
    func createInterstitialAd()
    {
        interstitialAd = MAInterstitialAd(adUnitIdentifier: "7baed02646413e44")
        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 = "7baed02646413e44"
        StartManager.shared.platformResponseTime = ad.requestLatency
        StartManager.shared.ecpm = Float(ad.revenue)
        StartManager.shared.dsp = ad.dspName
        StartManager.shared.network = ad.networkName
        
        StartManager.shared.idThreeprice = Float(ad.revenue)
        
        print("----idThree\(Float(ad.revenue))")
        
        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()
    }
}
