//
//  AV_DetalisVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/4/16.
//

import UIKit
import WCDBSwift
import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig

class AV_DetalisVC: AV_RootVC {
    @IBOutlet weak var imageV: UIImageView!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var contentLabel: UILabel!
    
    
    @IBOutlet weak var wsichsel: UISwitch!
    
    @IBOutlet weak var bgView: UIView!
    
    var interstitialAd: MAInterstitialAd!
    var remoteConfig: RemoteConfig!
    var isadshow:Bool = false
    var retryAttempt = 0.0
    
    var model:UserModel?
    override func viewDidLoad() {
        super.viewDidLoad()
//        bgView.clipsToBounds = true
        bgView.layer.cornerRadius = 20
        imageV.layer.cornerRadius = 20
        // 设置阴影属性
        bgView.layer.shadowColor = UIColor.hexSting(color: "#9ABDE6", alpha: 0.25).cgColor
        bgView.layer.shadowOpacity = 0.5
        bgView.layer.shadowOffset = CGSize(width: 0, height: 2) // 设置向下偏移
        bgView.layer.shadowRadius = 4
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createInterstitialAd()
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        fetchRemoteConfig()
        self.navigationController?.navigationBar.isHidden = true
        let image = model?.getImage()
        self.imageV.image = image
        self.timeLabel.text = model?.date
        self.contentLabel.text = model?.name
        self.wsichsel.isOn = ((model?.notificationEnabled) != nil)
        
    }
    
    @IBAction func editBtn(_ sender: UIButton) {
        let vc = AV_AddVC()
        vc.model = self.model
        vc.typeedit = 1
        vc.dataUpdateClosure = { [self] updatedModels in
            // 在闭包中接收更新的模型数组
            self.model = updatedModels
            // 在这里处理接收到的模型数组，例如重新加载数据或者刷新界面
            let image = model!.getImage()
            self.imageV.image = image
            self.timeLabel.text = model?.date
            self.contentLabel.text = model?.name
            self.wsichsel.isOn = ((model?.notificationEnabled) != nil)
        }
        navigationController?.pushViewController(vc, animated: true)
        
        
    }
    
    
    @IBAction func deleteBtn(_ sender: UIButton) {
       
        if self.isadshow == true{
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.5) {
                
                if self.interstitialAd.isReady {
                    self.interstitialAd.show()
                    self.setPostSHOW()
                    if let uid = self.model?.uid {
                        // 构建删除条件
                        let condition: Condition = UserModel.Properties.uid == uid
                        
                        // 调用删除方法
                        PrWCDBBaseManager.shared.deleteFromDb(fromTable: userModelTableName, where: condition)
                    } else {
                        print("Error: Model UID is nil")
                    }

                }else{
                    if let uid = self.model?.uid {
                        // 构建删除条件
                        let condition: Condition = UserModel.Properties.uid == uid
                        
                        // 调用删除方法
                        PrWCDBBaseManager.shared.deleteFromDb(fromTable: userModelTableName, where: condition)
                    } else {
                        print("Error: Model UID is nil")
                    }

                    self.navigationController?.popViewController(animated: true)
                }
            }
        }else{
            if let uid = model?.uid {
                // 构建删除条件
                let condition: Condition = UserModel.Properties.uid == uid
                
                // 调用删除方法
                PrWCDBBaseManager.shared.deleteFromDb(fromTable: userModelTableName, where: condition)
            } else {
                print("Error: Model UID is nil")
            }

            self.navigationController?.popViewController(animated: true)
        }
//        navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func back(_ 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)
                }
            }
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    ///是否有广告
    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_DetalisVC: MAAdDelegate
{
    func createInterstitialAd()
    {
        let randomString = getRandomString()
        interstitialAd = MAInterstitialAd(adUnitIdentifier: randomString ?? "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
        
        
        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()
    }
}
