<script>
	import { initIM, getConversationList } from './utils/im'

	export default {
		globalData: {
			badgeTimer: null
		},
		onLaunch: function() {
			const token = uni.getStorageSync('token')
			if (!token) return

			initIM().catch(e => {
				console.log('[App] IM 初始化失败（非阻塞）:', e.message)
			})
		},
		onShow: function() {
			this.updateTabBarBadge()
			// 全局定时刷新 tabBar 未读数（每10秒）
			if (!this.globalData.badgeTimer) {
				this.globalData.badgeTimer = setInterval(() => {
					this.updateTabBarBadge()
				}, 10000)
			}
		},
		onHide: function() {
			if (this.globalData.badgeTimer) {
				clearInterval(this.globalData.badgeTimer)
				this.globalData.badgeTimer = null
			}
		},
		methods: {
			async updateTabBarBadge() {
				try {
					const token = uni.getStorageSync('token')
					if (!token) return
					// 仅在 TabBar 页面才操作角标，避免非 TabBar 页面报错
					const pages = getCurrentPages()
					const currentPage = pages[pages.length - 1]
					const tabBarPaths = ['pages/index/index', 'pages/order-hall/order-hall', 'pages/message/message', 'pages/mine/mine']
					if (!currentPage || !tabBarPaths.includes(currentPage.route)) return
					const convList = await getConversationList()
					const total = convList.reduce((sum, c) => sum + (c.unreadCount || 0), 0)
					if (total > 0) {
						uni.setTabBarBadge({ index: 2, text: total > 99 ? '99+' : String(total) })
					} else {
						uni.removeTabBarBadge({ index: 2 })
					}
				} catch (e) {}
			}
		}
	}
</script>

<style>
	/* 全局公共样式 */
	page {
		background-color: #F5F5F5;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		font-size: 28rpx;
		color: #333333;
	}
</style>
