<script>
	export default {
		onLaunch: function() {
			console.log('App Launch');
			// 检查登录状态
			this.checkLoginStatus();
		},
		onShow: function() {
			console.log('App Show');
			// 每次显示应用时检查登录状态
			this.checkLoginStatus();
		},
		onHide: function() {
			console.log('App Hide');
			// 应用进入后台时释放资源
			this.releaseGlobalResources();
		},
		
		// 全局错误捕获
		onError: function(error) {
			this.handleGlobalError(error);
		},
		methods: {
			// 释放全局资源
			releaseGlobalResources: function() {
				console.log('Releasing global resources');
				// 清除可能存在的定时器
				try {
					// 这里可以添加更多的资源释放逻辑
				} catch (e) {
					console.error('Error releasing resources:', e);
				}
			},
			
			// 全局错误处理
			handleGlobalError: function(error) {
				console.error('Global error captured:', error);
				
				// 处理特定类型的错误
				if (error.message && error.message.includes('Failed to receiveTasks')) {
					// 提取实例ID
					const instanceIdMatch = error.message.match(/instance \((\d+)\)/);
					const instanceId = instanceIdMatch ? instanceIdMatch[1] : 'unknown';
					
					// 记录详细错误信息
					console.error(`UHF plugin instance (${instanceId}) error: Failed to receiveTasks`);
					
					// 显示错误提示
					uni.showToast({
						title: `设备通信错误(实例${instanceId})，请重试`,
						icon: 'none',
						duration: 3000
					});
						
					// 尝试重置插件实例
					setTimeout(() => {
						this.resetPluginInstance();
					}, 1000);
				}
			},
			
			// 重置应用状态
			resetAppState: function() {
				console.log('Resetting app state due to plugin error');
				try {
					// 清除所有相关缓存数据
					uni.removeStorageSync('uhf_plugin_state');
					uni.removeStorageSync('equipment_token');
					
					// 重新加载当前页面
					const pages = getCurrentPages();
					if (pages && pages.length > 0) {
						const currentPage = pages[pages.length - 1];
						// 如果当前是首页，则刷新页面
						if (currentPage.route === 'pages/index/index') {
							currentPage.$vm.$destroy();
							uni.redirectTo({
								url: '/pages/index/index'
							});
						} else {
							// 否则跳转到首页
							uni.redirectTo({
								url: '/pages/index/index'
							});
						}
					} else {
						// 如果没有页面，跳转到首页
						uni.redirectTo({
							url: '/pages/index/index'
						});
					}
				} catch (e) {
					console.error('Error resetting app state:', e);
				}
			},
			
			// 检查并清理插件实例
			checkAndCleanupPluginInstance: function() {
				console.log('Checking and cleaning up plugin instance');
				try {
					// 如果存在页面实例
					const pages = getCurrentPages();
					if (pages && pages.length > 0) {
						const currentPage = pages[pages.length - 1];
						if (currentPage && currentPage.$vm) {
							// 如果页面有uhfSFHelper实例，尝试释放设备
							if (currentPage.$vm.uhfSFHelper) {
								try {
									console.log('Releasing device from current page');
									currentPage.$vm.releaseDevice();
								} catch (e) {
									console.error('Error releasing device:', e);
								}
								// 清除插件实例
								currentPage.$vm.uhfSFHelper = null;
								console.log('Plugin instance cleared from current page');
							}
						}
					}
					
					// 清除全局插件相关缓存
					uni.removeStorageSync('uhf_plugin_instance');
					console.log('Plugin related storage cleared');
				} catch (e) {
					console.error('Error checking and cleaning up plugin instance:', e);
				}
			},
			

			checkLoginStatus: function() {
				try {
					const token = uni.getStorageSync('equipment_token');
					// 获取当前页面路径
					const pages = getCurrentPages();
					let currentPath = '';
					if (pages && pages.length > 0) {
						const currentPage = pages[pages.length - 1];
						currentPath = currentPage.route;
					}

					if (!token) {
						// 未登录，跳转到登录页面
						// 检查当前是否已经在登录页面，避免重复跳转
						if (currentPath !== 'pages/login/login') {
							uni.redirectTo({
								url: '/pages/login/login'
							});
						}
					} else {
						// 已登录，设置全局登录状态
						const equipmentManage = uni.getStorageSync('equipment_manage');
						const userInfo = uni.getStorageSync('user_info') || {};
						this.globalData.isLoggedIn = true;
						this.globalData.token = token;
						this.globalData.equipmentManage = equipmentManage;
						this.globalData.userInfo = userInfo;
					}
				} catch (e) {
					// 错误处理
					console.error('检查登录状态失败:', e);
					// 跳转到登录页面
					// 获取当前页面路径
					const pages = getCurrentPages();
					let currentPath = '';
					if (pages && pages.length > 0) {
						const currentPage = pages[pages.length - 1];
						currentPath = currentPage.route;
					}

					// 检查当前是否已经在登录页面，避免重复跳转
					if (currentPath !== 'pages/login/login') {
						uni.redirectTo({
							url: '/pages/login/login'
						});
					}
				}
			},
			
			// 重置插件实例
			resetPluginInstance: function() {
				console.log('Resetting plugin instance globally');
				try {
					this.checkAndCleanupPluginInstance();
					
					// 延迟一段时间后重置应用状态
					setTimeout(() => {
						this.resetAppState();
					}, 1000);
				} catch (e) {
					console.error('Error resetting plugin instance:', e);
				}
			}
		},
		globalData: {
			isLoggedIn: false,
			token: '',
			equipmentManage: 0,
			userInfo: {}
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import "components/colorui/main.css";
	@import "components/colorui/icon.css";
</style>