<script>
	// #ifdef APP-PLUS
	import {
		permissionListener
	} from './utils/permissionTips.js'
	// import { appUpdateListener } from '@/common/utils/appUpdateTips.js'
	import locationService from './utils/locationService.js'
	// import uploadApp from './utils/uploadApp.js'
	// #endif
	import request from './utils/request'
	import {
		setVersion
	} from './utils/version.js'
	//初始化一键登录插件
	const aLiSDKModule = uni.requireNativePlugin('AliCloud-NirvanaPns');
	export default {
		globalData: {
			artisanType: 2,
			latitude: '38.366667',
			longitude: '117.333333',
			address: '黄骅市',
			servers_region: `河北省-沧州市-黄骅市`,
			deviceid: '',
			addressRes: {
				"type": "gcj02",
				"altitude": 0,
				"latitude": 38.372266,
				"longitude": 117.332895,
				"speed": 0,
				"accuracy": 30,
				"adcode": "130983",
				"cCode": "130900",
				"pcode": "130000",
				"address": {
					"country": "中国",
					"province": "河北省",
					"city": "沧州市",
					"district": "黄骅市",
					"street": "渤海西路",
					"streetNum": "35号",
					// "poiName": "请开启位置权限",
					"poiName": "黄骅市人民政府",
					"cityCode": "0317",
					"adcode": "130983",
					"cCode": "130900",
					"pcode": "130000",
				}
			}
		},
		onLaunch: async function() {
			//缓存手机版本号
			// await setVersion()

			//获取访问路由
			// 发起 GET 请求
			let version = uni.getStorageSync('setVersion')
			let baseUrl
			await uni.request({
				url: 'https://api.mrrwlkj.top/api/openPuc/getSjApiUrl', // 接口地址
				method: 'GET', // 请求方法（默认 GET）
				header: {
					'Content-Type': 'application/json', // 请求头
					'VersionCode': version.VersionCode,
					'DeviceBrand': version.DeviceBrand,
					'DeviceType': version.DeviceType
				},
				success: (res) => {

					if (res.data.code == 200) {
						// #ifndef MP-WEIXIN
						uni.setStorageSync('baseUrl', res.data.data.url)
						// #endif
						// #ifdef MP-WEIXIN
						wx.setStorageSync('baseUrl', res.data.data.url)
						// #endif
						this.$store.commit("setLocation", true)
					}
					console.log('请求成功', res.data);
				},
				fail: (err) => {
					console.log('请求失败', err);
				},
				complete: () => {
					console.log('请求完成（无论成功失败都会执行）');
				}
			});

			// #ifdef APP-PLUS
			//禁止手机横屏
			plus.screen.lockOrientation("portrait-primary")
			// #endif
			// #ifdef APP-PLUS
			//权限提示监听
			let systemInfo = uni.getSystemInfoSync();
			let platform = systemInfo.platform;
			if (platform === 'android') {
				// console.log('安卓用户')
				permissionListener()
			} else if (platform === 'ios') {
				// console.log('苹果用户')
			} else {
				// console.log('平台未知')
			}

			//一键登录密钥设置
			let sdkInfo = '';
			//设置秘钥
			if (platform == 'android') {
				//开启SDK日志打印
				aLiSDKModule.setLoggerEnable(true);
				aLiSDKModule.expandAuthPageCheckedScope(true);
				//禁用物理返回键
				//aLiSDKModule.closeAuthPageReturnBack(true);
				//开启区分界面返回及物理返回功能，自动控制后续返回事件
				aLiSDKModule.userControlAuthPageCancel();
				//是否跟随系统深色模式
				aLiSDKModule.setAuthPageUseDayLight(false);
				sdkInfo =
					'cvJWYFO9s7xgJrzD+Ok2m2kCh3x0kdRkfJzGI0oxnyUXGlNAwAzvj87Yd6y030BWposVHUT84av2adBG9SdHl5CJpL0mGi+BRtachnyADJjfdpkJC0e0Uqb45pO7h7ZZvT+sNWQs1sa4JpL0U7hYKkgCP1iVXHoA1zKfzZynON6eKyvkzL1xpoPPag4O50slww4+6XuRVplCOSNCcsLRtot4CYnfsdcMvlV34MY5qB/rV+HNb1velpx4rg5atk3iTEiSLjla69c6pOT6vpjkK1qFVpNMxrEY';
			} else if (platform == 'ios') {
				sdkInfo =
					'BONXQSabNMt1a8Cru1TjeW94aXen5rQHeAxzLGgpFzIUicDYeb9SD0l35MkKvjq7gQemE2HDp6B7adKZ8nrdUk4wgg1LIYSGDYVSc/Q1CwrJ9A3lMUeBfS1UUu3nBBg58bDvG1bl3j6tS4h6FjnYmP5+dDsyqb0YNmIhlSmia5Et7cfBMv2OT85N9WLJc/tOMQ9ZQCnuizKVlofkmDGFgjsBN/Bf2gLq6lTQyVqsgPJE5yEPd4riNg=='
			}
			aLiSDKModule.setAuthSDKInfo(sdkInfo)



			// await uploadApp.uploadApp('onLaunch');
			// #endif


			console.log('App Launch')
			this.globalData.deviceId = uni.getDeviceInfo().deviceId;
			// this.globalData.deviceid = 'AC6F605124DFA87DCE40D5C062C94C3B';

			// #ifndef MP-WEIXIN
			if (uni.getStorageSync('refreshToken')) {
				let endTime = uni.getStorageSync('refresh_token_expries');
				endTime = new Date(endTime)
				// 当前系统时间
				var nowTime = new Date();
				var residueTime = (endTime.getTime() - nowTime.getTime() / 1000);
				// 4小时 14400
				if (residueTime < 4 * 60 * 60) {
					console.log('----------------------------')

					uni.removeStorageSync('accessToken')
					uni.removeStorageSync('refreshToken')
				}
			}
			// #endif
			// #ifdef MP-WEIXIN
			if (wx.getStorageSync('refreshToken')) {
				let endTime = wx.getStorageSync('refresh_token_expries');
				endTime = new Date(endTime)
				// 当前系统时间
				var nowTime = new Date();
				var residueTime = (endTime.getTime() - nowTime.getTime() / 1000);
				// 4小时 14400
				if (residueTime < 4 * 60 * 60) {
					console.log('----------------------------')

					wx.removeStorageSync('accessToken')
					wx.removeStorageSync('refreshToken')
				}
			}
			// #endif
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 验证登陆的全局方法
			verifyLogin() {
				if (!vuex.state.userInfo.token) {
					uni.showModal({
						title: '提示',
						content: '您需要登陆后才能进行此操作',
						confirmColor: '#F1AC66',
						success(e) {
							if (e.confirm) {
								// uni.oprPresentLogin()
								uni.navigateTo({
									url: '/pages/blogPopup/blogPopup'
								});
							}
						}
					})
				} else {
					return true
				}
			},
			/**
			 * 区/县adcode转换为6位市adcode（后两位补0）
			 * @param {string|number} districtAdcode - 6位区/县编码（字符串或数字类型）
			 * @returns {string|null} 6位市编码，无效编码返回null
			 */
			districtAdcodeTo6DigitCityAdcode(districtAdcode) {
				// 1. 统一转换为字符串并去除空格
				const adcodeStr = String(districtAdcode).trim();

				// 2. 验证编码有效性（6位数字）
				const adcodeReg = /^\d{6}$/;
				if (!adcodeReg.test(adcodeStr)) {
					console.warn('无效的区/县编码，必须是6位数字');
					return null;
				}

				// 3. 截取前4位 + 拼接"00" → 6位市编码
				const cityAdcode4Digit = adcodeStr.slice(0, 4);
				const cityAdcode6Digit = cityAdcode4Digit + '00';

				// 4. 可选验证：确保结果为6位数字
				if (!/^\d{6}$/.test(cityAdcode6Digit)) {
					console.warn('编码转换异常');
					return null;
				}

				return cityAdcode6Digit;
			},
			// 更新全局定位
			updateAddress(item) {
				console.log('item', item)
				let location = item.location.split(',');
				this.globalData.latitude = location[1];
				this.globalData.longitude = location[0];
				this.globalData.address = item.name;
				this.globalData.servers_region = `${item.pname}-${item.cityname}-${item.adname}`;
				this.globalData.pcode = item.pcode;
				this.globalData.cCode = this.districtAdcodeTo6DigitCityAdcode(item.adcode);
				this.globalData.adcode = item.adcode;
				//存储用户定位
				this.globalData.addressRes.latitude = location[1];
				this.globalData.addressRes.longitude = location[0];
				this.globalData.addressRes.address.province = item.pname;
				this.globalData.addressRes.address.city = item.cityname;
				this.globalData.addressRes.address.district = item.adname;
				this.globalData.addressRes.address.street = item.address;
				this.globalData.addressRes.address.poiName = item.name;
				this.globalData.addressRes.address.streetNum = '';
				this.globalData.addressRes.address.cityCode = '';
				this.globalData.addressRes.address.pcode = item.pcode;
				this.globalData.addressRes.address.cCode = this.districtAdcodeTo6DigitCityAdcode(item.adcode);
				this.globalData.addressRes.address.adcode = item.adcode;
				this.globalData.addressRes.pcode = item.pcode;
				this.globalData.addressRes.cCode = this.districtAdcodeTo6DigitCityAdcode(item.adcode);
				this.globalData.addressRes.adcode = item.adcode;
				console.log('globalData', this.globalData)
				uni.setStorageSync('userAdrees', this.globalData)
			},
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import '@/static/css/common.css';
</style>