//
//  WA_RKDetailsVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/17.
//

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

class WA_RKDetailsVC: WA_RootVC,UITextFieldDelegate {
    @IBOutlet weak var tableView: UITableView!
    var model: WA_RakModel?
    var dataItems: [DataModel] = []
    
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    
    @IBOutlet weak var plBtn: UIButton!
    var textField: UITextField!
    
    let activityView = UIActivityIndicatorView()
    
    
    var remoteConfig: RemoteConfig!
    
    var isadshow:Bool = false
    
    var bidToken:String?
    var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        plBtn.layer.cornerRadius = 10
        setTableViewCell()
        if let data = model?.data {
            dataItems = data
        }
        
        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)
        
        // 创建 UITextField
        textField = UITextField()
        textField.backgroundColor = .lightGray
        textField.isHidden = true
        textField.delegate = self
        textField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(textField)
        
        // 添加约束
        NSLayoutConstraint.activate([
//            plBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor),
//            plBtn.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            
            textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            textField.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            textField.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            textField.heightAnchor.constraint(equalToConstant: 40)
        ])
        
        // 注册键盘弹出和隐藏的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 初始化 Remote Config
        // 初始化 Remote Config
        remoteConfig = RemoteConfig.remoteConfig()
        
        
        
        // 设置最小获取间隔（开发期间可以设置较小的值）
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        // Fetch 配置值
        remoteConfig.setDefaults(fromPlist: "isopen")
        // Fetch 配置值
       
        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()
            }
        }
    }
    
    ///是否有广告
    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 setTableViewCell(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "WA_RKPLCell", bundle: nil), forCellReuseIdentifier: "WA_RKPLCell")
        tableView.register(UINib(nibName: "WA_RKTopCell", bundle: nil), forCellReuseIdentifier: "WA_RKTopCell")
        
    }
    
    @IBAction func backbtn(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func plBtn(_ sender: Any) {
//        if self.isadshow == true{
//            if interstitialAd.isReady {
//                interstitialAd.show()
//                Analytics.logEvent("touchrelease_load_success", parameters: nil)
//            }else{
//                if isLoggedIn(){
//                    self.plBtn.isHidden = true
//                    textField.isHidden = false
//                    textField.becomeFirstResponder()
//
//                }else{
//                    let vc = WA_LoginVC()
//                    vc.type = 1
//                    self.navigationController?.pushViewController(vc, animated: true)
//                    
//                }
//            }
//        }else{
//            if isLoggedIn(){
//                self.plBtn.isHidden = true
//                textField.isHidden = false
//                textField.becomeFirstResponder()
//
//            }else{
//                let vc = WA_LoginVC()
//                vc.type = 1
//                self.navigationController?.pushViewController(vc, animated: true)
//                
//            }
//        }
        let issureready = newInterstitialAdManager?.isAdReady()
        if  self.isadshow == true{
            if ((issureready) != nil) {
                newInterstitialAdManager?.show(from: self)
            }else{
                if isLoggedIn(){
                    self.plBtn.isHidden = true
                    textField.isHidden = false
                    textField.becomeFirstResponder()

                }else{
                    let vc = WA_LoginVC()
                    vc.type = 1
                    self.navigationController?.pushViewController(vc, animated: true)
                    
                }

            }
            
        }else{
            if isLoggedIn(){
                self.plBtn.isHidden = true
                textField.isHidden = false
                textField.becomeFirstResponder()

            }else{
                let vc = WA_LoginVC()
                vc.type = 1
                self.navigationController?.pushViewController(vc, animated: true)
                
            }

        }


    }
    
    //     键盘弹出时调用
    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
            // 计算键盘高度
            let keyboardHeight = keyboardFrame.height
                // 调整 textField 的位置
                self.textField.frame.origin.y = self.view.frame.height - keyboardHeight - self.textField.frame.height

//
        }
    }
    
    // 键盘隐藏时调用
    @objc func keyboardWillHide(notification: NSNotification) {
        textField.isHidden = true
        self.plBtn.isHidden = false
        textField.text = ""
    }
    
    // 点击确认按钮时调用
     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         // 在这里实现用户点击确认按钮后的逻辑操作
         print("The user clicked the confirm button")
         if textField.text?.count == 0{
             SVProgressHUD.showInfo(withStatus: "Please enter the comment content")
             DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                 SVProgressHUD.dismiss()
             }

         }else{
             textField.resignFirstResponder() // 收起键盘
             self.plBtn.isHidden = false
             textField.text = ""
             DispatchQueue.main.asyncAfter(deadline: .now()){
                 self.activityView.startAnimating()
                 
                 DispatchQueue.global().asyncAfter(deadline: .now() + 1.5){
                     DispatchQueue.main.asyncAfter(deadline: .now()){
                         self.activityView.stopAnimating()
                         SVProgressHUD.showInfo(withStatus: "Successfully sent comment, reviewing content")
                         DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                             SVProgressHUD.dismiss()
                         }
                     }
                 }
             }
         }
   
         return true
     }
    
}



extension WA_RKDetailsVC:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else {
            // 返回数据数组的数量
            return dataItems.count
        }
        
    }
    
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "WA_RKTopCell", for: indexPath)as!WA_RKTopCell
            if let imageURL = URL(string: model!.img ?? "") {
                cell.countImagV.sd_setImage(with: imageURL)
            }
            if let headURL = URL(string: model!.head ?? "") {
                cell.headImageV.sd_setImage(with: headURL)
            }
            cell.nameLabel.text = model?.name
            cell.titleLabel.text = model?.content
            cell.tlcoutlabel.text = "\(dataItems.count)Participation in topics"
            
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:)))
             cell.countImagV.isUserInteractionEnabled = true
             cell.countImagV.addGestureRecognizer(tapGesture)
            
            
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "WA_RKPLCell", for: indexPath)as!WA_RKPLCell
            cell.model = dataItems[indexPath.row]
            cell.reportBlcok = {
                // 创建一个 UIAlertController
                let alertController = UIAlertController(title: "report", message: "Report the content of this comment?", preferredStyle: .alert)
                
                // 添加一个取消按钮
                alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
                
                // 添加一个确定按钮
                alertController.addAction(UIAlertAction(title: "report", style: .default, handler: { action in
                    // 点击确定按钮后执行的操作
                    //                    print("点击了确定按钮")
                    DispatchQueue.main.asyncAfter(deadline: .now()){
                        self.activityView.startAnimating()
                        
                        DispatchQueue.global().asyncAfter(deadline: .now() + 1.5){
                            DispatchQueue.main.asyncAfter(deadline: .now()){
                                self.activityView.stopAnimating()
                                SVProgressHUD.showInfo(withStatus: "Successfully submitted. Thank you for your feedback. We will review this comment again in the future")
                                DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                                    SVProgressHUD.dismiss()
                                }
                            }
                            
                            
                        }
                    }
                }))
                
                // 在当前视图控制器中 present 显示提示框
                self.present(alertController, animated: true, completion: nil)
            }
            
            cell.blackBLcok = {
                // 创建一个 UIAlertController
                let alertController = UIAlertController(title: "Block", message: "Blacklisting comment content?", preferredStyle: .alert)
                
                // 添加一个取消按钮
                alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
                
                // 添加一个确定按钮
                alertController.addAction(UIAlertAction(title: "Block", style: .default, handler: { action in
                    // 点击确定按钮后执行的操作
                    //                    print("点击了确定按钮")
                    DispatchQueue.main.asyncAfter(deadline: .now()){
                        self.activityView.startAnimating()
                        DispatchQueue.global().asyncAfter(deadline: .now() + 1.5){
                            DispatchQueue.main.asyncAfter(deadline: .now()){
                                self.activityView.stopAnimating()
                                let selectedModel = self.dataItems[indexPath.row]
                                self.dataItems.remove(at: indexPath.row)
                                self.tableView.deleteRows(at: [indexPath], with: .fade)
                                SVProgressHUD.showInfo(withStatus: "Successfully submitted. Thank you for your feedback. We will review this comment again in the future")
                                self.tableView.reloadData()
                                DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                                    SVProgressHUD.dismiss()
                                    
                                }
                                
                            }
                        }
                    }
                }))
                
                // 在当前视图控制器中 present 显示提示框
                self.present(alertController, animated: true, completion: nil)
            }
            return cell
        }
        
        
    }
    @objc func imageTapped(_ sender: UITapGestureRecognizer) {
           if let imageView = sender.view as? UIImageView, let image = imageView.image {
               // 处理点击图片后的逻辑，例如展示全屏
               let fullScreenImageView = UIImageView(image: image)
               fullScreenImageView.frame = UIScreen.main.bounds
               fullScreenImageView.backgroundColor = .black
               fullScreenImageView.contentMode = .scaleAspectFit
               fullScreenImageView.isUserInteractionEnabled = true
               
               let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage(_:)))
               fullScreenImageView.addGestureRecognizer(tap)
               
               if let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
                   keyWindow.addSubview(fullScreenImageView)
               }
           }
       }
       
       @objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
           sender.view?.removeFromSuperview()
       }
    
}
extension WA_RKDetailsVC: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("广告被关闭")
                if isLoggedIn(){
                    self.plBtn.isHidden = true
                    textField.isHidden = false
                    textField.becomeFirstResponder()
        
                }else{
                    let vc = WA_LoginVC()
                    vc.type = 1
                    self.navigationController?.pushViewController(vc, animated: true)
        
                }
    }
}
//extension WA_RKDetailsVC: 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()
//        
//
//        if isLoggedIn(){
//            self.plBtn.isHidden = true
//            textField.isHidden = false
//            textField.becomeFirstResponder()
//
//        }else{
//            let vc = WA_LoginVC()
//            vc.type = 1
//            self.navigationController?.pushViewController(vc, animated: true)
//            
//        }   
//    }
//    
//    func didFail(toDisplay ad: MAAd, withError error: MAError)
//    {
//        // Interstitial ad failed to display. We recommend loading the next ad
//        interstitialAd.load()
//    }
//}
