<script>
	let uri = require('urijs');
	/**
	 * 用来处理从小程序拿到的参数
	 * */
	function getUrlParams(url) {
		try {
			// 通过 ? 分割获取后面的参数字符串
			let urlStr = url.split('?')[1]
			// 创建空对象存储参数
			let obj = {};
			// 再通过 & 将每一个参数单独分割出来
			let paramsArr = urlStr.split('&')
			for (let i = 0, len = paramsArr.length; i < len; i++) {
				// 再通过 = 将每一个参数分割为 key:value 的形式
				let arr = paramsArr[i].split('=')
				obj[arr[0]] = arr[1];
			}
			return obj
		} catch {
			return false
		}
	}
	import store from '@/store/index';
	import { HTTP_REQUEST_URL } from '@/config/app.js'
	import { mapMutations} from 'vuex'
	import { spread } from '@/request/restaurant/index.js'
	export default {
		globalData: {
			// FPT上传地址
			urlfileName:'https://jc.agrimedia.cn/discountt',
			parameters: {}
		},
		
		onLaunch: function(parameters = {}) {
			uni.setStorageSync('firstVisitUrlH5', location.href);
			
			// 动态构建script标签，用于引入wxjs文件
			var script = document.createElement('script');
			script.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
			document.body.appendChild(script);
			// 为适配旧版本项目代码中的取参逻辑此处为迭代后新版本传参并整合为旧版本参数格式
			let basurl = uri(decodeURIComponent(window.location.href))
			let querys = basurl.query(true);
			if (querys.token) {
				store.commit('SETTOKEN', 'Bearer ' + querys.token);
			}
			
			// 锁粉?后的
			if (querys.spread) {
				setTimeout(() => {
					spread({ puid: querys.spread, code: 0 }).then(res => {
						console.log(res)
					})
				}, 1000)
			};
			
			if(Object.keys(querys)['length'] > 0){
				if(querys?.para){
					console.log('正常登录')
					// 获取URL参数
					var _para = getUrlParams(window.location.href);
					console.log(_para,'_para');
					// 小程序首页会直接进入店铺首页,首页无赋值店铺信息逻辑所再次处进入之后赋值
					if(_para?.brand_id && typeof _para['brand_id'] != 'undefined' && typeof _para['brand_id'] != undefined &&  _para?.brand_name && typeof _para['brand_name'] != 'undefined' && typeof _para['brand_name'] != undefined){
						store.commit('shopping/SETBRANDINFOR', { brand_id: _para['brand_id'], brand_name:decodeURIComponent(_para['brand_name'])});
					};
					
					// 参数初始化处理
					if (typeof _para == 'object' && _para['para'] != undefined) {
						// URL参数
						var URLpara = decodeURIComponent(getUrlParams(window.location.href)['para']);
						try{
							// 转换过来的URL参数为一个JSON字符串其中存在一个#/字符，直接使用JSON.parse会报错，所以将#/截取出来
							var _r = URLpara.substr(0, URLpara.lastIndexOf("#/"));
							this['globalData']['parameters'] = JSON.parse(`${_r}`);
						}catch(e){
							this['globalData']['parameters'] = JSON.parse(URLpara);
							//TODO handle the exception
						}
						// 全局变量设置参数
						console.log(this['globalData']['parameters'],'----');
						// 合并其余参数
						const other = JSON.parse(JSON.stringify(_para,(key,val)=>{
							if(key === 'para') return undefined;
							return val;
						}))
						this['globalData']['parameters'] = {...this['globalData']['parameters'],...other};
					
					} else {
						console.log('没有参数')
					}
					
					alert(this['globalData']['parameters']['spread'], '获取1')
					this.SETSPREAD(this['globalData']['parameters']['spread']);
					// 分享者的参数
					// if (this['globalData']['parameters']['spread']) {
					// 	setTimeout(() => {
					// 		this.SETSPREAD(this['globalData']['parameters']['spread']);
					// 		spread({ puid: this['globalData']['parameters']['spread'], code: 0 }).then(res => {
					// 		})
					// 	}, 1000)
					// }
				}else{
					console.log('分享者的参数1997', !querys.token)
					console.log('登录token后存在的参数1997', querys)
					
					alert(querys.userinfor.spread, '获取2')
					// 分享者的参数
					if (querys.userinfor.spread) {
						setTimeout(() => {
							this.SETSPREAD(querys.userinfor.spread);
							spread({ puid: querys.userinfor.spread, code: 0 }).then(res => {
							})
						}, 1000)
					}
					
					if (!querys.token) {
						for(let key in querys){
							const value = querys[key];
							querys[key] = JSON.parse(value);
						}
					}
					
					this['globalData']['parameters'] = { ...querys['userinfor'], ...querys['query'], timestamp:querys['timestamp']};
					
					if (this['globalData']['parameters']['query']) {
						store.commit('shopping/SETBRANDINFOR', { brand_id: this['globalData']['parameters']['query']['brand_id'], brand_name:decodeURIComponent(this['globalData']['parameters']['query']['brand_name'])});
						store.commit('shopping/SETSHOPDETAIL', {
							city_name: this['globalData']['parameters'].cityInfor.city,
							is_open: 1,
							latitude: this['globalData']['parameters']['cityInfor'].lat,
							longitude: this['globalData']['parameters']['cityInfor'].lng,
							province_name: this['globalData']['parameters']['cityInfor'].province,
							regoin_name: null,
							restaurant_address: this['globalData']['parameters']['query'].restaurant_address,
							restaurant_id: this['globalData']['parameters']['query'].restaurant_id,
							restaurant_name: this['globalData']['parameters']['query'].restaurant_name,
							special: false,
							distance: this['globalData']['parameters']['query'].distance
						})
					}
					
					// 小程序首页会直接进入店铺首页,首页无赋值店铺信息逻辑所再次处进入之后赋值
					if(this['globalData']['parameters']?.brand_id){
						store.commit('shopping/SETBRANDINFOR', { brand_id: this['globalData']['parameters']['brand_id'], brand_name:decodeURIComponent(this['globalData']['parameters']['brand_name'])});
						// 设置店铺信息JIN
						store.commit('shopping/SETSHOPDETAIL', {
							city_name: this['globalData']['parameters'].cityInfor.city,
							is_open: 1,
							latitude: this['globalData']['parameters'].latitude,
							longitude: this['globalData']['parameters'].longitude,
							open_time: "07:00",
							province_name: this['globalData']['parameters'].cityInfor.province,
							regoin_name: null,
							restaurant_address: this['globalData']['parameters'].restaurant_address,
							restaurant_id: this['globalData']['parameters'].restaurant_id,
							restaurant_name: this['globalData']['parameters'].restaurant_name,
							special: false,
							distance: this['globalData']['parameters'].distance
						})
						store.commit('SETTOKEN', this['globalData']['parameters']['token']);
					};
				}
			};
			console.log(this['globalData']['parameters']['spread'],'测试取参');
			this.clearUrlParams();
			return;

			// 小程序进入H5逻辑
			/**
			 * 小程序进入H5会携带从小程序中获取到的部分参数(利用encodeURIComponent函数编码,所以接收是需要decodeURIComponent函数解码)
			 * {
			 * 	token
			 * 	isWechat
			 * 		lat
			 * 		lon
			 * 		city
			 * }
			 * 
			 * */
			// 解码
			// if (parameters['query']?.para)
			// 	this['globalData']['parameters'] = JSON.parse(decodeURIComponent(parameters['query']['para']));
			// console.log(this['globalData']['parameters'], 'globalData');
			

		},
		
		methods: {
			...mapMutations({
				SETSPREAD:'SETSPREAD',
				SETTOKEN: 'SETTOKEN'
			}),
			getParams(url) {
				const searchParams = new URLSearchParams(url.split("?")[1]);
				const params = {};
				for (const [key, value] of searchParams.entries()) {
					params[key] = value;
				}
				return params;
			},
			clearUrlParams() {
				// 存储分享链接
				let basurl = uri(decodeURIComponent(window.location.href))
				let querys = basurl.query(true);
				if (querys.token) return; // 从分享进入的
				
				for(let key in querys){
					querys[key] = JSON.parse(querys[key])
				}
				
				let parameters = { ...querys['userinfor'], ...querys['query']};
				parameters.token = '';
				console.log({...querys['query']}, '111111111111111111111111111111111111111')
				const safeDecode = (value) => {
				  if (value == null) return ''; // 默认空值
				  try {
				    return typeof value === 'string' ? decodeURIComponent(value) : value;
				  } catch {
				    return value; // 解码失败返回原值
				  }
				};
				const userinfor = {
				  cityInfor: {
				    lat: safeDecode(parameters.cityInfor.lat),
				    lng: safeDecode(parameters.cityInfor.lng),
				    city: safeDecode(parameters.cityInfor.address),
				    province: safeDecode(parameters.cityInfor.province),
				    adcode: safeDecode(parameters.cityInfor.adcode),
				  },
				  isWechat: true,
				  query: {...querys['query']}
				};
				
				let query = `userinfor=${encodeURIComponent(JSON.stringify(userinfor))}&timestamp=${Date.now()}`;
				uni.setStorageSync('SHARELINK', HTTP_REQUEST_URL +'/privilege/pages/restaurant/home/shop_home/shop_home?'+query);
				
				// 清除url
				// const url = new URL(window.location.href);
				// url.search = ''; // 移除所有查询参数
				// window.history.replaceState(null, '', url.href);
			}
		},
		
		onShow: function() {
			console.log('App Show');
			// 全局初始化参数中存在isWechat属性则代表就是从小程序跳入
			if (this['globalData']['parameters']?.isWechat) {
				store.commit('SetcityInfor', this['globalData']['parameters']['cityInfor']);
				if (getUrlParams(window.location.href)['token']) {  // 优先登录后token
					store.commit('SETTOKEN', decodeURIComponent(getUrlParams(window.location.href)['token']));
				} else if (this['globalData']['parameters']['token']) {  // 跳入token
					store.commit('SETTOKEN', this['globalData']['parameters']['token']);
				}
			} else {
				// 反之则代表从APP进入H5
				/**
				 * @获取用户位置信息
				 */
				// APP是由第三方开发,第三方开发文档中API-getLocation方法获取用户位置
				// 因为IOS端会跳进Safari浏览器,而Safari浏览器会提示getLocation方法不存在所以此处进行判断打断执行
				
				// 注释（不需要）
				// let isSafari = (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent));
				// console.log(isSafari, 'isSafari');
				// if (isSafari) return;
				// if (process.env.NODE_ENV !== 'development' && !this['globalData']['parameters']['isWechat']) {
				// 	getLocation().then(res => {
				// 		console.log(res, 'res');
				// 		store.commit('SetcityInfor', res);
				// 	});
				// }
			}
		},
		onHide: function() {
			console.log('App Hide')
		},
	}
</script>

<style lang="scss">
	@import 'uview-ui/theme.scss';
	@import "@/static/css/flex.css";
	@import "@/static/css/themeColor.scss";
	@import "@/static/css/icon/iconfont.css";
	*::-webkit-scrollbar {
	  display: none;
	}
	*::-webkit-scrollbar-horizontal {
	  display: none;
	}
	/*每个页面公共css */
	page {
		width: 100%;
		height: auto;
		min-height: 100%;
		position: relative;
		
	}
	
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	image {
		width: 100%;
		height: 100%;
	}

	uni-button:after {
		border: none !important;
	}

	// 点餐缺省样式
	.default {
		margin: auto;
		color: #999999;
		font-size: $FONTSIZE28;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 150rpx;

		.img {
			width: 160rpx;
			height: 132rpx;
			margin-bottom: 15rpx;
		}
	}
	@keyframes move {
	
		/* 开始状态 */
		0% {
			background-color: #f1f2f4;
		};
		
		50%{
			background-color: #E0E0E0;
		}
	
		/* 结束状态 */
		100% {
			background-color: #f1f2f4;
		}
	}
	
	.skeleton {
		width: 200rpx;
		height: 200rpx;
		animation-name: move;
		animation-duration: 0.5s;
	}
	/* 适配 iPhoneX */
	@supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
		.mescroll-safearea {
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
	}
	
</style>
