//
//  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
    }()
    
    let msgViewModel = YHMsgViewModel()
    
    lazy var shareView: YHShareViewOnTablebarView = {
        let view = YHShareViewOnTablebarView()
        view.isHidden = true
        return view
    }()
    
    private var shareModel: TabBarShareModel?
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        shareView.frame = self.tabBar.frame
        view.bringSubviewToFront(shareView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        handleTabBarLine()
        addObservers()
        if YHLoginManager.shared.isLogin() {
            reportDeviceInfo()
        }
        
        shareView.frame = self.tabBar.frame
        view.addSubview(shareView)
        
        shareView.block = { tag in
            
            if let model = self.shareModel {
                if tag == 0 {
                    // 分享
                    let title = !model.shareTitle.isEmpty ? model.shareTitle : "请查看"
                    YHShareManager.shared.shareToMiniProgram(path: model.shareUrl, shareTitle: title)
                } else {
                    // 预约咨询
                    let codeUrl = model.codeUrl
                    let downloadUrl = model.downloadUrl
                    YHConsultantQRCodeView.codeView(codeUrl, downloadUrl: downloadUrl).show()
                }
            }
        }
        
        getTotalUnreadMsgCount()
    }
    
    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(changeShareViewStatus(_ :)), name: YhConstant.YhNotification.changeShareViewStatusOnTabBarNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getTotalUnreadMsgCount), name: YhConstant.YhNotification.didRequestUnreadMsgTotalCountNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getTotalUnreadMsgCount), name: YhConstant.YhNotification.didQiYuUnReadMsgCountChangeNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(clearFriendTabBadge), name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
        
    }
    
    @objc func getTotalUnreadMsgCount() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        
        self.msgViewModel.requestTotalUnreadMsgCount {
            [weak self] _, _ in
            guard let self = self else { return }
            DispatchQueue.main.async {
                var unreadCount = self.msgViewModel.unreadTotalCount
                if YHButlerServiceManager.shared.isUatAllowed() {
                    unreadCount = self.msgViewModel.unreadTotalCount + YHButlerServiceManager.shared.unreadCount
                }
                // 朋友tab小红点显示逻辑
                self.showFriendTabRedBadgeNumber(unreadCount)
            }
        }
    }
    
    @objc func clearFriendTabBadge() {
        showFriendTabRedBadgeNumber(0)
    }
    
    func showFriendTabRedBadgeNumber(_ num: Int) {
        if let vcs = self.viewControllers, vcs.count > 3 {
            let friendVC = vcs[3]
            if let tabBarItem = friendVC.tabBarItem as? ESTabBarItem {
                // badgeValue 空字符串会显示小红点 nil则隐藏
                var badge: String?
                if num > 99 {
                    badge = "99+"
                } else if 0 < num, num <= 99 {
                    badge = "\(num)"
                }
                tabBarItem.badgeColor = UIColor.init(hex: 0xF81D22)
                tabBarItem.contentView?.badgeView.badgeLabel.font = UIFont.PFSC_M(ofSize: 10)
                tabBarItem.badgeValue = badge
            }
        }
    }
}

extension YHTabBarViewController {
    @objc func hideTabBar() {
        self.tabBar.isHidden = true
    }
    
    @objc func showTabBar() {
        self.tabBar.isHidden = false
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        getTotalUnreadMsgCount()
    }
    
    @objc func logoutSuccess() {
        printLog("登出成功")
        clearFriendTabBadge()
    }
    
    @objc func changeShareViewStatus(_ notification: Notification) {
        if let model = notification.object as? TabBarShareModel {
            shareModel = model
            if model.showFlag {
                if self.shareView.isHidden {
                    self.shareView.isHidden = false
                    self.shareView.layer.opacity = 0.0
                    UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseIn]) {
                        self.shareView.layer.opacity = 1.0
                    } completion: { _ in }
                }
            } else {
                if self.shareView.isHidden == false {
                    shareView.layer.opacity = 1.0
                    UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseOut]) {
                        self.shareView.layer.opacity = 0.0
                    } completion: { _ in
                        self.shareView.isHidden = true
                    }
                }
            }
        }
    }
            
    func reportDeviceInfo() {
        if !YHLoginManager.shared.isLogin() {
            return
        }
        JPUSHService.registrationIDCompletionHandler {
            _, registrationID in
            if let deviceId = registrationID, !deviceId.isEmpty {
                printLog("deviceId:\(deviceId)")
                YHLoginManager.shared.deviceTokenModel.registerId = deviceId
                self.viewModel.requestReportDeviceInfo(deviceId: deviceId) {
                    _, error in
                    if let error = error, !error.errorMsg.isEmpty {
                        printLog("error:\(error.errorMsg)")
                    }
                }
            }
        }
    }
}

extension YHTabBarViewController {
    
    // 展示tabbar上的横线
    func handleTabBarLine() {
        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: { _ in
        }
    }
}
