<template>
	<view style="width: 100%;">
		<web-view id="webview" :src="state.url" style="width: 100%;"></web-view>
	</view>
</template>

<script setup>
	import {
		reactive
	} from 'vue'
	import {
		onShow,
		onHide,
		onUnload,
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getOrderInfo
	} from '@/api/video/index.js'
	const state = reactive({
		orderId: '',
		timer: null,
		timer1: null,
		ajaxNum: 0,
		url: null, //要打开的外部链接
		viewerUrl: '/hybrid/html/web/viewer.html',
		webviewStyles: {
			width: '750px',
			height: '100%',
		}
	})

	function getOrder() {
		getOrderInfo({
			orderId: state.orderId
		}).then(res => {
			console.log(res);
			if (res == 1) {
				uni.hideLoading()
				const sysInfo = uni.getSystemInfoSync();
				let isIos = sysInfo.platform == 'ios'
				uni.showToast({
					title: '支付成功',
					icon: 'none'
				})
				if (isIos) {
					uni.navigateBack()
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					state.timer1 = setTimeout(() => {
						uni.navigateBack()
					}, 500)
				}
			} else {

			}
			if (executionCount >= maxExecutions) {
				console.log(`已达到最大执行次数(${maxExecutions})，定时器停止`);
				uni.navigateBack()
				cleartimer()
			}
		});
	}

	function cleartimer() {
		console.log('cleartimer');
		uni.hideLoading()
		clearTimeout(state.timer)
		clearTimeout(state.timer1)
		state.timer = null
		state.timer1 = null
	}

	let runOnetime = 2000; // 初始间隔2秒
	let executionCount = 0; // 执行计数
	const maxExecutions = 5; // 最大执行次数

	function startDynamicTimer() {
		let lastExecutionTime = Date.now();
		function executeAndReschedule() {
			// 检查是否达到最大执行次数
			if (executionCount >= maxExecutions) {
				console.log(`已达到最大执行次数(${maxExecutions})，定时器停止`);
				uni.navigateBack()
				cleartimer()
				return;
			}
			const currentTime = Date.now();
			const elapsed = currentTime - lastExecutionTime;
			lastExecutionTime = currentTime;
			getOrder();
			// 增加计数
			executionCount++;
			console.log('executionCount',executionCount);
			// 计算新的间隔：在上一次间隔基础上增加2秒
			runOnetime += 2000;
			// 如果未达到最大次数，安排下一次执行
			console.log('executionCount < maxExecutions',executionCount < maxExecutions);
			console.log(executionCount , maxExecutions);
			if (executionCount < maxExecutions) {
				state.timer = setTimeout(executeAndReschedule, runOnetime);
			}
		}

		// 启动第一个定时器
		state.timer = setTimeout(executeAndReschedule, runOnetime);
	}

	onShow(() => {
		executionCount=0;
		// #ifdef APP
		uni.showLoading({
			title: '支付中'
		})
		// #endif
		runOnetime = 2000;
		getOrder()
		clearTimeout(state.timer)
		// 启动动态定时器
		startDynamicTimer();
	})
	onHide(() => {
		console.log('onHide');
		cleartimer()
		uni.hideLoading()
	})
	onUnload(() => {
		console.log('onUnload');
		cleartimer()
		uni.hideLoading()
		uni.hideLoading()
	})
	onLoad((option) => {
		state.url = option.url
		state.orderId = option.orderId
	})
</script>
<style lang="scss">
	.webview {
		width: 100%;
		height: 100%;
	}
</style>