<script>
	import { wxLogin } from '@/http/api/auth.js'

	export default {
		onLaunch: function() {
			console.log('App Launch')
			this.initApp()
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 应用初始化
			async initApp() {
				console.log('应用初始化开始')
				await this.checkAutoLogin()
			},

			// 等待HTTP配置初始化
			async waitForHttpInit() {
				// 等待uni.$u.http可用
				let retryCount = 0
				const maxRetries = 10

				while (!uni.$u || !uni.$u.http) {
					if (retryCount >= maxRetries) {
						throw new Error('HTTP配置初始化超时')
					}
					await new Promise(resolve => setTimeout(resolve, 100))
					retryCount++
				}

				console.log('HTTP配置初始化完成')
			},

			// 检查自动登录
			async checkAutoLogin() {
				try {
					// 检查本地是否有有效token
					const token = uni.getStorageSync('token')
					if (token) {
						return
					}

					// 等待HTTP配置初始化完成
					await this.waitForHttpInit()

					// 获取微信登录code
					const loginRes = await new Promise((resolve, reject) => {
						uni.login({
							success: resolve,
							fail: reject
						})
					})

					if (loginRes.code) {
						// 调用后端登录接口
						const result = await uni.$u.http.post('/wechat/user/mini/login', {
							code: loginRes.code
						}, {
							custom: {
								loading: false,
								toast: false,
								auth: false
							}
						})

						if (result && result.token) {
							// 用户已授权过手机号，保存登录信息
							this.saveLoginData(result)
						} else {
							// 用户未授权手机号，保存微信登录code供后续使用
							this.saveWxCode(loginRes.code)
						}
					}
				} catch (error) {
					// 静默处理错误，不影响应用正常启动
					console.error('自动登录失败:', error)
				}
			},

			// 保存登录数据
			saveLoginData(result) {
				uni.setStorageSync('token', result.token)
				if (result.refreshToken) {
					uni.setStorageSync('refreshToken', result.refreshToken)
				}
				if (result.userInfo) {
					uni.setStorageSync('wxUserInfo', result.userInfo)
					uni.setStorageSync('userInfo', result.userInfo)
				}

				// 设置登录状态
				const loginStep = result.userInfo && result.userInfo.profileCompleted
					? 'profile_completed'
					: 'phone_authed'
				uni.setStorageSync('loginStep', loginStep)
			},

			// 保存微信code
			saveWxCode(code) {
				uni.setStorageSync('wxLoginCode', code)
				uni.setStorageSync('loginDate', new Date().toISOString())
				uni.setStorageSync('loginStep', 'wx_logged')
			}
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
  @import "@/uni_modules/uview-next/index.scss";
</style>
