//
//  WA_NewHomeVC.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/28.
//

import UIKit
import AppLovinSDK
import FirebaseAnalytics
import Alamofire

class WA_NewHomeVC: WA_RootVC {
    
    @IBOutlet weak var tableView: UITableView!
    
    var isFirstLaunch: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNetwork()
        setTableView()
        // 创建 ExampleViewController 实例
        
        if let localIP = StartManager.shared.localIP {
            print("Accessed Local IP:---- \(localIP)")
        }
        // 添加 ExampleViewController 到当前视图控制器中
//        addChild(exampleViewController)
//        view.addSubview(exampleViewController.view)
//        exampleViewController.didMove(toParent: self)
        Analytics.logEvent("in_home", parameters: nil)
        
        
//        let livevc = WA_LIVEVC()
//        livevc.createInterstitialAd()
        
//        let vc = WA_4KVC()
//        vc.createInterstitialAd()
        
//        let rakvc = WA_RankingVC()
//        rakvc.createInterstitialAd()
//        
//        let vcd = WA_DetailsVC()
//        vcd.createInterstitialAd()
//
//        let vc
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.setPostStar()
        }
        
        let isFirstLaunch = UserDefaults.standard.bool(forKey: "isFirstLaunch")
        
        if !isFirstLaunch {
            // 第一次运行应用程序时执行的代码
            AccountManager.createDefaultAccountIfNeeded()
            
            // 设置 isFirstLaunch 标志为 true
            UserDefaults.standard.set(true, forKey: "isFirstLaunch")
        }else{
            self.isFirstLaunch = false
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            // 请求跟踪授权
            requestTrackingAuthorization { idfa in
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    StartManager.shared.idfaid = idfa
                    print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
                } else {
                    print("IDFA is not available or tracking authorization denied.")
                }
            }
        }

    }
    
    func setNetwork() {
        let url = "https://www.baidu.com/"
        
        AF.request(url).response { response in
            if let error = response.error {

            } else if response.data != nil {
              
            } else {
               
            }
        }
    }
    
    
    
    func setPostStar(){
        let url = "http://111.9.47.226:38080/top_selection/save_app_start_log"
        let parameters:[String : Any] = [
            "deviceId": StartManager.shared.devicID ?? "",
            "localIp": StartManager.shared.localIP ?? "",
            "remoteIp": StartManager.shared.publicIP ?? "",
            "linkId": "",
            "packageName": "com.wallpapaer.hd.live.app",
            "gaid": StartManager.shared.idfaid ?? "",
            "dataId": "",
        ]
        
        
        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 setTableView(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "WA_NewHometypeCell", bundle: nil), forCellReuseIdentifier: "WA_NewHometypeCell")
        tableView.register(UINib(nibName: "WA_NewHomeBannerCell", bundle: nil), forCellReuseIdentifier: "WA_NewHomeBannerCell")
        tableView.register(UINib(nibName: "WA_TodayCell", bundle: nil), forCellReuseIdentifier: "WA_TodayCell")
        tableView.register(UINib(nibName: "WA_MonRankngCell", bundle: nil), forCellReuseIdentifier: "WA_MonRankngCell")
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isHidden = true
        DispatchQueue.main.asyncAfter(deadline: .now() ) {
            // 请求跟踪授权
            requestTrackingAuthorization { idfa in
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    StartManager.shared.idfaid = idfa
                    print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
                } else {
                    print("IDFA is not available or tracking authorization denied.")
                }
            }
        }

    }
    

    
}
extension WA_NewHomeVC:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 1
        }else if section == 1{
            return 1
        }else if section == 2{
            return 1
        }else{
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "WA_NewHomeBannerCell", for: indexPath)as! WA_NewHomeBannerCell
            cell.blocklive = {
                let vc = WA_LIVEVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            cell.blockpopu = {
                let vc = WA_4KVC()
                vc.type = 3
                self.navigationController?.pushViewController(vc, animated: true)
            }
            cell.blocknew = {
                let vc = WA_4KVC()
                vc.type = 2
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
            return cell
        }else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "WA_NewHometypeCell", for: indexPath)as! WA_NewHometypeCell
            cell.liveBlock = {
                let vc = WA_LIVEVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            cell.jpgblock = { type in
                let vc = WA_4KVC()
                vc.type = type
                self.navigationController?.pushViewController(vc, animated: true)
                
            }
            return cell
        }else if indexPath.section == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "WA_TodayCell", for: indexPath)as! WA_TodayCell
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "WA_MonRankngCell", for: indexPath)as! WA_MonRankngCell
            return cell
        }
    }
    
    
}
extension UIApplication {
    class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return getTopViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController {
                return getTopViewController(base: selected)
            }
        }
        if let presented = base?.presentedViewController {
            return getTopViewController(base: presented)
        }
        return base
    }
}


