<template>
	<view v-if="!globalDataLoaded" class="global-loading">
		<view class="loading-container">
			<view class="loading-logo">
				<image src="/static/回收/衣物.png" mode="aspectFit" class="logo-img" />
			</view>
			<view class="loading-spinner">
				<view class="spinner"></view>
			</view>
			<text class="loading-text">正在加载...</text>
			<view class="loading-progress">
				<view class="progress-bar" :style="{width: loadingProgress + '%'}"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import routerInterception from '@/utils/router-interception.js'
	import config from  '/config.js'
	export default {
		data() {
			return {
				globalDataLoaded: false,
				loadingProgress: 0,
				loadedCount: 0,
				totalRequests: 3 // 总共需要加载的请求数量
			}
		},
		globalData: {
			flag: 1,
			login_status: true,
			phone: null,
			bannerList: [],
			pricePreviewList: [],
			configData: [],
			qr_path: '',
			isAppDataReady: false // 新增标志位
		},
		onLaunch: function() {
			routerInterception()
			this.initializeAppData()
			console.log('App Launch')
		},
		onLoad: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 初始化应用数据
			async initializeAppData() {
				try {
					// 设置初始进度
					this.loadingProgress = 0
					this.loadedCount = 0
					
					// 并发加载所有数据
					const promises = [
						this.getBannerList(),
						this.getPricePreviewList(),
						this.getConfigData(),
					]
					// this.getQrCode()
					await Promise.all(promises)
					
					// 确保进度达到100%
					this.loadingProgress = 100
					
					// 所有数据加载完成
					this.globalDataLoaded = true
					getApp().globalData.isAppDataReady = true
					
					// 延迟一点时间让用户看到加载完成的状态
					setTimeout(() => {
						uni.$emit('appDataReady')
					}, 500)
					
				} catch (error) {
					console.error('App data loading failed:', error)
					// 即使失败也要让应用继续运行
					this.loadingProgress = 100
					this.globalDataLoaded = true
					getApp().globalData.isAppDataReady = true
					
					setTimeout(() => {
						uni.$emit('appDataReady')
					}, 500)
				}
			},
			
			// 更新加载进度
			updateProgress() {
				this.loadedCount++
				this.loadingProgress = Math.round((this.loadedCount / this.totalRequests) * 100)
			},
			
			getBannerList() {
				return new Promise((resolve) => {
					if (!this.$api) {
						this.updateProgress()
						resolve()
						return
					}
					
					this.$api('getBanner', {}, res => {
						if (res && res.code === 200 && Array.isArray(res.result)) {
							getApp().globalData.bannerList = res.result
							console.log(getApp().globalData.bannerList, 'bannerList')
							uni.$emit('bannerListUpdated')
						}
						this.updateProgress()
						resolve()
					})
				})
			},
			
			getPricePreviewList() {
				return new Promise((resolve) => {
					if (!this.$api) {
						this.updateProgress()
						resolve()
						return
					}
					
					this.$api('getPricePreviewClassList', {}, res => {
						if (res && res.success && Array.isArray(res.result)) {
							getApp().globalData.pricePreviewList = res.result
							uni.$emit('pricePreviewListUpdated')
						}
						this.updateProgress()
						resolve()
					})
				})
			},
			
			getConfigData() {
				return new Promise((resolve) => {
					if (!this.$api) {
						this.updateProgress()
						resolve()
						return
					}
					
					this.$api('getConfig', {}, res => {
						console.log('Config data response:', JSON.parse(JSON.stringify(res)))
						if (res && res.success && Array.isArray(res.result)) {
							getApp().globalData.configData = res.result
							uni.$emit('configDataUpdated')
						}
						this.updateProgress()
						resolve()
					})
				})
			},
			
			getQrCode() {
				return new Promise((resolve) => {
					if (!uni.getStorageSync('token')) {
						this.updateProgress()
						resolve()
						return
					}
					
					uni.getImageInfo({
						src: `${config.baseUrl}/recycle-admin/applet/promotion/getInviteCode?token=${uni.getStorageSync('token')}`,
						success: res => {
							getApp().globalData.qr_path = res.path
							console.log(getApp().globalData.qr_path, 'qr_path')
							this.updateProgress()
							resolve()
						},
						fail: err => {
							console.log('QR code load failed:', err)
							this.updateProgress()
							resolve()
						}
					})
				})
			}
		}
	}
</script>

<style>
	/* 全局loading样式 */
	.global-loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 99999;
	}
	
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.loading-logo {
		margin-bottom: 60rpx;
	}
	
	.logo-img {
		width: 160rpx;
		height: 160rpx;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
	}
	
	.loading-spinner {
		margin-bottom: 40rpx;
	}
	
	.spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.3);
		border-top-color: #fff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}
	
	.loading-text {
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 40rpx;
		opacity: 0.9;
	}
	
	.loading-progress {
		width: 400rpx;
		height: 6rpx;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 3rpx;
		overflow: hidden;
	}
	
	.progress-bar {
		height: 100%;
		background: linear-gradient(90deg, #fff 0%, #f0f8ff 100%);
		border-radius: 3rpx;
		transition: width 0.3s ease;
		box-shadow: 0 0 10rpx rgba(255, 255, 255, 0.3);
	}
	
	@keyframes spin {
		from { transform: rotate(0deg); }
		to { transform: rotate(360deg); }
	}

	/* 原有样式 */
	/*每个页面公共css */
	.uni-tabbar-bottom {
		display: none;
	}

	.icon {
		width: 50rpx;
		height: 50rpx;
	}

	.nav-bar {
		/* margin-top: calc(70rpx + env(safe-area-inset-top)); */
		height: 30%;
		display: flex;
		justify-content: center;
	}

	/* 每个页面公共css */
	/* 解决小程序和app滚动条的问题 */

	::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
		color: transparent;
	}


	/* 解决H5的问题 */

	uni-scroll-view .uni-scroll-view::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
		color: transparent;
	}
</style>