<script>
	import { getToken, getCurrentUserInfo, normalizeUserPayload } from './utils/api'
	import { connectWebSocket } from './composables/useWebSocket'
	import { setupAppNotifications } from './utils/notificationSetup'

	const USER_KEY = 'current_user'
	// #ifdef APP-PLUS
	import { scheduleAndroidApkUpdateCheck, maybeCheckAndroidApkUpdateByInterval } from './utils/appUpgrade'
	// #endif

	export default {
		onLaunch: async function() {
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform === 'android') {
				scheduleAndroidApkUpdateCheck()
			}
			// #endif
			const token = getToken()
			if (!token) {
				uni.reLaunch({ url: '/pages/login/index' })
				return
			}
			uni.reLaunch({ url: '/pages/index/index' })
			// 已登录启动即建 WS；登录页 setToken 后也会 connect（reLaunch 不会再次 onLaunch）
			connectWebSocket()
			// #ifdef APP-PLUS
			setupAppNotifications()
			// #endif
			getCurrentUserInfo(token)
				.then((me) => {
					const u = normalizeUserPayload(me)
					if (!u) return
					const orgName = u.orgName || u.org_name || ''
					try {
						const prev = uni.getStorageSync(USER_KEY)
						const base = prev && typeof prev === 'object' ? prev : {}
						uni.setStorageSync(USER_KEY, {
							...base,
							...u,
							orgName,
							org_name: orgName
						})
					} catch (e) {}
				})
				.catch(() => {})
		},
		onShow: function() {
			console.log('App Show')
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform === 'android') {
				maybeCheckAndroidApkUpdateByInterval()
			}
			// #endif
			if (getToken()) {
				connectWebSocket()
			}
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

<style>
	/*每个页面公共css */
</style>
