//
//  TableViewController.swift
//  Tabbar
//
//  Created by lym on 2020/12/31.
//

import Alamofire
import UIKit
import Combine
class TabBarController: UITabBarController {
    private var customTabBar = TabBar()
    
    private var cancellables = Set<AnyCancellable>()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .c.cbd
        configViewControllers()
        setupEvent()
    }

    private func setupEvent() {


        NotificationCenter.default.addObserver(self, selector: #selector(notiPresentSignInVc), name: AppNotificationName.presentSignInVc.notificationName, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(unreadChanged), name: AppNotificationName.unreadCountChanged.notificationName, object: nil)
        
        IMManager.shared.$chatTabAllUnreadCount.sink {[weak self] count in
            guard let `self` = self else {
                return
            }
            guard let chatItem = self.customTabBar.tabItems?[1] else { return }
            chatItem.count = count
        }.store(in: &cancellables)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        print("♻️TabBarController")
    }
}

extension TabBarController {
    public func setSelected(index: TabBarItemIndex) {
        customTabBar.setSelected(selected: true, index: index)
        switch index {
        case .home:
            selectedIndex = 0
        case .friend:
            selectedIndex = 1
        case .discover:
            selectedIndex = 2
        case .me:
            selectedIndex = 3
        case .add:
            break
        }
    }
}

extension TabBarController {
    private func configViewControllers() {
        let home = CLNavigationController(rootViewController: HomePageRootController())
        let friend = CLNavigationController(rootViewController: FriendsRootHomeController())
//        let discover = CLNavigationController(rootViewController: DiscoverRootPageController())
        let discover = CLNavigationController(rootViewController: RolesRootPageController())
        let me = CLNavigationController(rootViewController: MeRootPageController())
        viewControllers = [home, friend, discover, me]

        let homeItem = TitleItem(title: "1",
                                 image: UIImage(named: "tabbar_home_normal")!,
                                 selectedImage: UIImage(named: "tabbar_home_selected")!,
                                 itemIndex: .home)
        homeItem.count = 0

        let friendItem = TitleItem(title: "2",
                                   image: UIImage(named: "tabbar_video_normal")!,
                                   selectedImage: UIImage(named: "tabbar_video_selected")!,
                                   itemIndex: .friend)
        friendItem.count = 0

        let discoverItem = TitleItem(title: "3",
                                     image: UIImage(named: "tabbar_role_normal")!,
                                     selectedImage: UIImage(named: "tabbar_role_selected")!,
                                     itemIndex: .discover)

        let meItem = TitleItem(title: "4",
                               image: UIImage(named: "tabbar_history_normal")!,
                               selectedImage: UIImage(named: "tabbar_history_selected")!,
                               itemIndex: .me)
        meItem.count = 0

//        let addItem = TitleItem(title: "+",
//                                image: UIImage(named: "tabbar_create_app")!,
//                                selectedImage: UIImage(named: "tabbar_create_app")!,
//                                itemIndex: .add)

        let childItem: [TabbarItem] = [homeItem, friendItem, /*addItem,*/ discoverItem, meItem]
        customTabBar.tabItems = childItem
        customTabBar.tabBarDelegate = self
        setValue(customTabBar, forKey: "tabBar")
    }

    // MARK: noti

    @objc private func notiPresentSignInVc() {
        if UserCore.shared.isLogin() {
            return
        }

        if let vc = UIWindow.getTopViewController(), vc.isKind(of: CLLoginMainController.self) {
            dlog("⚠️已弹出登录")
        } else {
            let vc = CLLoginMainController()
            let navc = CLNavigationController(rootViewController: vc)
            navc.modalPresentationStyle = .fullScreen
            AppRouter.shared.isBlockBackRootVc = true
            present(navc, animated: true) {
                AppRouter.shared.isBlockBackRootVc = false
            }
        }
    }

//    @objc private func unreadChanged() {
//        guard let chatItem = customTabBar.tabItems?[1] else { return }
//        chatItem.count = IMManager.shared.chatTabAllUnreadCount
//    }
}

// MARK: - TabBarDelegate

extension TabBarController: TabBarDelegate {
    func tabBar(_: TabBar, didSelectItemAt index: TabBarItemIndex) {
        switch index {
        case .home:
            #if DEBUG
            if APIConfig.environment != .appStore && APIConfig.environment != .product{
                if selectedIndex == 0 {
                    UIWindow.getTopViewController()?.navigationController?.pushViewController(TestEntrancesController(), animated: true)
                }
            }
            #endif
            selectedIndex = 0
        case .friend:
            selectedIndex = 1
        case .discover:
            selectedIndex = 2
        case .me:
            selectedIndex = 3
        case .add:
            break
            //AppRouter.goCreateEditAIRole()
        }
        
        IMManager.shared.regetAllUnreadCount()
    }

    func tabBar(_: TabBar, canTapEnterItem index: TabBarItemIndex) -> Bool {
        switch index {
        case .me, .friend:
            if UserCore.shared.checkUserLoginIfNotPushUserToLogin() {
                return true
            } else {
                return false
            }
        case .add:
            if UserCore.shared.checkUserLoginIfNotPushUserToLogin(){
                AppRouter.goCreateEditAIRole()
            }
            return false
        default:
            return true
        }
    }
}
