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

import UIKit
///A面通用标签栏
class MPSideA_TabBarController: UITabBarController {
    //自定义tabBar
    private lazy var customTabBar:MPSideA_CustomTabBar = .init(frame: .init(x: 0, y: 0, width: screen_Width, height: 72*width))
    //底部音乐展示View（默认隐藏）
    private lazy var bottomView:MPSideA_BottomShowView = .instanceFromNib()
    //底部bottomShowView的展示状态
    private var isbottomShow:Bool = false{
        willSet{
            if isbottomShow != newValue {
                switch_bottomShow(newValue)
            }
            //填充音乐数据
            if newValue == true {
                guard let music = MPSideA_MediaCenterManager.shared.getMusic() else {
                    print("No Data Music")
                    return
                }
                bottomView.coverImageView.image = UIImage(data: music.cover)
                bottomView.titleLabel.text = music.title
                bottomView.subtitleLabel.text = setTimesToMinSeconds(music.duration)
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.isHidden = true
        self.setValue(customTabBar, forKey: "tabBar")
        //创建标签子控制器
        let homeVC = MPSideA_NavigationController(rootViewController: MPSideA_HomeViewController())
        let centerVC = MPSideA_NavigationController(rootViewController: MPSideA_CenterViewController())
        //添加子控制器
        viewControllers = [homeVC,centerVC]
        //禁止系统tabBaritem触发
        tabBar.items?.forEach({ item in
            item.isEnabled = false
        })
        tabBar.barTintColor = .clear
        UITabBar.appearance().backgroundColor = .clear
        tabBar.shadowImage = UIImage()
        // tabBar.shadowImage = image(UIColor.red) // 修改线条颜色
        tabBar.backgroundImage = UIImage()

        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)
        }
        //实现展示View的事件闭包
        //倒计时
        bottomView.modalTimerBlock = {
            [weak self] in
            self?.modalTimer()
        }
        //切换播放器状态
        bottomView.switchPlayerBlock = {
            [weak self] in
            self?.switchState()
        }
        //前往播放器
        bottomView.pushPlayerBlock = {
            [weak self] in
            self?.pushPlayer()
        }
        //在页面展示前，获取播放器是否存在历史播放（最后一次播放），并视情况展示View
        isbottomShow = MPSideA_MediaCenterManager.shared.getMusic() != nil
        //监听通知
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(switchAction(_:)), notificationName: .switch_tabBarItem)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(timesAction(_ :)), notificationName: .sideA_time_times)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(playMusicAction(_ :)), notificationName: .sideA_play_music)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(pauseMusicAction(_ :)), notificationName: .sideA_pause_music)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(resumeMusicAction(_ :)), notificationName: .sideA_resume_music)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(stopMusicAction(_ :)), notificationName: .sideA_stop_music)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(closeBottonViewAction(_ :)), notificationName: .sideA_close_show)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(displayBottomViewAction(_ :)), notificationName: .sideA_display_show)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(hiddenBottomViewAction(_ :)), notificationName: .sideA_hidden_show)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(renameMusicAction(_ :)), notificationName: .sideA_rename_music)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
    }
    deinit {
        //移除所有监听
        NotificationCenter.default.removeObserver(self)
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        //将展示View设置到最上层
        view.bringSubviewToFront(bottomView)
    }
    //底部BottomView的切换动画
    private func switch_bottomShow(_ state:Bool) {
        UIView.animate(withDuration: 0.3) {
            [weak self] in
            guard let self = self else { return }
            if state {
                //向上展示
                bottomView.transform = .init(translationX: 0, y: -139*width)
            }else {
                //向下隐藏
                bottomView.transform = .identity
            }
        }
    }
}
//MARK: - 事件处理
extension MPSideA_TabBarController: UIViewControllerTransitioningDelegate {
    //切换事件
    @objc private func switchAction(_ sender:Notification) {
        let tag = sender.object as! Int
        selectedIndex = tag
    }
    //弹出计时器
    private func modalTimer() {
        MPSideA_ModalType = .Timer
        let timerVC = MPSideA_CountTimerViewController()
        timerVC.transitioningDelegate = self
        timerVC.modalPresentationStyle = .custom
        present(timerVC, animated: true)
    }
    //切换播放器状态
    private func switchState() {
        guard let music = MPSideA_MediaCenterManager.shared.getMusic() else {
            //播放器未能持有音乐实体
            print("No Data Music")
            return
        }
        switch MPSideA_MediaCenterManager.shared.getPlayerState() {
        case .Null://启动播放
            MPSideA_MediaCenterManager.shared.playerStart(music, actionType: .Normal)
        case .Playing://暂停播放
            MPSideA_MediaCenterManager.shared.playerPause()
        case .Pause://继续播放
            MPSideA_MediaCenterManager.shared.playerResume()
        }
    }
    //前往播放器
    private func pushPlayer() {
        print("Go to player")
        //模态弹出
        let playerVC = MPSideA_PlayerViewController()
        present(playerVC, animated: true)
    }
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return MPSideA_PresentationController(presentedViewController: presented, presenting: presenting)
    }
}
//MARK: - 监听触发
extension MPSideA_TabBarController {
    //计时值变化事件
    @objc private func timesAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            //隐藏按钮，展示View
            bottomView.timerBtn.isHidden = true
            bottomView.timerView.isHidden = false
            let time = sender.object as! TimeInterval
            bottomView.timerLabel.text = setTimesToMinSeconds(time)
        }
    }

    //启动音乐播放器
    @objc private func playMusicAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            isbottomShow = true
            bottomView.stateBtn.isSelected = true
        }
    }
    //暂停音乐播放器
    @objc private func pauseMusicAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            bottomView.stateBtn.isSelected = false
        }
    }
    //继续音乐播放器
    @objc private func resumeMusicAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            bottomView.stateBtn.isSelected = true
        }
    }
    //终止音乐播放器
    @objc private func stopMusicAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            bottomView.stateBtn.isSelected = false
            bottomView.timerLabel.text = "Time"
            //展示按钮，隐藏View
            bottomView.timerBtn.isHidden = false
            bottomView.timerView.isHidden = true
        }
    }
    //播放音乐被删除
    @objc private func closeBottonViewAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            isbottomShow = false
        }
    }
    //展示音乐播放框(ishidden调整)
    @objc private func displayBottomViewAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            bottomView.isHidden = false
        }
    }
    //隐藏音乐播放框(ishidden调整)
    @objc private func hiddenBottomViewAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            bottomView.isHidden = true
        }
    }
    @objc private func renameMusicAction(_ sender:Notification) {
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else { return }
            isbottomShow = isbottomShow
        }
    }
}
