//
//  YL_PlayVC.swift
//  playbtest
//
//  Created by 忆海16 on 2024/11/5.
//

import UIKit
import AnyThinkInterstitial
class YL_PlayVC: UIViewController {

    @IBOutlet weak var textSDKView: UITextView!
    @IBOutlet weak var bundleIdLab: UILabel!
    @IBOutlet weak var deviceIdLab: UILabel!
    @IBOutlet weak var ipLab: UILabel!
    @IBOutlet weak var idfaLab: UILabel!
    @IBOutlet weak var ad1Lab: UILabel!
    @IBOutlet weak var ad2Lab: UILabel!
    @IBOutlet weak var ad3Lab: UILabel!
    
    private var observation: NSKeyValueObservation?
    
    private var observationis: NSKeyValueObservation?
    
    var openADTimer:Timer?
    let kOpenADPerSec: CGFloat = 0.1 // 假设的秒数
    let kOpenAdCTimeLength: CGFloat = 30 // 假设的超时时长
    
    static var totalTimeC: CGFloat = 0.0
    var firstShow = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        BbbAdManager.shared.loadAd(view:self)
        let bundleId = Bundle.main.bundleIdentifier ?? ""
        bundleIdLab.text = "Name:\(bundleId)"
        let deviceId = BbbAdManager.config.adbrush_deviceid ?? ""
        deviceIdLab.text = "DeviceID:\(deviceId)"
        let locIp = BbbAdManager.config.adbrush_localip ?? ""
        let remoteIp = BbbAdManager.config.remoteIp
        ipLab.text = "LocIP:\(locIp),RemoteIp:\(remoteIp)"
        
        if #available(iOS 14, *) {
            IDFA.shared.checkATT { idfa in
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    self.idfaLab.text =  "IDFA:\(idfa)"
                } else {
                    print("无法获取 IDFA")
                }
            }
        } else {
            IDFA.shared.getIDFAForOlderVersions { idfa in
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    self.idfaLab.text =  "IDFA:\(idfa)"
                } else {
                    print("无法获取 IDFA")
                }
            }
        }
      
        BbbAdManager.shared.start()

     
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if (!firstShow) {
            return
        }
        firstShow = false
        
        ad1Lab.text = BbbAdManager.config.adids[0]
        ad2Lab.text = BbbAdManager.config.adids[1]
        ad3Lab.text = BbbAdManager.config.adids[2]

        
        self.navigationController?.navigationBar.isHidden = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(addTextToTextView), name: NSNotification.Name("adinfo"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(adStatusChange), name: NSNotification.Name("adStatus"), object: nil)
         
        NotificationCenter.default.post(name: NSNotification.Name("adinfo"), object: nil, userInfo: ["text": "adbrush_base_url：\(BbbAdManager.config.adbrush_base_url)，adbrush_deviceid:\(String(describing: BbbAdManager.config.adbrush_deviceid))，adbrush_localip:\(String(describing: BbbAdManager.config.adbrush_localip))，adbrush_local_url:\(BbbAdManager.config.adbrush_local_url)，adbrush_ecpm:\(BbbAdManager.config.adbrush_ecpm)"])
    }
    
    @objc func addTextToTextView(notification: Notification) {
        if let newText = notification.userInfo?["text"] as? String {
            // 正确的方式
            DispatchQueue.global().async {
                // 后台线程处理数据

                
                DispatchQueue.main.async {
                    // 主线程更新UI
                    self.textSDKView.text.append("\(newText)\n\n")
                }
            }
           
        }
    }
    
    

    
    
    
    // 向文本末尾追加 100 行空白行
    func appendExtraLines1() {
        let extraLines = String(repeating: "\n", count: 100)
        let currentText = textSDKView.text ?? ""
        
        // 检查末尾是否已经有额外行，避免重复追加
        if !currentText.hasSuffix(extraLines) {
            textSDKView.text = currentText.trimmingCharacters(in: .whitespacesAndNewlines) + extraLines
        }
    }
    
    

    
    

    @objc func adStatusChange(notification: Notification) {
        if let newText = notification.userInfo?["text"] as? String, let id = notification.userInfo?["id"] as? String {
            var lab  = ad1Lab
            if id == BbbAdManager.config.adids[1] {
                lab = ad2Lab
            } else if id == BbbAdManager.config.adids[2] {
                lab = ad3Lab
            }
            DispatchQueue.global().async {
                // 后台线程处理数据

                DispatchQueue.main.async {
                    // 主线程更新UI
                    lab?.text = "\(id):\(newText)"                }
            }
           
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension Notification.Name {
    static let adStatusChanged = Notification.Name("adStatusChanged")
    
}
