
<script>
	import initApp from "@/util/router.js";
	import {interceptor} from "@/util/interceptor";
	import {baseURL,apiURL,cffpURL,companyInfo} from "@/environments/environment";
	import api from './api/api';
	import {hshare} from '@/util/fiveshare';
	
	export default {
		data() {
		        return {
		            invitationHandled: false ,// 在data中明确定义,
					dataToken:'',
		        }
		    },
		onLaunch: function() {
			console.log('App Launch');
			if(!uni.getStorageSync('loginType')){
				 uni.setStorageSync('loginType','visitor');
			}
			// 处理外部链接参数
			 this.handleExternalUrlParams();
			
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
				uni.getSystemInfo({
					success:(systemInfo)=> {
						uni.request({
						    url: `${apiURL}/appVersion/checkIsUpdate`,  
							method:'POST',
						    data: {  
						        appType: 1,  
						        version: wgtinfo.version,
								systemType:systemInfo.osName.toLowerCase() === 'ios' ? 2 : 1
						    },  
						    success: (result) => {
						        const data = result.data.data['appVersionInfo'];
								if (data.status==1 && data.isForceUpdate && data.wgtUrl) {
									    uni.downloadFile({  
									        url: `${baseURL}${data.wgtUrl}`,  
									        success: (downloadResult) => {  
									            if (downloadResult.statusCode === 200) {  
									                plus.runtime.install(downloadResult.tempFilePath, {  
									                    force: true  
									                }, function() {
									                    plus.runtime.restart();
									                }, function(e) {  
									                    console.error('install fail...');  
									                });  
									            }  
									        }  
									    });  
								} 
						    }  
						}); 
					}
				})
			})
			
		// #endif
			interceptor();
			initApp();
		},
		
		onShow: function(options) {
					console.log('App Show', options);
					// 每次进应用显示时检查用户状态
					 this.checkUserStatus();
					// App平台从options获取参数
					// #ifdef APP-PLUS
					if(options && options.query) {
						this.saveUrlParams(options.query);
					}
					// #endif
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			
			// 检查用户状态的方法  防止多端操作导致此用户不存在
			    async checkUserStatus() {
			        // 只有已登录用户才需要检查
			        if(uni.getStorageSync('loginType') == 'codelogin' && uni.getStorageSync('cffp_userId')) {
			            try {
			                const res = await api.queryInfo({userId: uni.getStorageSync('cffp_userId')});
			                if(!res['success']) {
			                    // 用户已注销，清除缓存
			                    this.clearLoginState();
			                    
			                    // 如果不是在白名单页面，跳转到登录页
			                    const pages = getCurrentPages();
			                    if(pages.length > 0) {
			                        const currentRoute = pages[pages.length - 1].route;
									console.log('currentRoute',currentRoute);
			                        const whiteList = [
			                        	'/myPackageA/login/login',
			                        	'/pages/invitationRegister/invitationlogin',
										'/myPackageA/applyFranchise/applyFranchise',
										'/pages/applyFranchise/applyFranchise',
										'/myPackageA/ruleAndContract/clause',
			                        	'/pages/courselist/courselist',
										'/pages/courseDetail/courseDetail',
										'/pages/orderDetail/orderDetail',
										'/pages/orderStatus/orderStatus',
			                        	'/pages/index/index',
										'/myPackageA/poster/poster',
			                        ] // 根据需要调整
			                        if(!whiteList.includes(currentRoute)) {
			                            uni.navigateTo({
			                                url: '/myPackageA/login/login'
			                            });
			                        }
			                    }
			                }
							if (res['success']) {
								delete res.data.commonResult
								const cffp_userInfo = {
									...res.data
								}
								uni.setStorageSync('cffp_userInfo', JSON.stringify(cffp_userInfo))
								
							}
			            } catch (err) {
			                console.error('检查用户状态失败:', err);
			            }
						return
			        }else {
						this.checkToken()
					}
			    },
			    // 清除登录状态
			    clearLoginState() {
			        // uni.clearStorageSync();
			        uni.setStorageSync('loginType', 'visitor');
					this.checkToken()
			        // 可以在这里添加其他需要清除的状态
			    },
				// 未登录状态下需要重新获取token
				checkToken(){
					api.checkToken().then(res=>{
						if(res['success']){}else{
							api.obtainToken().then(res=>{
								if(res.success){
									uni.setStorageSync('uni-token',res.data['token']);
								}
							})
						}
					})
				},
			// 处理外部链接参数
			handleExternalUrlParams() {
				// #ifdef H5
				this.handleH5UrlParams();
				// #endif
				
				// #ifdef APP-PLUS
				this.handleAppUrlParams();
				// #endif
			},
			
			// 处理H5平台的URL参数
			handleH5UrlParams() {
				const url = window.location.href;
				if(uni.getStorageSync('mpCffp')){
					uni.removeStorageSync('mpCffp')
				}
				
				if(url.indexOf('?') > -1) {
					const queryString = url.split('?')[1];
					const params = this.parseQueryString(queryString);
					this.saveUrlParams(params);
				}
				
			},
			
			// 处理App平台的URL参数
			handleAppUrlParams() {
				// 处理冷启动参数
				plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
					const args = plus.runtime.arguments;
					if(args) {
						const params = this.parseAppLaunchArgs(args);
						this.saveUrlParams(params);
					}
				});
				
				// 监听热启动事件
				plus.runtime.addEventListener('newintent', (e) => {
					const args = e.arguments;
					if(args) {
						const params = this.parseAppLaunchArgs(args);
						this.saveUrlParams(params);
					}
				});
			},
			
			// 解析H5的查询字符串
			parseQueryString(queryString) {
				const params = {};
				const pairs = queryString.split('&');
				for(let i = 0; i < pairs.length; i++) {
					const pair = pairs[i].split('=');
					if(pair.length === 2) {
						params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
					}
				}
				return params;
			},
			
			// 解析App启动参数
			parseAppLaunchArgs(args) {
				// 处理 scheme://path?key=value 格式
				if(args.indexOf('?') > -1) {
					const queryString = args.split('?')[1];
					return this.parseQueryString(queryString);
				}
				return {};
			},
			
			// 保存URL参数到本地存储
			saveUrlParams(params) {
				if(Object.keys(params).length > 0) {
					console.log('获取到外部链接参数:', params);
					
					// 使用uni.setStorageSync存储到本地
					try {
						//家办商城跳转登录状态下
						if(params.dataToken){
							// this.dataToken = params.dataToken
							uni.setStorageSync('dataToken',params.dataToken);
						}
						//家办商城跳转未登录状态下
						if(params.noLogin){
							uni.removeStorageSync('dataToken')
							uni.setStorageSync('loginType','visitor');
						}
						if(params.addSystemType){
							uni.setStorageSync('addSystemType', params.addSystemType);
						}
						// 家办商城跳转，分享带参
						if(params.mpCffp){
							uni.setStorageSync('mpCffp',params.mpCffp)
						}
					} catch(e) {
						console.error('存储外部链接参数失败:', e);
					}
				}
			}
		}
	}
</script>

<style>
	@import "@/static/font1/iconfont.css"; 
	@import "@/static/font/iconfont.css";
	
	/*每个页面公共css */
	@font-face {
		font-family: 'iconfont';
		src:url('data:application/x-font-woff2;charset=utf-8;base64,[encoded data, 13736 characters]')
	}
	.iconfont{
	    font-family:"iconfont" !important;
	    font-size:16px;
		font-style:normal;
	    -webkit-font-smoothing: antialiased;
	    -webkit-text-stroke-width: 0.2px;
	    -moz-osx-font-smoothing: grayscale;
	}
	image{
		width: 100%!important;
	}
	/* .container{
		background-color: rgba(235, 239, 247, 1);
		min-height: 100vh; 
		height: auto !important;
		height: 100vh;
	} */
	/* 全局基础样式 - 移动端优先 */
	.container {
	  background-color: rgba(235, 239, 247, 1);
	  min-height: 100vh; 
	  height: auto !important;
	  height: 100vh;
	  width: 100%;
	  max-width: 100%;
	  margin: 0 auto;
	  padding: 0;
	  box-sizing: border-box;
	  font-size: 28rpx;
	}
	
	/* 手机端默认样式 (小于768px) */
	/* @media (max-width: 767px) {
	  .container {
	  }
	} */
	
	/* 平板设备 (768px-1023px) */ 
	@media (min-width: 768px) and (max-width: 1023px) {
	  .container {
	    /* max-width: 100%; */
	  }
	  
	  /* iPad竖屏*/ 
	/* @media (orientation: portrait) {
	    .container {
	      max-width: 650px;
	    }
	  } */
	  
	  /* iPad横屏 */
	@media (orientation: landscape) {
	    .container {
	      max-width: 1024px;
		  display: flex;
		  align-items: center;
		  flex-direction: column;
	    }
	  }
	}
	
	/* 小桌面设备 (1024px-1279px) */
	@media (min-width: 1024px) and (max-width: 1279px) {
	  .container {
	    max-width: 1000px;
	  }
	}
	
	/* 大桌面设备 (1280px以上) */
	@media (min-width: 1280px) {
	  .container {
	    max-width: 1200px;
	  }
	}
	
	/* 特殊iPad Pro尺寸适配 */
	/* @media only screen 
	  and (min-device-width: 1024px) 
	  and (max-device-width: 1366px) 
	  and (-webkit-min-device-pixel-ratio: 2) {
	  .container {
	    max-width: 1100px;
	  }
	} */
	
	
	.uni-popup .uni-popup__wrapper{
		border-radius: 30rpx;
	}
	.richTextContent img{
		width: 100% !important;
	}
	.popupContainer .uni-popup .uni-popup__wrapper{
		/* width: 80%;
		border-radius: 20rpx; */
	}
	.container uni-slider{
		margin: 0;
	}
	.container uni-slider .uni-slider-value{
		text-align: right;
	}
	.noListTip{
		text-align: center;
		margin-top: 10%;
		color: #999;
	}
	.container uni-slider .uni-slider-value{
		width: 5ch;
	}
	.btn{
		background: #3671F4;
		color: #fff;
		width: 60%;
		margin: 0 auto;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
	}
	.uni-calendar-item--extra{
		white-space: nowrap !important;
	}
	.zuojiantou{
		display: inline-block;
		transform: rotate(180deg)!important;
		font-size: 30rpx;
		z-index: 1;
		position: absolute;
		left: 20rpx;
		width: 50rpx;
		height: 50rpx;
		text-align: center;
		line-height: 50rpx;
	}
	.iconStyle{
		color: rgba(51, 51, 51, 1);
		font-size: 28rpx;
	}
	.commonTitle{
		font-size: 30rpx;
	}
</style>
