//
//  MPPositive_TabBarController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/19.
//

import UIKit
///b面tabBar控制器
class MPPositive_TabBarController: UITabBarController, UIViewControllerTransitioningDelegate, GADFullScreenContentDelegate {
    //自定义tabBar
    private lazy var customTabBar:MPPositive_CustomTabBar = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 72*width))
    private lazy var bottomView:MPPositive_BottomShowView = .init(frame: .init(x: 0, y: 0, width: 351, height: 82))
    //底部展示状态
    private var isbottomShow:Bool = false{
        willSet{
            if isbottomShow != newValue {
                switch_bottomShowAnimation(newValue)
            }
        }
    }
    //是否Push
    private var isPush:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setValue(customTabBar, forKey: "tabBar")
        //创建标签子控制器
        let homeVC = MPPositive_NavigationController(rootViewController: MPPositive_HomeViewController())
        let searchVC = MPPositive_NavigationController(rootViewController: MPPositive_SearchViewController())
        let libraryVC = MPPositive_NavigationController(rootViewController: MPPositive_LibraryViewController())
        viewControllers = [homeVC,searchVC,libraryVC]
        //禁止系统tabBaritem触发
        tabBar.items?.forEach({ item in
            item.isEnabled = false
        })
        tabBar.barTintColor = .clear
        UITabBar.appearance().backgroundColor = .clear
        tabBar.shadowImage = UIImage()
        tabBar.backgroundImage = UIImage()
        //添加底部播放View
        view.addSubview(bottomView)
        //将展示View设置在主窗口下方之外，避免用户察觉
        bottomView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(82*width)
            make.width.equalTo(351*width)
            make.height.equalTo(82*width)
        }
        bottomView.showListBlock = {
            [weak self] in
            if MP_PlayerManager.shared.loadPlayer != nil {
                MPPositive_ModalType = .PlayerList
                let listVC = MPPositive_PlayerListShowViewController()
                listVC.transitioningDelegate = self
                listVC.modalPresentationStyle = .custom
                self?.present(listVC, animated: true)
            }
        }
        bottomView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(playerClick(_ :))))
        addNotification()
    }
    //监听通知
    private func addNotification() {
        //监听标签切换
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(switchAction(_:)), notificationName: .switch_tabBarItem)
        //监听控制器弹出
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(pupPlayerAction), notificationName: .pup_player_vc)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(bottomAnimationAction(_:)), notificationName: .pup_bottom_show)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(bottomAnimationAction(_:)), notificationName: .player_delete_list)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(pushAction(_ :)), notificationName: .positive_nav_push)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(popAction(_ :)), notificationName: .positive_nav_pop)
    }
    deinit {
        //移除所有监听
        NotificationCenter.default.removeObserver(self)
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPPositive_PresentationController(presentedViewController: presented, presenting: presenting)
    }
    
}
//MARK: - 通知处理
extension MPPositive_TabBarController {
    //切换事件
    @objc private func switchAction(_ sender:Notification) {
        let tag = sender.object as! Int
        selectedIndex = tag
    }
    @objc private func playerClick(_ sender:UITapGestureRecognizer) {
        MP_AnalyticsManager.shared.song_clickAction("Player")
        pupPlayerAction()
    }
    //弹出player控制器
    @objc private func pupPlayerAction() {
        MP_AdMobManager.shared.showPlayInterstitialAdIfAvailable { [weak self] ad in
            guard let self = self else {return}
            //判断音乐播放器是否已经播放
            MP_AdMobManager.shared.isShowingPlayInterstitialAd = true
            //播放器还未播放，可以弹出广告
            MP_AdMobManager.shared.setInterstitialSwitch(true)
            ad.fullScreenContentDelegate = self
            ad.present(fromRootViewController: self)
        }
        //执行加载播放器页面
        DispatchQueue.main.async {
            [weak self] in
            let playerVC = MPPositive_PlayerViewController()
            playerVC.modalPresentationStyle = .fullScreen
            playerVC.recommendBlock = {
                let recommendVC = MPPositive_RecommendViewController(MP_PlayerManager.shared.loadPlayer?.currentVideo?.song.relatedID ?? "")
                self?.viewControllers![self?.selectedIndex ?? 0].children[0].navigationController?.pushViewController(recommendVC, animated: false)
            }
            playerVC.searchBlock = { (text) in
                let resultVC = MPPositive_SearchResultShowViewController(text, isShowAd: false)
                self?.viewControllers![self?.selectedIndex ?? 0].children[0].navigationController?.pushViewController(resultVC, animated: false)
            }
            self?.present(playerVC, animated: true)
        }
    }
    //切换底部音乐模块状态
    @objc private func bottomAnimationAction(_ sender:Notification) {
        isbottomShow = MP_PlayerManager.shared.loadPlayer != nil
    }
    //底部BottomView的切换动画
    private func switch_bottomShowAnimation(_ state:Bool) {
        UIView.animate(withDuration: 0.3) {
            [weak self] in
            guard let self = self else { return }
            if state {
                //向上展示
                bottomView.transform = .init(translationX: 0, y: isPush ? -82*width:-145*width)
            }else {
                //向下隐藏
                bottomView.transform = .identity
            }
        }
    }
    //页面push事件
    @objc private func pushAction(_ sender:Notification) {
        isPush = true
        //检索页面状态
        if isbottomShow == true {
            //将bottomView，向下移动83
            UIView.animate(withDuration: 0.3) {
                [weak self] in
                guard let self = self else { return }
                bottomView.transform = .init(translationX: 0, y: -82*width)
            }
        }
    }
    @objc private func popAction(_ sender:Notification) {
        isPush = false
        //检索页面状态
        if isbottomShow == true {
            //将bottomView，向上移动83
            UIView.animate(withDuration: 0.3) {
                [weak self] in
                guard let self = self else { return }
                bottomView.transform = .init(translationX: 0, y: -145*width)
            }
        }
    }
    //MARK: - 覆盖型广告代理 GADFullScreenContentDelegate
    //覆盖型广告将要将要展示
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
//        UIApplication.shared.isStatusBarHidden = true
        if ad === MP_AdMobManager.shared.playInterstitialAd {//播放插页广告
            print("当前展示的广告是播放插页广告，广告ID--\(MP_AdMobManager.shared.playInterstitialAd?.adUnitID ?? "")")
            MP_AdMobManager.shared.playInterstitialAd?.paidEventHandler = { adValue in
                if let response =  MP_AdMobManager.shared.playInterstitialAd?.responseInfo {
                    MP_AnalyticsManager.shared.play_ads_showSuccessAction(response, adValue: adValue)
                }
            }
        }
    }
    //覆盖型广告已经消失
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
//        UIApplication.shared.isStatusBarHidden = false
        MP_AdMobManager.shared.interstitialDate = Date()
        if ad === MP_AdMobManager.shared.playInterstitialAd {//播放插页广告
            let UUID = MP_AdMobManager.shared.playInterstitialAd?.adUnitID ?? ""
            print("当前消失的广告是播放插页广告，广告ID--\(UUID)")
            //执行播放插页广告完成事件包
            if MP_AdMobManager.shared.completePlayInterstitialAdBlock != nil {
                MP_AdMobManager.shared.completePlayInterstitialAdBlock!()
            }
            //执行加载播放器页面
            DispatchQueue.main.async {
                [weak self] in
                let playerVC = MPPositive_PlayerViewController()
                playerVC.modalPresentationStyle = .fullScreen
                playerVC.recommendBlock = {
                    let recommendVC = MPPositive_RecommendViewController(MP_PlayerManager.shared.loadPlayer.currentVideo.song.relatedID)
                    self?.viewControllers![self?.selectedIndex ?? 0].children[0].navigationController?.pushViewController(recommendVC, animated: false)
                }
                self?.present(playerVC, animated: true)
            }
        }

    }
    //覆盖型广告加载出错
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
//        UIApplication.shared.isStatusBarHidden = false
        MP_AdMobManager.shared.interstitialDate = Date()
        if ad === MP_AdMobManager.shared.playInterstitialAd {//播放插页广告
            let UUID = MP_AdMobManager.shared.playInterstitialAd?.adUnitID ?? ""
            print("播放插页广告展示时出错，广告ID--\(UUID)，具体错误原因:\(error.localizedDescription)")
            MP_AnalyticsManager.shared.play_ads_showFailureAction(error.localizedDescription)
            //执行播放插页广告完成事件包
            if MP_AdMobManager.shared.completePlayInterstitialAdBlock != nil {
                MP_AdMobManager.shared.completePlayInterstitialAdBlock!()
            }
//            //执行加载播放器页面
//            DispatchQueue.main.async {
//                [weak self] in
//                let playerVC = MPPositive_PlayerViewController()
//                playerVC.modalPresentationStyle = .fullScreen
//                playerVC.recommendBlock = {
//                    let recommendVC = MPPositive_RecommendViewController(MP_PlayerManager.shared.loadPlayer.currentVideo.song.relatedID)
//                    self?.viewControllers![self?.selectedIndex ?? 0].children[0].navigationController?.pushViewController(recommendVC, animated: false)
//                }
//                self?.present(playerVC, animated: true)
//            }
        }

    }
}
