<template>
	<view class="startup-page">
		<text class="hint">{{ hintText }}</text>
		<text v-if="showRetry" class="retry" @click="runStartup">点击重试</text>
	</view>
</template>

<script>
	import {
		getToken,
		setToken,
		getCurrentUserInfo,
		normalizeUserPayload
	} from '../../utils/api'
	import { connectWebSocket } from '../../composables/useWebSocket'
	// #ifdef APP-PLUS
	import { setupAppNotifications } from '../../utils/notificationSetup'
	// #endif

	const USER_KEY = 'current_user'

	const ME_OPTIONS = {
		skipSessionRedirectOnAuthFailure: true,
		skipRequestFailToast: true
	}

	export default {
		data() {
			return {
				hintText: '软件正在启动中…',
				showRetry: false
			}
		},
		onLoad() {
			this.runStartup()
		},
		methods: {
			async runStartup() {
				const token = getToken()
				if (!token) {
					uni.reLaunch({ url: '/pages/login/index' })
					return
				}
				this.showRetry = false
				this.hintText = '软件正在启动中…'
				try {
					const me = await getCurrentUserInfo(token, ME_OPTIONS)
					const u = normalizeUserPayload(me)
					if (u) {
						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) {}
					}
					connectWebSocket()
					// #ifdef APP-PLUS
					setupAppNotifications()
					// #endif
					uni.reLaunch({ url: '/pages/index/index' })
				} catch (e) {
					if (e && e.authFailure) {
						setToken('')
						uni.showToast({ title: '登录已过期', icon: 'none' })
						setTimeout(() => {
							uni.reLaunch({ url: '/pages/login/index' })
						}, 80)
						return
					}
					this.hintText = '网络异常，请检查网络后重试'
					this.showRetry = true
					uni.showToast({ title: e.message || '网络异常', icon: 'none' })
				}
			}
		}
	}
</script>

<style scoped>
	.startup-page {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #fff;
		padding: 48rpx;
		box-sizing: border-box;
	}
	.hint {
		font-size: 32rpx;
		color: #333;
		text-align: center;
		line-height: 1.5;
	}
	.retry {
		margin-top: 48rpx;
		font-size: 30rpx;
		color: #259653;
		text-decoration: underline;
	}
</style>
