<script setup lang="ts">
	import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
	import { onMounted, ref } from "vue";
	import { WebSocket } from '@/Service/Comm/TwWebSocket';
	import { Service } from "@/Service/Service"
	import { CNRiderOrderService } from '@/Service/CN/CNRiderOrderService'

	import { CNRiderLoginService } from "@/Service/CN/CNRiderLoginService";
	let isios = ref(false)

	const currentLatitude = ref(0);
	const currentLongitude = ref(0);

	let locationTimer : ReturnType<typeof setInterval> | null = null;


	onLaunch(() => {
		isios.value = uni.getSystemInfoSync().platform != 'ios'//是否为ios
		//#ifdef APP-PLUS//app
		if (isios.value) {
			getUpData()//更新
		}
		//#endif 
		// 在 App 启动时，立即初始化并建立 WebSocket 连接
		if (Service.GetUserIsLogin()) {
			WebSocket.ConnectSocketInit();
		}
		// 打开调用
		uni.$on("ImCom", () => {
			WebSocket.ConnectSocketInit();
			startFetchingLocation()
		})
		// 关闭调用
		uni.$on("ImComOff", () => {
			WebSocket.CloseSocket();
		})

	});
	onShow(() => {
		if (Service.GetUserIsLogin()) {
			startFetchingLocation()
			WebSocket.ConnectSocketInit();
		}
	});
	onHide(() => {
		stopFetchingLocation()
	});


	const startFetchingLocation = () => {
		// 安全检查：如果定时器已存在，先清除，防止重复启动
		if (locationTimer) {
			clearInterval(locationTimer);
		}

		// 1. 立即执行第一次获取
		getLocationNow();

		// 2. 设置定时器，每 60000 毫秒 (1分钟) 执行一次
		locationTimer = setInterval(() => {
			getLocationNow();
		}, 60000);
	};

	const getLocationNow = () => {
		console.log('重新定位');
		uni.getLocation({
			type: 'gcj02',
			altitude:true,
			isHighAccuracy: true,
			success: (res) => {
				console.log(res);
				if (Service.GetUserIsLogin()) {
					CNRiderOrderService.UpdateRiderLocation(res.longitude, res.latitude).then(data => { 
						if(data.code==0){
							console.log(data);
						}
					})
				}
			},
			fail: (err) => {
				console.error('获取经纬度失败:', err);
			}
		});
	};

	/**
	 * 停止定时获取位置
	 */
	const stopFetchingLocation = () => {
		if (locationTimer) {
			console.log('清楚计时器');
			clearInterval(locationTimer);
			locationTimer = null; // 清理 ID
		}
	};

	const getUpData = () => {
		plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
			CNRiderLoginService.GetAppVersion(wgtinfo.versionCode, 'Rider').then(res => {
				if (res.code == 0) {
					if (res.data.url !== '') {
						setTimeout(function () {
							Service.GoPage('/pages/index/upApp?url=' + res.data.url)
						}, 1000)
					}
				}
			})
		})

	}
</script>
<style lang="scss">
	@import "uview-plus/index.scss";
	@import "colorui/main.css";
	@import "colorui/icon.css";

	page {
		--nav-mian: #1890FF; //全局颜色
		--nav-vice: #52C41A; //副颜色
		--nav-diluted: #FF4D4F; //次颜色

	}
</style>