<template>
	<view class="camera-page" :style="{ 'background-color': goods_design_color }" @touchstart="resetTimer">
		<view class="back-header">
			<view class="btn-back">
				<view class="back-btn" hover-class="hover_btn" @click="handleBack">
					<image class="back-icon" src="/static/icon_back.png" mode="aspectFill"></image>
				</view>
				<text class="title-line">确认打印</text>
				<button style="width: 50rpx;"></button>
			</view>
		</view>
		<text class="prompt">{{goods_name}}</text>

		<view class="card">
			<!-- 展示传入的图片预览 -->
			<image class="goods_image" :style="infoStyle" :src="goods_front_image" mode="aspectFit" />
			<image :style="infoStyle" :src="imageSrc" mode="aspectFit" />
		</view>
		<view class="actions">
			<image class="loading" style="height:30rpx;width:50%" v-if="statusValue == 'waiting'"
				src="/static/waiting.gif" mode="aspectFit" />
			<image class="loading" v-else-if="statusValue == 'printing'" src="/static/icon_printing.gif"
				mode="aspectFit" />
			<image class="loading" v-else-if="statusValue == 'completed'" src="/static/Complete.gif" mode="aspectFit" />
			<image class="loading" v-else src="/static/canceled.png" mode="aspectFit" />

			<text class="printing" v-if="statusValue == 'waiting'">作品已生成，如需打印请联系工作人员
			</text>
			<text class="printing" v-else-if="statusValue == 'printing'">作品打印中...</text>
			<text class="printing" v-else-if="statusValue == 'completed'">作品已打印，请及时取货</text>
			<text class="printing" v-else>打印已取消</text>

			<view class="take-photo-btn" hover-class="hover_btn" @click="handleOpenShare">
				<image class="take-photo-icon" src="/static/icon_print.png" /><text class="take-photo-text">分享</text>
			</view>
		</view>
	</view>
	<PrintShare :visible="showPrintShare" title="分享作品" :worksId="worksId"
		@update:visible="onPrintShareVisibleChange" />
	<PopupConfirm :visible="showPopup" :title="popupTitle" :content="popupContent" :showCancel="false"
		@confirm="onPopupConfirm" @cancel="onPopupCancel" />
</template>
<script setup lang="uts">
	import { ref, computed } from 'vue'
	import PageHeader from '../../components/Common/PageHeader.uvue'
	import PopupPrinting from '../../components/Popup/PopupPrinting.uvue'
	import PopupPrintov from '../../components/Popup/PopupPrintov.uvue'
	import PrintShare from '../../components/Common/PrintShare.uvue'

	import { createorder, print, queryStatus } from '../../utils/reques.uts'
	import type { ResponseData } from '../../utils/reques.uts'
	
	let inactivityTimer : number = 0
	const INACTIVITY_TIMEOUT = 6 * 60 * 1000 // 6分钟
	
	const imageSrc = ref('');   //展示图片
	const worksId = ref(0) //作品id
	const orderId = ref(0) //订单id
	const goods_front_image = ref('') //模板设计图
	const goods_name = ref('')
	const goods_design_color = ref('')

	const showPrintShare = ref(false)
	const showPopup = ref(false)
	const popupTitle = ref('提示')
	const popupContent = ref('')
	const screenWidth = ref(0)
	const imageWidth = ref(0)
	const imageHeight = ref(0)
	const statusValue = ref('waiting') // 打印状态：waiting(等待), printing(打印中), completed(完成)

	// 接收的 creatework 返回对象（来自上一页）
	const incomingWork = ref<UTSJSONObject | null>(null)

	// 重置定时器 - 提前声明，供其他函数调用
	const resetTimer = () => {
		// 清除现有定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
		
		// 启动新的定时器
		inactivityTimer = setTimeout(() => {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}, INACTIVITY_TIMEOUT)
	}

	const handleOpenShare = () => {
		resetTimer() // 用户点击分享时重置定时器
		showPrintShare.value = true
	}

	const onPrintShareVisibleChange = (v : boolean) : void => {
		resetTimer() // 分享弹窗状态变化时重置定时器
		showPrintShare.value = v
	}

	// 全局轮询取消标志，页面关闭或跳转时停止轮询
	let pollCancelled : boolean = false

	// 轮询定时器ID
	let pollTimer : number | null = null

	// 完成弹窗自动关闭定时器（5秒）
	let printovAutoCloseTimer : number | null = null

	// 错误处理定时器
	let errorAutoCloseTimer : number | null = null

	const clearPollTimer = () : void => {
		if (pollTimer != null) {
			clearTimeout(pollTimer as number)
			pollTimer = null
		}
	}

	const clearErrorAutoClose = () : void => {
		if (errorAutoCloseTimer != null) {
			clearTimeout(errorAutoCloseTimer as number)
			errorAutoCloseTimer = null
		}
	}

	// 清理所有定时器的统一函数
	const cleanupAllTimers = () : void => {
		// 清除无操作定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
		// 停止轮询
		pollCancelled = true
		clearPollTimer()
		clearErrorAutoClose()
	}

	const onPopupConfirm = () : void => {
		showPopup.value = false
		// 跳转前清除所有定时器
		cleanupAllTimers()
		// 跳转到首页
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}

	const onPopupCancel = () : void => {
		showPopup.value = false
		// 跳转前清除所有定时器
		cleanupAllTimers()
		// 跳转到首页
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}

	// 轮询配置：间隔与最长等待时间（毫秒）
	const POLL_INTERVAL_MS : number = 5000 //每隔 5 秒会调用一次轮询查询
	const MAX_POLL_TIME_MS : number = 360000 // 最长轮询6分钟

	// 安全延时函数（UTS严格类型）- 使用可清理的定时器
	const delay = (ms : number) : Promise<void> => {
		return new Promise<void>((resolve) => {
			pollTimer = setTimeout(() : void => {
				pollTimer = null
				resolve()
			}, ms)
		})
	}

	// 轮询订单状态：waiting -> printing -> completed/canceled
	const pollOrderStatus = async (order_id : number) : Promise<void> => {
		let elapsed : number = 0
		// 打开“打印中”弹窗

		while (pollCancelled == false && elapsed < MAX_POLL_TIME_MS) {
			const queryRes : ResponseData = await queryStatus({ order_id: order_id }) as ResponseData
			console.log('queryStatus result', queryRes)
			if (queryRes.code != 0) {
				throw new Error(queryRes.message)
			}
			const dataObj = queryRes.data as UTSJSONObject
			// 从嵌套的 status 对象中获取 value
			const statusObj = dataObj.getJSON('status') as UTSJSONObject | null
			const currentStatus : string = statusObj != null ? (statusObj.getString('value') ?? '') : ''
			console.log('statusValue', currentStatus)

			// 更新状态值，触发图片变化
			statusValue.value = currentStatus
			console.log('statusValue updated to:', statusValue.value)

			// 根据返回值切换UI与逻辑
			if (currentStatus == 'waiting' || currentStatus == 'printing') {
				// 等待/打印中：维持打印中弹窗显示
			} else if (currentStatus == 'completed') {
				// 完成：关闭打印中，显示完成弹窗，停止轮询
				pollCancelled = true
				return
			} else if (currentStatus == 'canceled') {
				pollCancelled = true
				popupTitle.value = '提示'
				popupContent.value = '打印已取消'
				showPopup.value = true
				console.log('打印已取消，弹窗状态:', showPopup.value)
				return
			} else {
			}

			await delay(POLL_INTERVAL_MS)
			elapsed = elapsed + POLL_INTERVAL_MS
		}
		throw new Error('打印超时，请稍后重试')
	}

	const handleBack = () => {
		// 用户主动返回，清除所有定时器
		cleanupAllTimers()
		uni.reLaunch({
			url: '/pages/list/index'
		})
	}

	// 打印确认处理函数（基于传入的 order_id 执行打印并轮询）
	const handlePrint = async () => {
		try {
			const printRes : ResponseData = await print({ order_id: orderId.value }) as ResponseData
			console.log('print result', printRes)
			if (printRes.code != 0) {
				throw new Error(printRes.message)
			}
			// 轮询查询订单状态（waiting/printing -> completed/canceled）
			await pollOrderStatus(orderId.value)
		} catch (e) {
			console.log('打印错误:', e)
			popupTitle.value = '提示'
			const errorMsg = (e as Error).message
			console.log('错误消息:', errorMsg)
			popupContent.value = errorMsg.length > 0 ? errorMsg : '打印失败，请联系管理员'
			showPopup.value = true
			console.log('弹窗状态:', showPopup.value, '内容:', popupContent.value)
		}
	}

	const initDeviceInfo = () => {
		const systemInfo = uni.getSystemInfoSync()
		screenWidth.value = systemInfo.screenWidth as number
		console.log('[CroppImage] 设备信息初始化完成:', systemInfo.screenWidth)

		// 获取图片的实际宽高
		if (imageSrc.value.length > 0) {
			uni.getImageInfo({
				src: imageSrc.value,
				success: (res) => {
					imageWidth.value = res.width
					imageHeight.value = res.height
					console.log('[printlist] 图片尺寸:', res.width, res.height)
				},
				fail: (err) => {
					console.error('[printlist] 获取图片信息失败:', err)
				}
			})
		}
	}

	const infoStyle = computed(() => {
		if (imageWidth.value == 0 || imageHeight.value == 0) {
			return {
				width: '0px',
				height: '0px'
			}
		}
		const newsizewidth = (screenWidth.value / imageWidth.value) * imageWidth.value * 0.51
		const aspectRatio = imageHeight.value / imageWidth.value
		const newsizeheight = newsizewidth * aspectRatio
		return {
			width: `${newsizewidth}px`,
			height: `${newsizeheight}px`
		}
	})

	// 页面卸载时，清理所有定时器并停止轮询
	onUnload(() : void => {
		cleanupAllTimers()
	})
	
	onLoad((event : OnLoadOptions) => {
		const workStr : UTSJSONObject = JSON.parseObject(event["work"] ?? '{}') as UTSJSONObject
		console.log('workStr', workStr)

		// 解析并赋值数据
		imageSrc.value = workStr.getString('image') ?? ''
		worksId.value = workStr.getNumber('works_id') ?? 0
		orderId.value = workStr.getNumber('order_id') ?? 0

		const goods : UTSJSONObject | null = workStr.getJSON('goods')
		if (goods != null) {
			goods_name.value = goods.getString('name') ?? ''
			goods_front_image.value = goods.getString('front_image') ?? ''
			goods_design_color.value = goods.getString('design_color') ?? ''
		}

		initDeviceInfo()
		handlePrint()
		
		// 启动无操作定时器
		resetTimer()
	})
</script>

<style>
	.camera-page {
		height: 100%;
	}

	.back-header {
		padding: 0 38rpx;
		padding-top: 33rpx;
		position: relative;
		z-index: 2;
	}

	.btn-back {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.title-line {
		font-weight: bold;
		font-size: 25rpx;
		color: #666666;
	}

	.back-btn {
		width: 50rpx;
		height: 50rpx;
		border-radius: 25rpx;
		background-color: rgba(255, 255, 255, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.back-icon {
		width: 45rpx;
		height: 45rpx;
	}

	.card {
		position: relative;
		height: 70%;
		margin-top: 30rpx;
		border-radius: 53rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.goods_image {
		position: absolute;
		z-index: 999;
	}


	.loading {
		width: 100rpx;
		height: 90rpx;
	}

	.printing {
		font-size: 28rpx;
		color: #fd3da0;
		text-align: center;
	}

	.prompt {
		font-size: 22rpx;
		color: #666666;
		text-align: center;
		margin: 20rpx 0;
	}

	.card-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}


	.cropping-area {
		margin-top: 50rpx;
	}


	.actions {
		position: fixed;
		bottom: 60rpx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}


	.btn {
		width: 180rpx;
		height: 80rpx;
		border-radius: 16rpx;
		font-size: 28rpx;
	}

	.primary {
		width: 181rpx;
		height: 83rpx;
		background: #FFFFFF;
		border-radius: 14rpx;
		border: 2rpx solid #FF86C3;
		font-weight: bold;
		font-size: 24rpx;
		color: #000000;
		margin-right: 20rpx;
		line-height: 83rpx;
	}

	.pickprimary {
		margin-top: 51rpx;
		width: 657rpx;
		height: 97rpx;
		background: #FD3DA0;
		border-radius: 14rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		font-size: 24rpx;
		color: #FFFFFF;
		border: none;
		line-height: 97rpx;
	}

	.take-photo-btn {
		width: 657rpx;
		height: 97rpx;
		background: #FD3DA0;
		border-radius: 14rpx;
		flex-direction: row;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		margin: 0 auto;
		margin-top: 51rpx;
	}

	.take-photo-icon {
		margin-right: 20rpx;
		width: 29.86rpx;
		height: 27.08rpx;
	}

	.take-photo-text {
		font-weight: bold;
		font-size: 28rpx;
		color: #FFFFFF;
	}
</style>