//
//  BsTabBarViewController.swift
//  BaiSiSMApp
//
//  Created by davidhuang on 2022/12/4.
//  Copyright © 2022 www.davidhuang.com. All rights reserved.
//

import UIKit
import ESTabBarController_swift

class YHTabBarViewController: ESTabBarController {
    
    lazy var viewModel = {
        let model = YHMsgViewModel()
        return model
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        handleTabBarLine()
        addObservers()
        if YHLoginManager.shared.isLogin() {
            getTotalUnreadMsgCount()
            reportDeviceInfo()
        }
    }
    
    func addObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(clearAllUnreadBadge), name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(getTotalUnreadMsgCount), name: YhConstant.YhNotification.didRequestUnreadMsgTotalCountNotification, object: nil)
        
    }
}

extension YHTabBarViewController {
    @objc func hideTabBar() -> Void {
        self.tabBar.isHidden = true
    }
    
    @objc func showTabBar() -> Void {
        self.tabBar.isHidden = false
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        getTotalUnreadMsgCount()
    }
    
    @objc func logoutSuccess() {
        printLog("登出成功")
    }
    
    
    @objc func clearAllUnreadBadge() {
        DispatchQueue.main.async {
            if let vcs = self.viewControllers, let msgListVC = vcs[safe: 2] {
                msgListVC.tabBarItem.badgeValue = nil
                UIApplication.shared.applicationIconBadgeNumber = 0
            }
        }
    }
    
    // 请求未读消息总数
    @objc func getTotalUnreadMsgCount() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        self.viewModel.requestTotalUnreadMsgCount {
            [weak self] success, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                if let vcs = self.viewControllers, let msgListVC = vcs[safe: 2] {
                    let count = self.viewModel.unreadTotalCount
                    var unreadText:String? = nil
                    if 0 < count && count <= 99 {
                        unreadText = String(count)
                        
                    } else if count > 99 {
                        unreadText = "99+"
                    }
                    msgListVC.tabBarItem.badgeValue = unreadText
                }
            }
        }
    }
    
    func reportDeviceInfo() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        JPUSHService.registrationIDCompletionHandler {
            resCode, registrationID in
            if let deviceId = registrationID, !deviceId.isEmpty {
                printLog("deviceId:\(deviceId)")
                YHLoginManager.shared.deviceTokenModel.registerId = deviceId
                self.viewModel.requestReportDeviceInfo(deviceId: deviceId) {
                    success, error in
                    if let error = error, !error.errorMsg.isEmpty {
                        printLog("error:\(error.errorMsg)")
                    }
                }
            }
        }
    }
}

extension YHTabBarViewController {
    
    //展示tabbar上的横线
    func handleTabBarLine() -> Void {
        let rect = CGRect.init(x:0,y:0,width:KScreenWidth,height:0.5)
        let fillColor = UIColor.mainTextColor5
        let img = UIImage.from(color: fillColor, rect: rect)
        
        UIView.transition(with:self.tabBar, duration:0.5, options: .transitionCrossDissolve) {
            let appearance = self.tabBar.standardAppearance.copy()
            appearance.backgroundImage = UIImage()
            appearance.shadowImage = img
            self.tabBar.standardAppearance = appearance
        } completion: { Bool in
        }
    }
}
