//
//  AV_AddWaterVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/8.
//

import UIKit
import SVProgressHUD
import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig
class AV_AddWaterVC: AV_RootVC {
    
    @IBOutlet weak var mcView: UIView!
    
    @IBOutlet weak var bgView: UIView!
    
    
    @IBOutlet weak var sureBtn: UIButton!
    
    @IBOutlet weak var mlTextf: UITextField!
    
    
    
    @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 customView: UIView!
    var bottomConstraint: NSLayoutConstraint?
    
    
    var interstitialAd: MAInterstitialAd!
    var remoteConfig: RemoteConfig!
    var isadshow:Bool = false
    var retryAttempt = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
       
        setcollectionV()
        rulerV = MLSliderRulerView(frame:cupuView.bounds)

        self.cupuView.addSubview(rulerV)
        
        sureBtn.layer.cornerRadius = 25
        
        self.mcView.isHidden = true
        self.bgView.isHidden = true
        bgView.layer.cornerRadius = 30
    }
   
    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")
    }
    
    
    @IBAction func back(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func addml(_ sender: UIButton) {
        let currentRulerValue = rulerV.rulerScrollView.currentRulerValue
                print("----\(currentRulerValue)")
        let defaults = UserDefaults.standard
        let answer = defaults.integer(forKey: "waveView")
        let neanswer = answer + Int(currentRulerValue)
        defaults.set(neanswer, forKey: "waveView")
        
        SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
            SVProgressHUD.dismiss()
        }
        
    }
    
    @IBAction func keyBoard(_ sender: Any) {
        if self.isadshow == true{
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.5) {
                
                if self.interstitialAd.isReady {
                    self.interstitialAd.show()
                    self.setPostSHOW()
                    
                }else{
//                    self.navigationController?.popViewController(animated: true)
                    self.mcView.isHidden = false
                    self.bgView.isHidden = false
                    self.mlTextf.becomeFirstResponder()
                }
            }
        }else{
//            self.navigationController?.popViewController(animated: true)
            self.mcView.isHidden = false
            self.bgView.isHidden = false
            self.mlTextf.becomeFirstResponder()
        }

    }
    
    
    
    @IBAction func deleteBtn(_ sender: Any) {
        self.mcView.isHidden = true
        self.bgView.isHidden = true
        // 示例：关闭键盘
        mlTextf.resignFirstResponder()
    }
    
    
    @IBAction func sureBtn(_ sender: UIButton) {
        self.mcView.isHidden = true
        self.bgView.isHidden = true
        // 示例：关闭键盘
        mlTextf.resignFirstResponder()
        let defaults = UserDefaults.standard
        let answer = defaults.integer(forKey: "waveView")
        let neanswer = answer + (Int("\(mlTextf.text ?? "0")") ?? 0)
        defaults.set(neanswer, forKey: "waveView")
        navigationController?.popViewController(animated: true)
        SVProgressHUD.showSuccess(withStatus: "Add drinking water successfully")
        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.5) {
            SVProgressHUD.dismiss()
        }
    }
    
   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        self.createInterstitialAd()
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        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 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)")
                }
            }
        
    }

}
extension AV_AddWaterVC: 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_AddWaterVC: MAAdDelegate
{
    func createInterstitialAd()
    {
        let randomString = getRandomString()
        interstitialAd = MAInterstitialAd(adUnitIdentifier: randomString ?? "2e66a808a4251e3a")
        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 = "2e66a808a4251e3a"
        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)
        self.mcView.isHidden = false
        self.bgView.isHidden = false
        mlTextf.becomeFirstResponder()
    }
    
    func didFail(toDisplay ad: MAAd, withError error: MAError)
    {
        // Interstitial ad failed to display. We recommend loading the next ad
        interstitialAd.load()
    }
}
