//
//  TSLaunchVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import Alamofire
import UIKit

class TSLaunchVC: UIViewController {
    var dismissHandler: (() -> Void)?

    // 定时器
    private var timer: DispatchSourceTimer?
    // 闪屏页剩余显示时长
    #if DEBUG
    private var remindTimeInterval: TimeInterval = 1.5
    #else
        private var remindTimeInterval: TimeInterval = 3.0
    #endif

    private var isStop: Bool = false

    var showingAdViewController: Bool {
        return presentedViewController != nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupLaunchScreenView()
        startTimer()
        addNotifiy()
    }

    func addNotifiy() {
        TSNetworkShared.startListenNetStatus { status, manager in
            switch status {
            case .reachable:
                kPurchaseToolShared.luanchuPrchase()
//                AppDelegate.requestAdTrack()
                manager?.stopListening()
//                self.initAdMob()
                break
            default:
//                AppDelegate.requestAdTrack()
                kPurchaseToolShared.luanchuPrchase()
//                self.initAdMob()
                break
            }
        }
    }

    func initAdMob() {
//        GADMobileAds.sharedInstance().start { status in
//            print("启动状态 == status === \(status.adapterStatusesByClassName)")
//        }
    }

    func enterApp() {
        
        showEveryDayPopPurchase()
        
//        DispatchQueue.main.async {
//            self.dismissHandler?()
//        }
    }


    
    private func startTimer() {
        if timer == nil {
            timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
            timer?.schedule(deadline: .now(), repeating: .milliseconds(200))
            timer?.setEventHandler(handler: { [weak self] in
                // App活跃时，计时有效；如网络授权弹窗唤起时，计时失效
                DispatchQueue.main.async {
                    guard let self = self,
                          UIApplication.shared.applicationState == .active,
                          !self.showingAdViewController else {
                        return
                    }
                    self.remindTimeInterval -= 0.2
                    print("倒计时：\(self.remindTimeInterval)")
                    if self.remindTimeInterval <= 0 {
                        self.timer?.cancel()
                        self.enterApp()
                    }
                }

            })
            timer?.resume()
        }
    }
    
    

    private func setupLaunchScreenView() {
        // 获取 LaunchScreen.storyboard 的视图控制器
        let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
        guard let launchVC = storyboard.instantiateInitialViewController() else {
            debugPrint("无法加载 LaunchScreen 的初始视图控制器")
            return
        }

        // 获取 LaunchScreen 的视图
        guard let launchView = launchVC.view else {
            debugPrint("无法获取 LaunchScreen 的视图")
            return
        }

        // 设置 launchView 的 frame 为当前视图的 bounds
        launchView.frame = UIScreen.main.bounds

        // 将 launchView 添加到 TSLaunchVC 的视图中
        view.addSubview(launchView)
    }
}


extension TSLaunchVC {
    
    func showEveryDayPopPurchase() {
        
        if UserDefaults.standard.string(forKey: "isFirstInstallApp") == nil || kPurchaseToolShared.isVip {
            //启动页->引导图->会员购买
            dismissHandler?()
            return
        }
        
        //启动页->会员购买
        // 1. 获取当前日期
        let currentDate = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyyMMdd"
        let currentDateString = dateFormatter.string(from: currentDate)
        
        // 2. 获取上次弹窗的日期
        let userDefaults = UserDefaults.standard
        let lastGreetingDateString = userDefaults.string(forKey: "kEveryDayPopPurchase")
        
        // 3. 检查是否需要显示弹窗 "20250319"
        if lastGreetingDateString != currentDateString {
            
            // 4. 弹窗付费引导
            let vc = TSPurchaseVC()
            vc.closePageBlock = { [weak self]  in
                guard let self = self else { return }
                dismissHandler?()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        
            // 5. 更新上次弹窗的日期
            userDefaults.set(currentDateString, forKey: "kEveryDayPopPurchase")
            
//            userDefaults.set(String(Int(currentDateString)!+1), forKey: "kEveryDayPopPurchase")测试用的
        }else{
            dismissHandler?()
        }
    }
}
