//
//  WA_AddVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/27.
//

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

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()
        
        let param = MTGBiddingRequestParameter(placementId: "1636950", unitId: "3501963", basePrice: nil)
        
        MTGBiddingRequest.getBidWith(param) { bidResponse in
            if bidResponse.success{
                self.bidToken = bidResponse.bidToken
                bidResponse.notifyWin()
                self.newInterstitialAdManager = MTGNewInterstitialBidAdManager(placementId: "1636950", unitId: "3501963", delegate: self)
                self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
                self.fetchRemoteConfig()
                
            }else{
                WA_TabbarCommon.TabBarController()
            }
        }
    }
    
    
    @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 self.interstitialAd.isReady {
//                            self.interstitialAd.show()
//                            Analytics.logEvent("release_load_success", parameters: nil)
//                        }else{
//                            print("-------广告没准备好")
//                            Analytics.logEvent("release_load_fail", parameters: nil)
//                        }
                        let issureready = self.newInterstitialAdManager?.isAdReady()
                        if  self.isadshow == true{
                            if ((issureready) != nil) {
                                self.newInterstitialAdManager?.show(from: self)
                            }
                            
                        }
                    }
                }
            }
      
            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:MTGNewInterstitialBidAdDelegate{
    
    //    func newInterstitialBidAdShowSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
    //        print("广告展示成功")
    //    }
    
    func newInterstitialBidAdResourceLoadSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("资源加载成功，表示可播放状态")
    }
    
    func newInterstitialBidAdLoadSuccess(_ adManager: MTGNewInterstitialBidAdManager) {
        print("广告加载成功")
    }
    
    
    func newInterstitialBidAdLoadFail(_ error: any Error, adManager: MTGNewInterstitialBidAdManager) {
        
        print("-----\(error)")
        //        print(" 广告加载失败")
    }
    
    func newInterstitialBidAdShowSuccess(withBidToken bidToken: String, adManager: MTGNewInterstitialBidAdManager) {
        
        print("广告展示成功")
    }
    
    
    func newInterstitialBidAdShowFail(_ error: any Error, adManager: MTGNewInterstitialBidAdManager) {
        print("广告展示失败")
    }
    
    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)
                SVProgressHUD.showInfo(withStatus: "Successfully published, waiting for review")
                DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
                    SVProgressHUD.dismiss()
                }
    }
}
//extension WA_AddVC: MAAdDelegate
//{
//    func createInterstitialAd()
//    {
//        interstitialAd = MAInterstitialAd(adUnitIdentifier: "83802ca889ba09e6")
//        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
//    }
//    
//    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()
//        SVProgressHUD.showInfo(withStatus: "Successfully published, waiting for review")
//        DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
//            SVProgressHUD.dismiss()
//        }
//
//    }
//    
//    func didFail(toDisplay ad: MAAd, withError error: MAError)
//    {
//        // Interstitial ad failed to display. We recommend loading the next ad
//        interstitialAd.load()
//    }
//    
//}
