<template>
	<view class="camera-page" @touchstart="resetTimer">
		<PageHeader @back="handleBack">照片拍摄</PageHeader>
		<view class="card">
			<view class="frame">
				<text class="prompt" v-if="imageSrc == '' && !cameraInitializing">保持眼神注视镜头，身体静止状态</text>
				<text class="prompt" v-if="imageSrc == '' && cameraInitializing">相机初始化中，请稍候...</text>
				<view class="preview-host" style="height: 70%;" v-if="imageSrc == ''">
					<!-- #ifdef APP -->
					<camera :key="cameraPosition" class="camera" :device-position="cameraPosition" flash="off" mode="normal" resolution="high"
						frame-size="large" @stop="handleStop" @error="handleError" @initdone="handleInitDone"></camera>
					<image class="preview" src="/static/silhouette.png" mode="scaleToFill"></image>
					<view v-if="countdownVisible" class="countdown-overlay">
						<text class="countdown-number">{{ countdownNumber }}</text>
					</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<H5Camera ref="h5CameraRef" :imageSrc="imageSrc" @captured="handleH5Captured"
						@retake="handleH5Retake" />
					<!-- #endif -->
				</view>
				<view class="preview-host" style="height: 100%;" v-else>
					<view class="refresh-host" @click="retake">
						<image class="refresh-icon" src="/static/icon_refresh.png" mode="scaleToFill"></image>
					</view>
					<!-- 加载状态 -->
					<view v-if="imageLoading" class="loading-overlay">
						<image class="loading-gif" src="/static/waiting.gif" mode="aspectFit"></image>
						<text class="loading-text">加载中..</text>
					</view>
					<image class="captured" :src="imageSrc" mode="widthFix" @load="handleImageLoad" @error="handleImageError"></image>
				</view>
			</view>
			<view class="actions">
				<button class="btn secondary" v-if="imageSrc != '' && isDirectPrint == 1" hover-class="hover_btn"
					@click="print">打印原图</button>
				<button class="btn pick-primary" v-if="imageSrc == '' && !autoConfirmInProgress" hover-class="hover_btn"
					@click="confirm">拍照</button>
				<button class="btn" :class="isDirectPrint == 0 ? 'primary-full' : 'primary'" v-if="imageSrc != ''"
					hover-class="hover_btn" @click="submit">AI</button>
			</view>
		</view>
	</view>
	<PopupPrintov :visible="showPopupPrintov" />
	<CategorySelector :visible="showCategorySelector" @close="handleCategorySelectorClose" @select="handleCategoryProductSelect" />
</template>

<script setup lang="uts">
	import { ref } from 'vue'
	import PageHeader from '../../components/Common/PageHeader.uvue'
	import PopupPrintov from '../../components/Popup/PopupPrintov.uvue'
	import CategorySelector from '../../components/Common/CategorySelector.uvue'
	// #ifdef H5
	import H5Camera from '../../components/Common/H5Camera.uvue'
	// #endif
	import { ossUpload, type ResponseData } from '../../utils/reques.uts'
	import type { machineItems, categoryItem } from '../../types/globalData.uts'

	let cameraContext : CameraContext | null = null
	let inactivityTimer : number = 0
	const INACTIVITY_TIMEOUT = 3 * 60 * 1000 // 3分钟
	const imageSrc = ref<string>('')
	// 图片加载状态
	const imageLoading = ref<boolean>(false)
	// 倒计时显示控制
	const countdownVisible = ref<boolean>(false)
	const countdownNumber = ref<number>(5)
	let countdownTimerId : number | null = null
	// 首次进入时自动拍照进行中标记，用于隐藏“拍照”按钮
	const autoConfirmInProgress = ref<boolean>(false)
	// 相机初始化状态
	const cameraInitialized = ref<boolean>(false)
	const cameraInitializing = ref<boolean>(false)
	// 是否需要在初始化完成后自动拍照
	const needAutoCapture = ref<boolean>(false)
	// 是否需要镜像翻转（针对部分设备）
	const needMirror = ref<boolean>(false)
	// 摄像头位置（'front' 或 'back'）
	const cameraPosition = ref<string>('back')
	const showPopupPrintov = ref(false)
	const showCategorySelector = ref(false)
	const url = ref('')
	// 是否显示打印原图按钮（0: 不显示, 1: 显示）
	const isDirectPrint = ref<number>(0)
	// #ifdef H5
	const h5CameraRef = ref<InstanceType<typeof H5Camera> | null>(null)
	// #endif

	// 重置定时器 - 提前声明，供其他函数调用
	const resetTimer = () => {
		// 清除现有定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
		
		console.log('[camera] 重置无操作定时器，3分钟后自动退出')
		
		// 启动新的定时器
		inactivityTimer = setTimeout(() => {
			console.log('[camera] 3分钟无操作，自动跳转到首页')
			// 3分钟无操作，跳转到首页
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}, INACTIVITY_TIMEOUT)
	}

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

	const print = () => {
		// 打开分类选择器
		showCategorySelector.value = true
	}

	const handleStop = (e : UniCameraStopEvent) => {
	}

	const handleError = (e : UniCameraErrorEvent) => {
	}

	// 执行拍照（APP 原生）
	const doTakePhoto = () => {
		if (cameraContext == null) {
			cameraContext = uni.createCameraContext()
		}
		cameraContext?.takePhoto({
			quality: 'original',
			selfieMirror: needMirror.value, // 前置摄像头使用selfieMirror参数控制拍照结果是否镜像
			success: (res : CameraContextTakePhotoResult) => {
				console.log('拍照成功', res)
				const path = res.tempImagePath ?? ''
				imageSrc.value = path
				// 拍照成功后，先压缩图片
			},
			fail: (err : any) => {
				// 失败也结束自动流程，恢复按钮显示
				autoConfirmInProgress.value = false
			}
		} as CameraContextTakePhotoOptions)
	}

	// 开始5秒倒计时（内部逻辑）
	const startCountdown = () => {
		// 防重入
		if (countdownVisible.value) {
			return
		}
		countdownNumber.value = 5
		countdownVisible.value = true
		// 进入自动拍照流程，隐藏按钮
		autoConfirmInProgress.value = true
		if (countdownTimerId != null) {
			clearInterval(countdownTimerId as number)
			countdownTimerId = null
		}
		countdownTimerId = setInterval(() => {
			if (countdownNumber.value > 1) {
				countdownNumber.value = countdownNumber.value - 1
			} else {
				if (countdownTimerId != null) {
					clearInterval(countdownTimerId as number)
					countdownTimerId = null
				}
				countdownVisible.value = false
				doTakePhoto()
			}
		}, 1000) as number
	}

	const handleInitDone = (e : UniCameraInitDoneEvent) => {
		console.log('相机初始化完成')
		cameraInitialized.value = true
		cameraInitializing.value = false
		// 如果需要自动拍照，则在初始化完成后开始倒计时
		if (needAutoCapture.value) {
			needAutoCapture.value = false
			startCountdown()
		}
	}

	// 开始5秒倒计时，结束后拍照
	const confirm = () => {
		// #ifdef H5
		if (h5CameraRef.value) {
			// H5 触发组件内部倒计时与拍照
			h5CameraRef.value.startCountdown()
		}
		// #endif

		// #ifdef APP
		// 检查相机是否已初始化
		if (!cameraInitialized.value) {
			console.log('相机尚未初始化完成，等待初始化...')
			// 标记需要自动拍照，等待初始化完成后执行
			needAutoCapture.value = true
			autoConfirmInProgress.value = true
			return
		}

		startCountdown()
		// #endif
	}

	onReady(() => {
		// #ifdef APP
		cameraContext = uni.createCameraContext()
		cameraInitializing.value = true
		// 首次进入且没有传入图片时，标记需要自动拍照，等待相机初始化完成
		if (imageSrc.value == '' && autoConfirmInProgress.value) {
			needAutoCapture.value = true
		}
		// #endif

		// #ifdef H5
		// H5 端相机无需等待初始化，直接触发自动拍照
		if (imageSrc.value == '' && autoConfirmInProgress.value) {
			confirm()
		}
		// #endif
	})

	onLoad((event : OnLoadOptions) => {
		const incomingImageSrc = event["imageSrc"] ?? ""
		imageSrc.value = incomingImageSrc
		url.value = incomingImageSrc
		// 如果有传入图片，显示加载状态
		if (incomingImageSrc != '') {
			imageLoading.value = true
		}
		// 读取 is_direct_print 的值
		const storedValue = uni.getStorageSync('is_direct_print')
		if (storedValue != null) {
			isDirectPrint.value = storedValue as number
		}
		// 首次进入时，如果没有初始图片则隐藏拍照按钮并准备自动拍照
		if (imageSrc.value == '') {
			autoConfirmInProgress.value = true
		} else {
			autoConfirmInProgress.value = false
		}
		
		// 从缓存读取镜像设置和摄像头位置
		const storedMirror = uni.getStorageSync('cameraMirror')
		const storedPosition = uni.getStorageSync('cameraPosition')
		
		// 处理 storedMirror 可能是字符串的情况
		if (storedMirror != null) {
			if (typeof storedMirror == 'boolean') {
				needMirror.value = storedMirror as boolean
			} else if (typeof storedMirror == 'string') {
				needMirror.value = (storedMirror as string) == 'true'
			} else {
				needMirror.value = false
			}
		} else {
			needMirror.value = false
		}
		cameraPosition.value = storedPosition != null ? storedPosition as string : 'back'
		
		console.log('摄像头镜像状态:', needMirror.value)
		console.log('摄像头位置:', cameraPosition.value)
		
		// 启动无操作定时器
		resetTimer()
	})

	onUnload(() => {
		if (countdownTimerId != null) {
			clearInterval(countdownTimerId as number)
			countdownTimerId = null
		}
		// 清除无操作定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
	})

	const retake = () => {
		imageSrc.value = ''
		// 重拍时标记需要自动拍照
		autoConfirmInProgress.value = true
		needAutoCapture.value = true
		// #ifdef H5
		if (h5CameraRef.value) {
			h5CameraRef.value.retake()
			// H5 端直接触发倒计时
			setTimeout(() => {
				confirm()
			}, 100)
		}
		// #endif
		// #ifdef APP
		// 重拍时重新从缓存读取，确保使用正确的摄像头位置
		const storedMirror = uni.getStorageSync('cameraMirror')
		const storedPosition = uni.getStorageSync('cameraPosition')
		
		// 处理 storedMirror 可能是字符串的情况
		if (storedMirror != null) {
			if (typeof storedMirror == 'boolean') {
				needMirror.value = storedMirror as boolean
			} else if (typeof storedMirror == 'string') {
				needMirror.value = (storedMirror as string) == 'true'
			} else {
				needMirror.value = false
			}
		} else {
			needMirror.value = false
		}
		cameraPosition.value = storedPosition != null ? storedPosition as string : 'back'
		
		// 重拍时重新初始化相机上下文，确保后续拍照正常
		cameraContext = uni.createCameraContext()
		cameraInitialized.value = false
		cameraInitializing.value = true
		// 相机初始化完成后会自动触发倒计时（通过 needAutoCapture 标记）
		// #endif
	}

	const submit = () => {
		// 跳转到其他页面前清除定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
		// 对 imageSrc 进行 URL 编码，防止特殊字符影响 URL 解析
		const encodedImageSrc = encodeURIComponent(imageSrc.value)
		uni.navigateTo({
			url: '/pages/gener/index?imageSrc=' + encodedImageSrc
		})
	}

	// 关闭分类选择器
	const handleCategorySelectorClose = () => {
		showCategorySelector.value = false
	}

	// 处理分类选择器中的商品选择
	const handleCategoryProductSelect = async (product : any) => {
		console.log('[camera] 选中商品:', product)
		showCategorySelector.value = false
		
		// 跳转到其他页面前清除定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
		
		// 上传图片到OSS（如果还未上传）
		let uploadedUrl = url.value
		if (uploadedUrl == '') {
			try {
				const response = await ossUpload(imageSrc.value) as ResponseData
				if (response.code == 0 && response.data != null) {
					const data = response.data as UTSJSONObject
					const file = data.getAny('file') as UTSJSONObject | null
					uploadedUrl = file?.getString('url') ?? ''
					url.value = uploadedUrl
					console.log('[camera] 图片上传成功:', uploadedUrl)
				} else {
					console.error('[camera] 图片上传失败:', response.message)
					uni.showToast({
						title: '图片上传失败',
						icon: 'none'
					})
					return
				}
			} catch (e) {
				console.error('[camera] 图片上传异常:', e)
				uni.showToast({
					title: '图片上传异常',
					icon: 'none'
				})
				return
			}
		}
		
		// 将商品数据通过 URL 参数传递到打印页面
		const productData = encodeURIComponent(JSON.stringify(product))
		uni.navigateTo({
			url: '/pages/print/index?imageSrc=' + encodeURIComponent(uploadedUrl) + '&productData=' + productData
		})
	}



	// H5 拍照回调
	const handleH5Captured = (dataUrl : string) => {
		imageSrc.value = dataUrl
		// 结束自动拍照流程
		autoConfirmInProgress.value = false
	}

	// H5 重拍回调
	const handleH5Retake = () => {
		imageSrc.value = ''
		// 重拍时恢复按钮显示
		autoConfirmInProgress.value = false
	}

	// 图片加载完成
	const handleImageLoad = () => {
		imageLoading.value = false
	}

	// 图片加载失败
	const handleImageError = () => {
		imageLoading.value = false
	}
</script>

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

	.gradient-header {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding: 0 36rpx;
		padding-top: 56rpx;
		height: 410rpx;
		background: linear-gradient(to bottom, #FC81C0, #FFFFFF);
	}

	.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;
	}


	.header-title {
		font-weight: bold;
		font-size: 25rpx;
		color: #000000;
	}

	.card {
		position: absolute;
		top: 114rpx;
		bottom: 0;
		left: 0;
		right: 0;
		margin: 32rpx;
		background: #f6f4f4;
		border-radius: 28rpx;
		padding: 20rpx 20rpx 56rpx 20rpx;
		z-index: 0;
	}

	.prompt {
		font-size: 22rpx;
		color: #666666;
		text-align: center;
		padding-top: 50rpx;
	}


	.frame {
		position: relative;
		width: 100%;
		height: 90%;
		border-radius: 24rpx;
		overflow: hidden;
		background: #f6f4f4;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 40rpx;
		flex-direction: column;
		justify-content: flex-start;
		align-items: stretch;
	}

	.preview-host {
		position: relative;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: auto;
		margin-bottom: auto;
		align-self: center;
		justify-content: center;
		align-items: center;
	}

	.camera {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		/* transform: scale(1.2); */
	}
	
	/* 修复部分设备镜像问题 */
	.camera-mirror {
		transform: scaleX(-1);
	}

	.captured {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
	}

	.refresh-host {
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		width: 32rpx;
		height: 32rpx;
		background: #FFFFFF;
		border-radius: 26rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;
	}

	.refresh-icon {

		width: 16rpx;
		height: 16rpx;

	}

	.preview {
		position: relative;
		width: 506rpx;
		height: 560rpx;
		pointer-events: none;
	}

	.countdown-overlay {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;
	}

	.countdown-number {
		font-weight: bold;
		font-size: 180rpx;
		color: #FFFFFF;
	}

	.loading-overlay {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: rgba(246, 244, 244, 0.9);
		z-index: 5;
	}

	.loading-gif {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 20rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666666;
	}


	.actions {
		/* margin-top: 100rpx; */
		display: flex;
		flex-direction: row;
		justify-content: center;
	}

	.btn {
		border-radius: 16rpx;
		font-size: 28rpx;
	}

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

	.pick-primary {
		width: 381rpx;
		height: 83rpx;
		background: #FD3DA0;
		border-radius: 14rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		font-size: 24rpx;
		color: #FFFFFF;
		border: none;
		line-height: 83rpx;
	}

	.primary {
		width: 181rpx;
		height: 83rpx;
		background: #FD3DA0;
		border-radius: 14rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		font-size: 24rpx;
		color: #FFFFFF;
		border: none;
		line-height: 83rpx;
	}

	.primary-full {
		width: 381rpx;
		height: 83rpx;
		background: #FD3DA0;
		border-radius: 14rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		font-size: 24rpx;
		color: #FFFFFF;
		border: none;
		line-height: 83rpx;
	}
</style>