//
//  LunchViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/3/27.
//

import UIKit
import GoogleMobileAds
///启动页
class MP_LunchViewController: UIViewController, GADFullScreenContentDelegate {
    @IBOutlet weak var progressView: MP_Lunch_ProgressView!{
        didSet{
            progressView.layer.masksToBounds = true
        }
    }
    //帧计时器
    private var timer:CADisplayLink!
    //最大计时值
    private lazy var maxTimes:TimeInterval = 10
    //当前计时值
    private lazy var currentTimes:TimeInterval = 0
    //进度比值
    private lazy var addValue:TimeInterval = 0.1
    //计时器结束事件
    private var completionBlock:(() -> Void)?
    //是否执行过A/B面检测
    private var isBeen:Bool = false
    //广告事件传递闭包
    private var adShowBlock:(() -> Void)?
    //切换事件传递闭包
    private var switchBlock:(() -> Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            //printCallStack()
            // 请求跟踪授权
            requestTrackingAuthorization { idfa in
            }
        }
        view.backgroundColor = .init(hex: "#000000")
        timer = CADisplayLink(target: self, selector: #selector(timerActionClick(_ :)))
        //一秒执行多少次
        timer.preferredFramesPerSecond = 10
        //开辟线程
        timer.add(to: RunLoop.current, forMode: .common)
        //启动计时器
        timer.isPaused = false        
        switchBlock = {
            [weak self] in
            guard let self = self else {return}
            if completionBlock != nil {
                completionBlock!()
            }else {
                //完成闭包没有配置完成，直接前往A面
                print("ALog")
                //打开A面
                DispatchQueue.main.async {
                    [weak self] in
                    guard let self = self else {return}
                    //printCallStack()
                    //停止计时器
                    timer.isPaused = true
                    MP_AnalyticsManager.shared.jump_eventAction("jump to A", reason: "User has not determined network permissions")
                    //加载完毕，判断并跳转
                    accessAppdelegate.switch_aSide()
                }
            }
        }
        //检查并清理多余缓存文件
        MP_CacheAndArchiverManager.shared.zhoujunfeng_checkAndCleanCacheFolder()
    }
    deinit {
        timer.isPaused = true
        //销毁计时器
        timer.invalidate()
        timer = nil
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    //计时器执行事件
    @objc fileprivate func timerActionClick(_ link:CADisplayLink) {
        if maxTimes > currentTimes {
            //未加载完
            currentTimes += addValue
            let value = (currentTimes/maxTimes).isNaN ? 0:(currentTimes/maxTimes)
            DispatchQueue.main.async {
                
                [weak self] in
                guard let self = self else {return}
                //设置进度条
                progressView.setProgress(value)
            }
            //执行A/B面检测
            if isBeen == false {
                //修改值避免一直检测
                MP_AnalyticsManager.shared.launch_pvAction()
                isBeen = true
                switchAOrBAction()
            }
        }else {
            //停止计时器
            timer.isPaused = true
            MP_AnalyticsManager.shared.launch_progress_endAction()
            //判断是否具备广告
            if adShowBlock != nil {
                adShowBlock!()
            }else if switchBlock != nil {
                switchBlock!()
            }
        }
    }
    //a/b面开关判断
    private func switchAOrBAction() {
        //首先检测之前是否进入过B面
        guard UserDefaults.standard.bool(forKey: "MP_Into_B") != true else {
            //更新开关以及响应的数据
            MP_AnalyticsManager.shared.getOpenStatus { [weak self] open in
                if open {
                    print("允许进入B面")
                }else {
                    print("不允许进入B面，但是之前进入过，所以能进入B面")
                }
                //更新地区信息
                MP_NetWorkManager.shared.requestIPInfo { statu in
                    //获取B面首页数据
                    MPPositive_BrowseLoadViewModel.shared.reloadBrowseLists()
                }
            }
            //拉取广告
            MP_AdMobManager.shared.loadMoreAdMobs()
            MP_AdMobManager.shared.showOpenAdIfAvailable(.ICE) { [weak self] (ad, isOpen) in
                guard let self = self else {return}
                //将广告事件传递闭包赋值
                adShowBlock = {
                    self.adPresent(ad: ad, isOpen: isOpen)
                }
            }
            //进入过B面
            self.completionBlock = {
                //允许进入b面
                print("BLog")
                //保存进入B面的记录，下次加载直接进入B面
                UserDefaults.standard.set(true, forKey: "MP_Into_B")
                DispatchQueue.main.async {
                    [weak self] in
                    //printCallStack()
                    guard let self = self else {return}
                    //停止计时器
                    timer.isPaused = true
                    MP_AnalyticsManager.shared.jump_eventAction("jump to B", reason: "Side B has been shown")
                    //加载完毕，判断并跳转
                    accessAppdelegate.switch_positive()
                }
            }
            return
        }
        //添加队列任务
        MP_NetWorkManager.shared.performTaskNetWrokAvailable {
            [weak self] in
            guard let self = self else {return}
            //进行开关检测
            MP_AnalyticsManager.shared.getOpenStatus { [weak self] open in
                guard let self = self else {return}
                if open {
                    //开关检测为通过，以下发ID刷新广告
                    MP_AdMobManager.shared.loadMoreAdMobs()
                    MP_AdMobManager.shared.showOpenAdIfAvailable(.ICE) { [weak self] (ad,isOpen) in
                        guard let self = self else {return}
                        //将广告事件传递闭包赋值
                        adShowBlock = {
                            self.adPresent(ad: ad, isOpen: isOpen)
                        }
                    }
                    //根据ip值确定进入那个页面
                    MP_NetWorkManager.shared.requestIPInfo { statu in
                        if statu == true {
                            //允许进入b面
                            //获取B面首页数据
                            MPPositive_BrowseLoadViewModel.shared.reloadBrowseLists()
                            print("BLog")
                            //保存进入B面的记录，下次加载直接进入B面
                            UserDefaults.standard.set(true, forKey: "MP_Into_B")
                            //判断当前时间节点是否已经超时
                            if self.maxTimes > self.currentTimes {
                                //未超时，完成包处理
                                self.completionBlock = {
                                    DispatchQueue.main.async {
                                        [weak self] in
                                        //printCallStack()
                                        guard let self = self else {return}
                                        //停止计时器
                                        timer.isPaused = true
                                        MP_AnalyticsManager.shared.jump_eventAction("jump to B", reason: "Switch test passed, IP test passed")
                                        //加载完毕，判断并跳转
                                        accessAppdelegate.switch_positive()
                                    }
                                }
                            }else {
                                //已超时，直接跳转（可能出现从A到B的情况）
                                DispatchQueue.main.async {
                                    [weak self] in
                                    //printCallStack()
                                    guard let self = self else {return}
                                    //停止计时器
                                    timer.isPaused = true
                                    if accessAppdelegate.showStatus == false {
                                        //当前已处于A面
                                        MP_AnalyticsManager.shared.jump_eventAction("A jump to B", reason: "Switch test passed, IP test passed, User delays in processing network permissions")
                                    }else {
                                        //当前还未跳转
                                        MP_AnalyticsManager.shared.jump_eventAction("jump to B", reason: "Switch test passed, IP test passed")
                                    }
                                    //加载完毕，判断并跳转
                                    accessAppdelegate.switch_positive()
                                }
                            }
                        }else {
                            //地区限制不允许进入B面
                            print("ALog")
                            //打开A面
                            if self.maxTimes > self.currentTimes {
                                //未超时，完成包处理
                                self.completionBlock = {
                                    DispatchQueue.main.async {
                                        [weak self] in
                                        //printCallStack()
                                        guard let self = self else {return}
                                        //停止计时器
                                        timer.isPaused = true
                                        MP_AnalyticsManager.shared.jump_eventAction("jump to A", reason: "Switch test passed, IP detection failed")
                                        //加载完毕，判断并跳转
                                        accessAppdelegate.switch_aSide()
                                    }
                                }
                            }else {
                                //已超时，直接跳转
                                DispatchQueue.main.async {
                                    [weak self] in
                                    //printCallStack()
                                    guard let self = self else {return}
                                    //停止计时器
                                    timer.isPaused = true
                                    MP_AnalyticsManager.shared.jump_eventAction("jump to A", reason: "Switch test passed, IP detection failed")
                                    //加载完毕，判断并跳转
                                    accessAppdelegate.switch_aSide()
                                }
                            }
                        }
                    }
                }else {
                    //开关检测未通过，以默认ID刷新广告
                    MP_AdMobManager.shared.loadMoreAdMobs()
                    MP_AdMobManager.shared.showOpenAdIfAvailable(.ICE) { [weak self] (ad,isOpen) in
                        guard let self = self else {return}
                        //将广告事件传递闭包赋值
                        adShowBlock = {
                            self.adPresent(ad: ad, isOpen: isOpen)
                        }
                    }
                    print("ALog")
                    //打开A面
                    if self.maxTimes > self.currentTimes {
                        self.completionBlock = {
                            DispatchQueue.main.async {
                                [weak self] in
                                //printCallStack()
                                guard let self = self else {return}
                                //停止计时器
                                timer.isPaused = true
                                MP_AnalyticsManager.shared.jump_eventAction("jump to A", reason: "Switch test failed")
                                //加载完毕，判断并跳转
                                accessAppdelegate.switch_aSide()
                            }
                        }
                    }else {
                        DispatchQueue.main.async {
                            [weak self] in
                            //printCallStack()
                            guard let self = self else {return}
                            //停止计时器
                            timer.isPaused = true
                            MP_AnalyticsManager.shared.jump_eventAction("jump to A", reason: "Switch test failed")
                            //加载完毕，判断并跳转
                            accessAppdelegate.switch_aSide()
                        }
                    }
                }
            }
        }
    }
    //广告弹出
    private func adPresent(ad: GADFullScreenPresentingAd, isOpen:Bool) {
        DispatchQueue.main.async {
            //printCallStack()
            //修改插页总开关状态
            MP_AdMobManager.shared.setInterstitialSwitch(true)
            MP_AdMobManager.shared.isShowingOpenAd = true
            if isOpen {
                let new = ad as? GADAppOpenAd
                //覆盖并实现代理
                new?.fullScreenContentDelegate = self
                do{
                    try new?.canPresent(fromRootViewController: self)
                    new?.present(fromRootViewController: self)
                }catch{
                    print("开屏广告展示失败，失败原因:\(error)")
                    if MP_AdMobManager.shared.completeOpenAdBlock != nil {
                        MP_AdMobManager.shared.completeOpenAdBlock!()
                    }

                }
            }else {
                let new = ad as? GADInterstitialAd
                //覆盖并实现代理
                new?.fullScreenContentDelegate = self
                do{
                    try new?.canPresent(fromRootViewController: self)
                    new?.present(fromRootViewController: self)
                }catch{
                    print("开屏广告展示失败，失败原因:\(error)")
                    if MP_AdMobManager.shared.completeOpenAdBlock != nil {
                        MP_AdMobManager.shared.completeOpenAdBlock!()
                    }

                }
            }
        }
    }
    //MARK: - 覆盖型广告代理 GADFullScreenContentDelegate
    //覆盖型广告将要将要展示
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        if ad === MP_AdMobManager.shared.appOpenAd || ad === MP_AdMobManager.shared.appInterstitialAd {
            print("当前展示的广告是开屏广告，广告ID--\(MP_AdMobManager.shared.appOpenAd != nil ? (MP_AdMobManager.shared.appOpenAd?.adUnitID ?? ""):(MP_AdMobManager.shared.appInterstitialAd?.adUnitID ?? ""))")
            if let openAd = MP_AdMobManager.shared.appOpenAd {
                print("当前展示的广告是开屏广告，广告ID--\(openAd.adUnitID)")
                //上传广告收益
                openAd.paidEventHandler = { adValue in
                    MP_AnalyticsManager.shared.cold_ads_showSuccessAction(openAd.responseInfo, adValue: adValue)
                }
            }else if let openAd = MP_AdMobManager.shared.appInterstitialAd {
                print("当前展示的广告是开屏广告，广告ID--\(openAd.adUnitID)")
                //上传广告收益
                openAd.paidEventHandler = { adValue in
                    MP_AnalyticsManager.shared.cold_ads_showSuccessAction(openAd.responseInfo, adValue: adValue)
                }
            }
        }
    }
    //覆盖型广告已经消失
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {

        //当前启动页，展示广告一定是开屏广告
        if switchBlock != nil {
            switchBlock!()
        }
        if MP_AdMobManager.shared.completeOpenAdBlock != nil {
            MP_AdMobManager.shared.completeOpenAdBlock!()
        }
    }
    //覆盖型广告加载出错
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {

        MP_AnalyticsManager.shared.cold_ads_showFailureAction(error.localizedDescription)
        //当前启动页，展示广告一定是开屏广告
        if switchBlock != nil {
            switchBlock!()
        }
        if MP_AdMobManager.shared.completeOpenAdBlock != nil {
            MP_AdMobManager.shared.completeOpenAdBlock!()
        }
    }
}
