//
//  WA_AddVC.swift
//  wallpaper_project


import UIKit
import SVProgressHUD
import AppLovinSDK
import FirebaseAnalytics
import FirebaseCore
import FirebaseRemoteConfig
import MTGSDKNewInterstitial
import MTGSDKBidding
import MTGSDK
import AnyThinkInterstitial

class WA_AddVC: WA_RootVC,UITextViewDelegate {
    @IBOutlet weak var contentImageV: UIImageView!
    
    
    @IBOutlet weak var contenttextV: UITextView!
    
    @IBOutlet weak var sureBtn: UIButton!
    let placeholderLabel = UILabel()
    
    let activityView = UIActivityIndicatorView()
    
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    var remoteConfig: RemoteConfig!
    var isadshow:Bool = false
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化 Remote Config
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        // Fetch 配置值
//        fetchRemoteConfig()
        
//        fetchRemoteConfig()
        Analytics.logEvent("in_release", parameters: nil)
        contenttextV.layer.cornerRadius = 5
        contenttextV.layer.borderColor = UIColor.black.cgColor
        contenttextV.layer.borderWidth = 1
        
        contentImageV.layer.cornerRadius = 5
        sureBtn.layer.cornerRadius = 5
        // 设置textView的frame等属性
        
        contenttextV.delegate = self
        
        
        // 添加占位符Label
        placeholderLabel.text = "Please enter the content..."
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.frame = CGRect(x: 5, y: 8, width: contenttextV.frame.width - 10, height: 20)
        contenttextV.addSubview(placeholderLabel)
        
        activityView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - kSafeArea_Top - 44)
        // 停止后，隐藏菊花
        activityView.hidesWhenStopped = true
        activityView.color = .black
        activityView.style = UIActivityIndicatorView.Style.whiteLarge
        
        self.view.addSubview(activityView)
    }
    
    func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        self.createInterstitialAd()
        
        loadTopAD()
    }
    func loadTopAD(){
        let extra: [String: Any] = [
                 kATAdLoadingExtraMediaExtraKey: "custom_values"
             ]
        ATAdManager.shared().loadAD(withPlacementID: "n66bdc1da370ec", extra: extra, delegate: self)
        self.fetchRemoteConfig()
        
    }
    
    @IBAction func backBtn(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    
    @IBAction func upBtn(_ sender: Any) {
        var imagePicker = UIImagePickerController()
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            imagePicker.delegate = self
//            imagePicker.allowsEditing = true
            imagePicker.sourceType = .photoLibrary
            present(imagePicker, animated: true, completion: nil)
        }
        
    }
    
    
    @IBAction func sureBtn(_ sender: Any) {
        
        if self.contenttextV.text.count <= 0 {
            SVProgressHUD.showInfo(withStatus: "Please enter your recommendation reason")
            DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
            SVProgressHUD.dismiss()
            }
        }else if self.contentImageV.image == nil{
            SVProgressHUD.showInfo(withStatus: "Please select the image you recommend")
            DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
            SVProgressHUD.dismiss()
            }
        }else{
            DispatchQueue.main.asyncAfter(deadline: .now()){
                self.activityView.startAnimating()
                DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                    DispatchQueue.main.asyncAfter(deadline: .now()){
                        self.activityView.stopAnimating()
                        self.dismiss(animated: true)
                    }
         

                    if  self.isadshow == true{
                        if ATAdManager.shared().interstitialReady(forPlacementID: "n66bdc1da370ec"){
                            ATAdManager.shared().showInterstitial(withPlacementID: "n66bdc1da370ec", in: self, delegate: self)
                            StartManager.shared.shelfNumber = "发布页面show"
                            setPostSHOW()
                            
                        }
                    }
                }
            }
      
            let headimage = UIImage(named: "loginhead_s")
             let base64imgString = convertImageToString(image: headimage!)
       
            let contnetimg = self.contentImageV.image
             let base64String = convertImageToString(image: contnetimg!)
        
            let dataModel1 = WA_RakModel(name: "Saul", content: self.contenttextV.text, head:base64imgString, img: base64String)
    
            PreferencesManager.shared.addRakModel(dataModel1)
            
        }
        
        
    }
    
    ///是否有广告
    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)")
                }
            }
        }
    }
    
    // 将 UIImage 转换为字符串
    func convertImageToString(image: UIImage) -> String? {
        if let imageData = image.jpegData(compressionQuality: 1.0) {
            // 将图片数据转换为 Base64 编码的字符串
            let base64String = imageData.base64EncodedString()
            return base64String
        }
        return nil
    }
    
}
extension WA_AddVC: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            contentImageV.image = selectedImage
          }
          
          picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}


extension WA_AddVC:ATInterstitialDelegate{
//    插页广告展示成功
    func interstitialDidShow(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("----成功")
    }
   /// 插页广告被点击
    func interstitialDidClick(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("----点击")
    }
//    插页广告已关闭
    func interstitialDidClose(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
        print("----关闭")
//        WA_TabbarCommon.TabBarController()
        DispatchQueue.global().asyncAfter(deadline: .now() + 1.0) {
        SVProgressHUD.dismiss()
        }
        
    }
    
    func didFinishLoadingAD(withPlacementID placementID: String!) {
        print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(placementID)")
    }
    
//    load失败
    func didFailToLoadAD(withPlacementID placementID: String!, error: (any Error)!) {
        print("----load失败")
        print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(String(describing: placementID))---error\(String(describing: error))")
        
    }
    
    // 完成加载广告
    func didFinishLoadingADSource(withPlacementID placementID: String!,extra: [AnyHashable : Any]?) {
   
        let networkID = extra?["network_firm_id"]
        
        let ecpm = extra?["adsource_price"]
        
        let country = extra?["country"]

        
        if let adsourcePriceString = extra?["adsource_price"] as? String,
           let adsourcePrice = Double(adsourcePriceString) {
            StartManager.shared.ecpm = Float(adsourcePrice) / 1000
            print("-----ecpm ID: \(StartManager.shared.ecpm)")
        } else {
            print("无法获取 adsource_price 或类型不匹配")
        }
        
        StartManager.shared.countryCode = country as? String
        StartManager.shared.network = network(networkID as! Int)
        StartManager.shared.shelfNumber = "发布页面load"
        StartManager.shared.adId = "n66bdc1da370ec"
        setPostload()

    print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(placementID)")
    
}
}

