<script>
	// #ifdef APP-PLUS
	import {
		isNotificationsEnabled,
		permissions,
		registPush
	} from '@/utils/AS-NotifyTheAuthority.js'
	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: null,
			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() {
			// plus.android.requestPermissions(['POST_NOTIFICATIONS'], function(e) {
			// 		console.log('1111111111' + e.deniedAlways.length);
			// 	if (e.deniedAlways.length > 0) { //权限被永久拒绝
			// 		// 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
			// 		console.log('Always Denied!!! ' + e.deniedAlways.toString());
			// 	}
			// 	if (e.deniedPresent.length > 0) { //权限被临时拒绝
			// 		// 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
			// 		console.log('Present Denied!!! ' + e.deniedPresent.toString());
			// 	}
			// 	if (e.granted.length > 0) { //权限被允许
			// 		//调用依赖获取定位权限的代码
			// 		console.log('Granted!!! ' + e.granted.toString());
			// 	}
			// }, function(e) {
			// 	console.log('Request Permissions error:' + JSON.stringify(e));
			// });
	
			// #ifdef APP-PLUS
			if (uni.getStorageSync('accessToken')) {
				registPush()
			}
			// #endif

			//跟新底部消息数量
			this.messageUpudateNum()

			//隐藏原生Tabar
			uni.hideTabBar({
				animation: true
			});
			//缓存手机版本号
			// await setVersion()

			//获取访问路由
			// 发起 GET 请求
			let version = uni.getStorageSync('setVersion')
			let baseUrl
			await uni.request({
				url: 'https://app.mrrweb.com.cn/api/openPuc/getApiUrl', // 接口地址
				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 =
					'VXQhWWtyx6hqQIh6W8oMB2Kdzarg+2TSlQOvRb8fCUA1ygRWUKLsYkTuncn1VB1EK5gVvwoYZNXPF26x853cRzOfYW+lLKDNjMX7QZFgift8remIOFof9wjwyZFuHW2gBQAef6O6vxXeobInLVmJ/6sPqpJylk0ipYe+KBkEhKwiaNZudEHGrTFMQ2PvaNNjnnIWTB6WQJRTljArPvbgVT4FjXTwY8BJlFBR84CGE4k6HRRs1/ov1cBbON3zz6xE9DUlJhS43eEYVRYosJxrfDHfgz+++CfjinSGOX1m474=';
			} else if (platform == 'ios') {
				sdkInfo =
					'+4L59pm2xfA84cMIyUc4//tTAznhbtCGZ5bXa3Ax8UUTCH3IwxX0F0o8gVw7eanDoI3XVvriXMpQA3wcnAEbBD75JswXKAG0+ekz2cVUAgpHLGU3rDkakqTyRC9LIS4aHsJ/i9yv94tEAifXkxlIzdmZbT6dyYAexeJL6dLd6olEnFuKaaSRRl0VBtvSC5HQKlYqRZQ82ljIpAWCqaDG74lvsKfdxKU0wQPBQPzO15nJQOSfLIQpRsBm8STvkmeR'
			}
			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() {
			//隐藏原生Tabar
			uni.hideTabBar()
			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>