<template>
	<scroll-view class="content-card" @click="handleStart" scroll-y="true" refresher-enabled="true"
		:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
		<!-- 轮播图背景 -->
		<swiper class="background-swiper" :indicator-dots="false" :autoplay="true" :interval="5000" :duration="500"
			:circular="true">
			<swiper-item v-for="(item, index) in adslist" :key="index">
				<image class="background-image" :src="item.image" mode="aspectFill"></image>
			</swiper-item>
		</swiper>

		<!-- 右上角设备信息按钮 -->
		<view class="device-info-btn" @click.stop="handleDeviceInfo">
			<text class="device-info-icon">ⓘ</text>
		</view>

		<!-- <view class="language" @click="handleLang" hover-class="hover_btn">
			<image class="lang-icon" src="/static/lang_icon.png" mode="aspectFill"></image>
			<text class="lang-text">{{ currentLangLabel }}</text>
		</view> -->
		<view @click.stop="handleQueue" hover-class="hover_btn" class="queue">
			<image class="queue-icon" src="/static/liebiao.png" mode="aspectFit" />
		</view>
		<button class="start-btn" hover-class="hover_btn" @click="handleStart">点击屏幕开始体验</button>
	</scroll-view>
	<Popuplang :visible="showLang" :closeOnOverlay="true" :languages="languageslist" v-model:modelValue="selectedLang"
		@close="showLang = false" @cancel="showLang = false" @confirm="onLangConfirm" />
	<PopupBind :Bindvisible="showBind" :closeOnOverlay="true" @close="showBind = false" @success="onBindSuccess" />
	<PopupDeviceInfo :visible="showDeviceInfo" :closeOnOverlay="true" :deviceInfo="machineInfo"
		@close="showDeviceInfo = false" />
	<AppUpgrade :visible="upgradeVisible" :close-on-overlay="true" :version-info="appVersionInfo"
		@close="upgradeVisible=false" />
	<PopupPrintList :visible="showQueueList" :closeOnOverlay="true" @close="showQueueList=false" />
</template>

<script setup lang="ts">
	import Popuplang from '../../components/Popup/Popuplang.uvue'
	import PopupBind from '../../components/Popup/PopupBind.uvue'
	import PopupDeviceInfo from '../../components/Popup/PopupDeviceInfo.uvue'
	import AppUpgrade from '../../components/Common/AppUpgrade.uvue'
	import PopupPrintList from '../../components/Popup/PopupPrintList.uvue'
	import { LanguageOption, AdsOption } from '../../types/index.uts'

	import { languages, getMachineApp, ads, type ResponseData } from '../../utils/reques.uts'

	// 弹窗相关
	const showLang = ref(false)
	const showBind = ref(false)
	const showDeviceInfo = ref(false)
	const upgradeVisible = ref<boolean>(false)
	const appVersionInfo = ref<UTSJSONObject | null>(null)
	const machineInfo = ref<UTSJSONObject | null>(null)
	const showQueueList = ref(false)
	// 设备信息按钮点击计数
	const deviceInfoClickCount = ref<number>(0)
	const deviceInfoClickTimer = ref<number | null>(null)

	const animationTimer = ref<number | null>(null)
	// 下拉刷新状态
	const refreshing = ref<boolean>(false)
	// 语言列表数据
	const languageslist = ref<Array<LanguageOption>>([])
	const selectedLang = ref<string>('zh-Hans')

	//获取轮播图广告
	const adslist = ref<Array<AdsOption>>([])

	// 设置默认广告图片
	const setDefaultAd = () => {
		const defaultAd : AdsOption = {
			image: '/static/index.png'
		}
		adslist.value = [defaultAd]
	}

	const getads = async () => {
		const params = {} as object
		try {
			const res = await ads(params) as ResponseData
			if (res.code as number == 0) {
				// 将 res.data 转换为数组以安全访问属性
				const dataArray = res.data as Array<UTSJSONObject>
				const adsItems : Array<AdsOption> = []

				const length = dataArray.length as number
				for (let i = 0; i < length; i++) {
					const item = dataArray[i] as UTSJSONObject
					const adsItem : AdsOption = {
						image: item.getString('content') ?? '',
					}
					adsItems.push(adsItem)
				}
				// 如果获取到广告数据，则使用，否则使用默认图片
				if (adsItems.length > 0) {
					adslist.value = adsItems
				} else {
					setDefaultAd()
				}
			} else {
				setDefaultAd()
			}
		} catch (error) {
			setDefaultAd()
		}
	}


	// 获取语言列表的方法
	const getLanguages = async () => {
		const params = {} as object
		try {
			const res = await languages(params) as ResponseData
			if (res.code as number == 0) {
				// 将 res.data 转换为 UTSJSONObject 以安全访问属性
				const dataObj = res.data as UTSJSONObject
				const dataArray = dataObj.getArray('list') as Array<any>
				const languageItems : Array<LanguageOption> = []

				for (let i = 0; i < dataArray.length; i++) {
					const item = dataArray[i] as UTSJSONObject
					const languageItem : LanguageOption = {
						label: item.getString('label') ?? '',
						value: item.getString('value') ?? ''
					}
					languageItems.push(languageItem)
				}
				languageslist.value = languageItems
			}
		} catch (error) {
			console.log('获取语言列表失败:', error)
		}
	}



	// 版本比较与展示判断（兼容纯数字或 x.y.z 格式）
	const isDigitsOnly = (s : string) : boolean => {
		if (s.length == 0) return false
		for (let i = 0; i < s.length; i++) {
			const ch = s.charCodeAt(i)
			if (ch != null && (ch < 48 || ch > 57)) return false
		}
		return true
	}

	const safeToNumber = (s : string) : number => {
		if (isDigitsOnly(s)) {
			return parseInt(s)
		}
		return 0
	}

	const splitVersion = (v : string) : Array<number> => {
		const parts = v.split('.')
		const nums : Array<number> = []
		for (let i = 0; i < parts.length; i++) {
			nums.push(safeToNumber(parts[i]))
		}
		return nums
	}

	const compareVersions = (a : string, b : string) : number => {
		// 若均为纯数字，直接比较大小
		if (isDigitsOnly(a) && isDigitsOnly(b)) {
			const ai = parseInt(a)
			const bi = parseInt(b)
			if (ai < bi) return -1
			if (ai > bi) return 1
			return 0
		}
		// 否则按 x.y.z 语义化比较
		const A = splitVersion(a)
		const B = splitVersion(b)
		const maxLen = A.length > B.length ? A.length : B.length
		for (let i = 0; i < maxLen; i++) {
			const ai = i < A.length ? A[i] : 0
			const bi = i < B.length ? B[i] : 0
			if (ai < bi) return -1
			if (ai > bi) return 1
		}
		return 0
	}

	const shouldShowUpgrade = (current : string, remote : string) : boolean => {
		if (remote.length == 0) return false
		if (current.length == 0) return true
		return compareVersions(current, remote) < 0
	}

	const getMachineinfo = async () => {
		const params = {} as object
		try {
			const res = await getMachineApp(params) as ResponseData
			if (res.code as number == 0) {
				// 将 res.data 转换为 UTSJSONObject 以安全访问属性
				const dataObj = res.data as UTSJSONObject
				// 保存完整的设备信息
				machineInfo.value = dataObj

				// 存储 is_direct_print 的 value
				if (dataObj.is_direct_print != null) {
					const isDirectPrintObj = dataObj.is_direct_print as UTSJSONObject
					const isDirectPrintValue = isDirectPrintObj.getNumber('value') ?? 0
					uni.setStorage({
						key: 'is_direct_print',
						data: isDirectPrintValue
					})
				}
				// 解析并传递版本信息给升级组件

				// #ifdef APP
				if (dataObj.app_version != null) {
					const appObj = dataObj.app_version as UTSJSONObject
					const remoteVersion = appObj.getString('version') ?? ''
					const downloadUrl = appObj.getString('download_url') ?? ''
					appVersionInfo.value = appObj
					// 读取当前应用版本
					const base = uni.getAppBaseInfo()
					const currentVersion = base.appVersion ?? ''
					if (remoteVersion.length > 0 && downloadUrl.length > 0) {
						if (shouldShowUpgrade(currentVersion, remoteVersion)) {
							upgradeVisible.value = true
						}
					}
				}
				// #endif
			}
		} catch (error) {
			console.log('获取机器信息失败:', error)
		}
	}

	// 队列执行函数 - 按顺序执行，如果某个失败则停止后续执行
	const executeQueue = async () => {
		try {
			// 1. 获取广告
			await getads()
			// 2. 获取机器信息
			await getMachineinfo()
			// 3. 获取语言列表
			await getLanguages()
		} catch (error) {
			console.log('队列执行失败:', error)
			throw error
		}
	}

	// 下拉刷新处理函数
	const onRefresh = async () => {
		refreshing.value = true
		try {
			await executeQueue()
		} catch (error) {
			console.log('刷新失败:', error)
		} finally {
			// 延迟关闭刷新状态，确保用户能看到刷新动画
			setTimeout(() => {
				refreshing.value = false
			}, 500)
		}
	}

	onLoad((event : OnLoadOptions) => {
		// 获取 URL 参数
		// 在 WEB 环境下处理 URL 参数
		// #ifdef WEB
		// 先设置默认广告，确保有内容显示
		if (event != null) {
			// 检查是否有 machine_code 参数
			const urlMachineCode = event['machine_code'] as string | null
			if (urlMachineCode != null && urlMachineCode != '') {
				// 将 URL 参数中的 machine_code 保存到缓存
				uni.setStorageSync('machine_code', urlMachineCode)
				executeQueue()
			} else {
				setDefaultAd()
		}
		}
		// #endif

		// uni.removeStorage({
		// 	key: 'machine_code',
		// 	success: function (res) {
		// 		console.log('success');
		// 	}
		// });

	})
	// #ifdef APP
	onShow(() => {
		// 每次进入页面都执行 getMachineinfo
		uni.removeStorageSync('selectedItem')

		const machine_code = uni.getStorageSync('machine_code')
		if (machine_code != null && machine_code != '') {
			executeQueue()
		} else {
			// 没有 machine_code 时显示默认广告
			setDefaultAd()
			showBind.value = true
		}
	})
	// #endif
	onUnmounted(() => {
		// 清理定时器
		const timer = deviceInfoClickTimer.value
		if (timer != null) {
			clearTimeout(timer)
			deviceInfoClickTimer.value = null
		}
	})

	const handleStart = () => {
		uni.navigateTo({
			url: '/pages/list/index',
			fail: (err) => {
				console.log('导航失败:', err)
			}
		})
	}

	const currentLangLabel = computed<string>(() => {
		let result : string = '简体中文'
		for (let i = 0; i < languageslist.value.length; i++) {
			const it : LanguageOption = languageslist.value[i]
			if (it.value == selectedLang.value) {
				result = it.label
				break
			}
		}
		return result
	})

	const handleLang = () => {
		showLang.value = true
	}

	const handleQueue = () => {
		showQueueList.value = true
	}

	const handleDeviceInfo = () => {
		// 增加点击计数
		deviceInfoClickCount.value++

		// 清除之前的定时器
		const timer = deviceInfoClickTimer.value
		if (timer != null) {
			clearTimeout(timer)
		}

		// 如果达到5次点击，打开设备信息弹窗
		if (deviceInfoClickCount.value >= 5) {
			showDeviceInfo.value = true
			deviceInfoClickCount.value = 0 // 重置计数
			deviceInfoClickTimer.value = null
			return
		}

		// 设置2秒后重置计数的定时器
		deviceInfoClickTimer.value = setTimeout(() => {
			deviceInfoClickCount.value = 0
			deviceInfoClickTimer.value = null
		}, 2000)
	}

	const onLangConfirm = (value : string) => {
		selectedLang.value = value
		showLang.value = false
	}

	// 绑定成功的处理函数
	const onBindSuccess = () => {
		// 绑定成功后重新获取机器信息和语言列表
		executeQueue()
	}
</script>

<style>
	.content-card {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.background-swiper {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	.background-image {
		width: 100%;
		height: 100%;
	}

	.device-info-btn {
		position: absolute;
		opacity: 0.05;
		top: 10rpx;
		right: 10rpx;
		width: 80rpx;
		height: 80rpx;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 9999rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	}

	.device-info-icon {
		font-size: 36rpx;
		color: #333333;
		font-weight: bold;
	}

	.language {
		position: absolute;
		top: 60rpx;
		right: 0;
		z-index: 2;
		height: 74rpx;
		padding: 0 10rpx;
		background: #FFFFFF;
		border-radius: 37rpx 0rpx 0rpx 37rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.lang-icon {
		margin: 0 10rpx;
		width: 34.72rpx;
		height: 35.42rpx;
	}

	.lang-text {
		font-weight: 400;
		font-size: 39rpx;
		color: #333333;
	}

	.queue {
		position: absolute;
		top: 300rpx;
		right: -15rpx;
		z-index: 2;
		height: 55rpx;
		width: 81rpx;
		padding: 0 10rpx;
		border-radius: 37rpx 0rpx 0rpx 37rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.queue-icon {
		width: 100%;
		height: 100%;
	}

	.start-btn {
		position: fixed;
		bottom: 20%;
		left: 50%;
		transform: translateX(-50%);
		width: 263.89rpx;
		height: 83.33rpx;
		background: linear-gradient(to bottom, #FD3C9F, #FCA7D3);
		font-family: Source Han Sans CN;
		font-weight: bold;
		font-size: 25rpx;
		color: #000000;
		line-height: 83.33rpx;
		border-radius: 20rpx;
		z-index: 2;
	}
</style>