 
<script>
	import {
		loginAfterHandle
	} from './utils/loginHandle.js'
  import AppConfirm from '@/components/app-confirm/app-confirm.vue'
  // #ifdef H5
  import Vue from 'vue'
  // #endif
	export default {
    components:{ AppConfirm },
		globalData: {
			isPad: false,
			lastAuthCheckTime: 0
		},
			onLaunch: function(e) {
			//当url存在loginData时直接种上数据
			/* 条件编译，仅在H5平台生效 */
			// #ifdef H5

			if (e.query.loginData && e.query.hospSign) {
				try {
					loginAfterHandle(JSON.parse(decodeURI(e.query.loginData)), e.query.hospSign);
				} catch (e) {
					console.log({
						e
					})
				}
			}


			uni.getSystemInfo({
				success:(e)=>{
					/* 窗口宽度大于420px且不在PC页面且不在移动设备时跳转至 PC.html 页面 */
					console.log(e, window.top.isPC, !/iOS|Android/i.test(e.system));
					this.globalData.isPad =
						e.deviceType === 'pad' ||
						/iPad|Pad/i.test(e.model) ||
						e.screenWidth >= 768
						
					if (e.windowWidth > 420 && !window.top.isPC && !/iOS|Android/i.test(e.system)) {

						const url = decodeURIComponent(`/TracerMethodology/static/html/template.html`);
						// console.log({hospSign,url});
						window.location.pathname = url;
						/* 若项目未设置根目录（默认为 / 时），则使用下方代码 */
						// window.location.pathname = '/static/html/pc.html';
					}
				}
			})
			// #endif		

			// 统一：H5 端在关闭页签/刷新时清空 AI 问答本地缓存
			// #ifdef H5
			try {
				if (typeof window !== 'undefined') {
					window.addEventListener('beforeunload', () => {
						try {
							uni.removeStorageSync('aiQaMessagesV1');
						} catch (err) {}
					});
				}
			} catch (err) {}
			// #endif
			
			// 创建全局自定义弹窗服务（无侵入替换 uni.showModal）
			try {
				if (!uni.__ORIG_SHOW_MODAL__) {
					uni.__ORIG_SHOW_MODAL__ = uni.showModal;
					uni.showModal = (options = {}) => {
						try {
							const app = getApp && getApp();
							const root = app && app.$vm;
							const confirmRef = root && root.$refs && (root.$refs.AppConfirm || root.$refs.appConfirm);
							if (confirmRef && typeof confirmRef.open === 'function') {
								return confirmRef.open({
									title: options.title || '提示',
									content: options.content || '',
									confirmText: options.confirmText || '确定',
									cancelText: options.cancelText || '取消',
									showCancel: options.showCancel !== false, // 透传 showCancel，默认 true
									type: options.type || 'default'
								}).then((ok) => {
									options.success && options.success({ confirm: ok, cancel: !ok });
									options.complete && options.complete({ confirm: ok, cancel: !ok });
									return { confirm: ok, cancel: !ok };
								});
							}
						} catch (err) {}
						// 兜底：若全局组件未就绪，回退原生
						return uni.__ORIG_SHOW_MODAL__.call(uni, options);
					}
				}
			} catch (err) {}

			// H5：程序化挂载（仅当静态挂载未就绪时）
			// #ifdef H5
			try {
				const app = getApp && getApp();
				const root = app && app.$vm;
				if (root && !(root.$refs && root.$refs.AppConfirm)) {
					const Ctor = Vue.extend(AppConfirm);
					const vm = new Ctor();
					vm.$mount();
					document.body.appendChild(vm.$el);
					root.$refs = root.$refs || {};
					root.$refs.AppConfirm = vm;
				}
			} catch (e) {}
			// #endif

			// APP-PLUS：不再进行运行时 DOM 插入，统一依赖静态挂载的 <AppConfirm />

			// 应用启动时执行设备授权校验
			this.checkDeviceAuthorization();
		},
		onShow: function() {
			// 所有平台在应用启动或回到前台时都执行设备授权校验
			this.checkDeviceAuthorization();
		},
		onHide: function() {
			// 应用进入后台或被关闭时，清空 AI 问答的本地缓存
			try {
				uni.removeStorageSync('aiQaMessagesV1');
			} catch (e) {}
		},
		methods: {
			// 启动设备授权校验：基于 IMEI 获取授权状态，根据不同状态进行相应跳转
			async checkDeviceAuthorization() {
				console.log('checkDeviceAuthorization 被调用');

				// H5 平台：不走授权流程
				// #ifdef H5
				return;
				// #endif

				// 移除H5的debug授权页面兜底逻辑

				// APP 平台：等待 plusready 再执行，确保能获取到设备标识
				// #ifdef APP-PLUS
				try {
					if (typeof plus === 'undefined' || !plus.device) {
						console.log('APP 未就绪，等待 plusready 后再执行授权校验');
						const once = () => {
							try { document.removeEventListener('plusready', once); } catch (e) {}
							this.checkDeviceAuthorization();
						};
						document.addEventListener('plusready', once);
						return;
					}
				} catch (e) {}
				// #endif
				
				// 检查当前页面路径
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				const currentRoute = currentPage ? currentPage.route : '';
				console.log('当前页面路径:', currentRoute);
				
				// 不再存在需要排除的 debug 调试页面
				
				// 节流机制：避免短时间内重复检查（5秒内只检查一次）
				const now = Date.now();
				if (now - this.globalData.lastAuthCheckTime < 5000) {
					console.log('授权检查节流：跳过重复检查', { 
						now, 
						last: this.globalData.lastAuthCheckTime, 
						diff: now - this.globalData.lastAuthCheckTime 
					});
					return;
				}
				this.globalData.lastAuthCheckTime = now;
				
				try {
					const { getDeviceImeiOrUuid } = await import('@/utils/device.js');
					const { fetchDeviceAuthorization } = await import('@/utils/authorize.js');
					const imei = await getDeviceImeiOrUuid();
					if (!imei) {
						// H5+Debug才会执行到这里，为避免误扰，仅提示一次
						uni.showToast({ title: '无法获取设备标识', icon: 'none' });
						return;
					}
					console.log('开始调用授权查询接口, IMEI:', imei);
					const auth = await fetchDeviceAuthorization(imei);
					console.log('设备授权状态返回结果:', auth);
					
					if (!auth) {
						uni.showToast({ title: '授权查询失败', icon: 'none' });
						return;
					}
					
					switch (auth.status) {
						case 'authorized':
							// 已授权：保存hospSign并跳转到登录页
							if (auth.hospSign) {
								uni.setStorageSync('hospSign', auth.hospSign);
							}
							// 保存后端region作为业务接口域名
							if (auth.region) {
								try {
									const { setRuntimeRegionDomain } = await import('@/utils/requestUrl.js');
									setRuntimeRegionDomain(auth.region);
								} catch (e) {}
							}
							// 已授权：根据是否已登录决定是否跳转登录页
							try {
								const hasToken = !!uni.getStorageSync('token');
								if (hasToken) {
									console.log('设备已授权，已登录，跳过登录跳转');
									return;
								}
							} catch (e) {}
							console.log('设备已授权，未登录，跳转登录页');
							uni.reLaunch({ url: `/pages/login/login?hospSign=${encodeURIComponent(auth.hospSign || '')}` });
							return;
							
						case 'reviewing':
							// 审核中：跳转到申请页面并显示待审核状态
							if (auth.applyInfo) {
								uni.setStorageSync('authApplyInfo', auth.applyInfo);
							}
							uni.reLaunch({ url: `/pages/applyAuth/applyAuth?imei=${encodeURIComponent(imei)}` });
							break;
							
						case 'expired':
							// 授权已到期：跳转到申请页面并显示到期状态
							if (auth.applyInfo) {
								uni.setStorageSync('authExpiredInfo', auth.applyInfo);
							}
							uni.reLaunch({ url: `/pages/applyAuth/applyAuth?imei=${encodeURIComponent(imei)}&expired=true` });
							break;
							
						case 'unauthorized':
						default:
							// 未授权：清理可能残留的本地状态并跳转到申请页面
							try {
								uni.removeStorageSync('authApplyInfo');
								uni.removeStorageSync('authExpiredInfo');
							} catch (e) {}
							uni.reLaunch({ url: `/pages/applyAuth/applyAuth?imei=${encodeURIComponent(imei)}&status=unauthorized` });
							break;
					}
				} catch (e) {
					console.warn('设备授权校验失败', e);
					uni.showToast({ title: '授权校验失败', icon: 'none' });
				}
			},
			// 监测是否传参数
			checkArguments() {
				try {
					if (uni.getSystemInfoSync().platform === 'android') {
						// 接收第三方app传递的参数 extra；
						// #ifdef APP-PLUS 
						if (plus.runtime.arguments) {
							// patParams: 院区，病区， 床号
							const {
								patParams
							} = JSON.parse(plus.runtime.arguments);
							console.log({
								patParams
							});
							uni.setStorageSync('patParams', patParams);
						}
						// #endif
					}
				} catch (e) {}
			},
			//角色和对应的跳转页面
			rolToTarget(nowPermission) {
				if (nowPermission != 0) {
					let current = this.rolList.find(item => item.permission == nowPermission);
					if (current) {
						// 页面跳转
						uni.redirectTo({
							url: `/${current.pagePath}`
						});
					}
				}
			}
		}
	};
</script>

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


	/* 条件编译，仅在H5平台生效 */
	// #ifdef H5
	body::-webkit-scrollbar,
	html::-webkit-scrollbar {
		display: none;
	}

	// #endif

	body,
	uni-app,
	uni-page,
	uni-page-wrapper,
	uni-page-body {
		height: 100%;
		font-size: 20rpx;
		line-height: 30rpx;
		color: #292C33;
		background-color: #F5F6FA;
	}

	view,
	label,
	scroll-view {
		box-sizing: border-box;
	}

	// 底部固定的按钮
	.fixed-buttom-btn {
		position: fixed;
		left: 0;
		bottom: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 12.5rpx;
		width: 100%;
		height: 75rpx;
		background-color: #3377FF;

		.btn-text {
			flex: 1;
			font-size: 22.5rpx;
			color: #fff;
			text-align: center;
		}

		.btn-text.cancle {
			line-height: 76.25rpx;
			background-color: #FFFFFF;
			color: #3377FF;
		}
	}

	// 新建情境样式start
	.creatingSituations {
		.title {
			padding-bottom: 35rpx;
			padding-left: 25rpx;
			font-size: 30rpx;
			line-height: 45rpx;
			color: #292C33;
		}
	}

	// 新建情境样式end
	// 查核地图列表样式start
	.check-map-list {
		overflow: hidden;
		padding: 0 25rpx;

		.item {
			position: relative;
			overflow: hidden;
			margin-bottom: 25rpx;
			border-radius: 5rpx;
			padding-top: 16.25rpx;
			padding-bottom: 0;
			width: 100%;
			background-color: #fff;
			box-shadow: 0 3.75rpx 12.5rpx 0 rgba(0, 13, 51, 0.1);

			.title-wrap {
				display: flex;
				flex-direction: row;
				align-items: center;
				padding: 0 25rpx;

				>text {
					font-size: 35rpx;
					line-height: 52.5rpx;
					font-weight: normal;
					color: #292C33;
				}

				>view {
					display: flex;
					flex-direction: row;
					align-items: center;
					margin-left: 20rpx;
					// border-radius: 17.5rpx;
					height: 35rpx;
					font-size: 17.5rpx;
					line-height: 35rpx;
					color: #8F9BB3;
					background-color: #EDF2FA;

					image {
						width: 35rpx;
						height: 35rpx;
					}

					text {
						padding-left: 10rpx;
						padding-right: 20rpx;
					}
				}
			}

			.content {
				display: flex;
				flex-direction: column;
				padding: 11.25rpx 25rpx 20rpx;

				>text {
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					font-size: 20rpx;
					line-height: 30rpx;
					color: #666F80;

					&:first-child {
						margin-bottom: 5rpx;
						font-weight: bold;
						color: #292C33;
					}
				}
			}
		}
	}

	// 查核地图列表样式end
</style>