//
//  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() {
            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)
        
    }
}

extension YHTabBarViewController {
    @objc func hideTabBar() -> Void {
        self.tabBar.isHidden = true
    }
    
    @objc func showTabBar() -> Void {
        self.tabBar.isHidden = false
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
    }
    
    @objc func logoutSuccess() {
        printLog("登出成功")
    }
    
    
    @objc func clearAllUnreadBadge() {
        DispatchQueue.main.async {
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
    }
        
    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
        }
    }
}
