<template>
	<view class="camera-page" :style="{ 'background-color': design_color }" @touchstart="resetTimer">
		<view class="card">
			<view class="back-header" :style="{ visibility: isEditing ? 'hidden' : 'visible' }">
				<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>
					<view class="back-reset-btn" hover-class="hover_btn" @click="handleChangereset">
						<image class="back-reset-icon" src="/static/icon_refresh.png" />
						<text class="back-reset-text">重置</text>
					</view>
				</view>
			</view>
			<view class="replace" @click.stop="handleChangeProduct" hover-class="hover_btn"
				:style="{ visibility: isEditing ? 'hidden' : 'visible' }">
				<text class="replace-text">更换商品</text>
			</view>
			<!-- 纪念币裁剪区域 -->
			<text class="prompt" :style="{ visibility: isEditing ? 'hidden' : 'visible' }">拖动作品，可调整打印区域</text>
			<CroppImage ref="CroppImageRef" :avatar="imageSrc" :sizewidth="sizewidth" :sizeheight="sizeheight"
				@cropData="handleCropData" :isCropping="Cropping" :categoryValue="category_value" :fixturebg="Fixturebg"
				@editingChange="handleEditingChange" />
		</view>
		<view class="actions" :style="{ visibility: isEditing ? 'hidden' : 'visible' }">
			<view class="take-photo-btn" hover-class="hover_btn" @click="handlePrint">
				<image class="take-photo-icon" src="/static/icon_print.png" /><text class="take-photo-text">打印</text>
			</view>
		</view>
	</view>
	<PopupPrinting :visible="showPopupPrinting" printText="处理中..." />
	<PopupConfirm :visible="showConfirmBack" title="温馨提示" content="作品已生成，请确认是否退出？" confirmText="确定" cancelText="取消"
		@confirm="handleConfirmBack" @cancel="handleCancelBack" />
	<CategorySelector :visible="showCategorySelector" @close="handleCategorySelectorClose" @select="handleCategoryProductSelect" />
</template>
<script setup lang="uts">
	import { ref } from 'vue'
	import PageHeader from '../../components/Common/PageHeader.uvue'
	import CroppImage from '../../components/Common/CroppImage.uvue'
	import PopupPrinting from '../../components/Popup/PopupPrinting.uvue'
	import CategorySelector from '../../components/Common/CategorySelector.uvue'
	// 本页负责裁剪、创建作品、创建订单后传参到打印列表页
	import { creatework, createorder } from '../../utils/reques.uts'
	import type { ResponseData } from '../../utils/reques.uts'

	let inactivityTimer : number = 0
	const INACTIVITY_TIMEOUT = 3 * 60 * 1000 // 3分钟

	const category_value = ref('')
	const design_color = ref('')
	const imageSrc = ref('');
	const ai_model_id = ref(0)
	const machine_id = ref(0)
	const Fixturebg = ref('')
	const sizewidth = ref(0)
	const sizeheight = ref(0)
	// 裁剪组件引用
	const CroppImageRef = ref<ComponentPublicInstance | null>(null)
	const Cropping = ref(false)
	// 存储裁剪数据
	const cropInfoObj = ref<UTSJSONObject | null>(null)
	const showPopupPrinting = ref(false)
	// 判断是否显示更换商品按钮

	// 编辑状态 - 用于控制其他元素的显示/隐藏
	const isEditing = ref(false)
	// 控制退出确认弹窗
	const showConfirmBack = ref(false)
	// 控制分类选择器显示
	const showCategorySelector = ref(false)

	const handleBack = () => {
		showConfirmBack.value = true
	}

	// 确认退出
	const handleConfirmBack = () => {
		showConfirmBack.value = false
		uni.reLaunch({
			url: '/pages/list/index'
		})
	}

	// 取消退出
	const handleCancelBack = () => {
		showConfirmBack.value = false
	}

	// 接收子组件传递的裁剪数据
	const handleCropData = (cropInfo : UTSJSONObject) => {
		cropInfoObj.value = cropInfo
		console.log('[Print] 接收到裁剪数据:', cropInfo)
	}

	// 接收子组件传递的编辑状态
	const handleEditingChange = (editing : boolean) => {
		isEditing.value = editing
		console.log('[Print] 编辑状态变化:', editing)
	}


	// 重置编辑
	const handleChangereset = () => {
		if (CroppImageRef.value != null) {
			CroppImageRef.value.$callMethod('resetImage')
		}
	}

	// 打开选择商品弹窗
	const handleChangeProduct = () => {
		// 打开分类选择器
		showCategorySelector.value = true
	}

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

	// 处理分类选择器中的商品选择 - 更换商品参数
	const handleCategoryProductSelect = (product : UTSJSONObject) => {
		console.log('[print] 选中新商品:', product)
		showCategorySelector.value = false
		
		// 更新商品相关参数
		ai_model_id.value = product.getNumber('value') ?? 0
		machine_id.value = product.getNumber('machine_id') ?? 0
		category_value.value = product.getString('category_value') ?? ''
		
		const widthNum : number = parseFloat(product.getString('render_width') ?? '547')
		const heightNum : number = parseFloat(product.getString('render_height') ?? '542')
		sizewidth.value = isNaN(widthNum) ? 547 : widthNum
		sizeheight.value = isNaN(heightNum) ? 542 : heightNum
		Fixturebg.value = product.getString('front_image') ?? ''
		design_color.value = product.getString('design_color') ?? ''
		
		console.log('[print] 商品参数已更新:', {
			id: ai_model_id.value,
			machine_id: machine_id.value,
			category: category_value.value,
			size: `${sizewidth.value}x${sizeheight.value}`,
			color: design_color.value
		})
		
		// 重置裁剪区域以适应新商品尺寸
		handleChangereset()
	}

	// 打印确认处理函数（仅裁剪并跳转传参）
	const handlePrint = async () => {
		// 显示打印中弹窗
		showPopupPrinting.value = true
		// 触发裁剪信息收集
		Cropping.value = true
		// 延时 1s，确保子组件传递完成
		await new Promise<void>((resolve) => {
			setTimeout(() : void => {
				resolve()
			}, 1000)
		})
		// 使用组件传递的裁剪信息
		const cropData = cropInfoObj.value
		console.log('cropInfoObj', cropData);

		let upper_left_x : number = 0
		let upper_left_y : number = 0
		let width : number = 0
		let height : number = 0
		let zoom : number = 1
		let rotate : number = 0

		upper_left_x = (cropData != null ? (cropData['imageX'] as number) : 0) ?? 0
		upper_left_y = (cropData != null ? (cropData['imageY'] as number) : 0) ?? 0
		width = (cropData != null ? (cropData['displayWidth'] as number) : 0) ?? 0
		height = (cropData != null ? (cropData['displayHeight'] as number) : 0) ?? 0
		zoom = (cropData != null ? (cropData['imageScale'] as number) : 1) ?? 1
		rotate = (cropData != null ? (cropData['imageRotation'] as number) : 0) ?? 0

		// 构造完整的 payload 对象并先请求 creatework
		const payload = {
			goods_id: ai_model_id.value,
			machine_id: machine_id.value,
			components: [
				{
					upper_left_x: upper_left_x,
					upper_left_y: upper_left_y,
					width: width,
					height: height,
					zoom: zoom,
					rotate: rotate,
					index: 0,
					content: imageSrc.value,
					type_value: 'image'
				}
			]
		} as any
		// console.log('creatework payload', payload)
		try {
			const workRes : ResponseData = await creatework(payload) as ResponseData
			if (workRes.code != 0) {
				throw new Error(workRes.message)
			}
			const dataObj = workRes.data as UTSJSONObject
			const works_id = dataObj.getNumber('works_id') ?? 0
			const image = dataObj.getString('image') ?? ''
			const dpi = dataObj.getNumber('dpi') ?? 0
			const render_cove_width = dataObj.getString('render_cove_width') ?? ''
			const render_cove_height = dataObj.getString('render_cove_height') ?? ''
			const render_left = dataObj.getString('render_left') ?? ''
			const render_top = dataObj.getString('render_top') ?? ''
			const goodsObj = dataObj.getJSON('goods') as UTSJSONObject | null
			const goods = goodsObj

			// 创建订单
			const orderRes : ResponseData = await createorder({ works_id: works_id }) as ResponseData
			console.log('createorder result', orderRes)
			if (orderRes.code != 0) {
				throw new Error(orderRes.message)
			}
			const order = orderRes.data as UTSJSONObject
			const order_id = order.getNumber('order_id') ?? 0
			console.log('order_id', order_id);

			const work = {
				works_id: works_id,
				order_id: order_id,
				image: image,
				dpi: dpi,
				render_cove_width: render_cove_width,
				render_cove_height: render_cove_height,
				render_left: render_left,
				render_top: render_top,
				goods: goods
			} as any
			console.log('navigate work', work)

			// 关闭弹窗
			showPopupPrinting.value = false

			uni.navigateTo({ url: `/pages/printlist/index?work=${encodeURIComponent(JSON.stringify(work))}` })
		} catch (e) {
			console.error('creatework error', e)

			// 关闭弹窗
			showPopupPrinting.value = false

			uni.showToast({
				title: (e as Error).message,
				icon: 'none'
			})
		}
	}

	// 重置定时器
	const resetTimer = () => {
		// 清除现有定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
		}
		
		// 启动新的定时器
		inactivityTimer = setTimeout(() => {
			// 3分钟无操作，跳转到首页
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}, INACTIVITY_TIMEOUT)
	}

	onLoad((event : OnLoadOptions) => {

		// 从路由参数获取商品信息
		const productData = event["productData"] ?? ''
		if (productData.length > 0) {
			try {
				const decoded = decodeURIComponent(productData) ?? ''
				const productJson = JSON.parse(decoded as string) as UTSJSONObject

				ai_model_id.value = productJson.getNumber('value') ?? 0
				machine_id.value = productJson.getNumber('machine_id') ?? 0
				category_value.value = productJson.getString('category_value') ?? ''

				const widthNum : number = parseFloat(productJson.getString('render_width') ?? '')
				const heightNum : number = parseFloat(productJson.getString('render_height') ?? '')
				sizewidth.value = isNaN(widthNum) ? 547 : widthNum
				sizeheight.value = isNaN(heightNum) ? 542 : heightNum
				Fixturebg.value = productJson.getString('front_image') ?? ''
				design_color.value = productJson.getString('design_color') ?? ''
				
				console.log('[print] 商品数据加载成功:', {
					id: ai_model_id.value,
					machine_id: machine_id.value,
					category: category_value.value,
					size: `${sizewidth.value}x${sizeheight.value}`
				})
			} catch (e) {
				console.error('[print] 解析商品数据失败:', e)
				uni.showToast({
					title: '商品数据解析失败',
					icon: 'none'
				})
			}
		} else {
			console.warn('[print] 未接收到商品数据')
		}

		const rawImageSrc = event["imageSrc"] ?? ''
		const decoded = rawImageSrc.length > 0 ? decodeURIComponent(rawImageSrc) : ''
		imageSrc.value = decoded != null ? decoded : ""
		
		console.log('[print] 图片地址:', imageSrc.value)
		
		// 启动无操作定时器
		resetTimer()
	})

	// 页面隐藏时清除定时器
	onHide(() => {
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
	})

	onUnload(() => {
		// 清除无操作定时器
		if (inactivityTimer > 0) {
			clearTimeout(inactivityTimer)
			inactivityTimer = 0
		}
	})
</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-reset-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: row;
		background: #ffffff;
		padding: 10rpx;
		border-radius: 20rpx;
		border: 2rpx solid #FD3DA0;
	}

	.back-reset-text {
		font-size: 22rpx;
		color: #000000;
	}

	.back-reset-icon {
		width: 21rpx;
		height: 21rpx;
		margin: 0 5rpx;
	}

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

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

	.replace {
		position: absolute;
		bottom: 300rpx;
		right: 0;
		z-index: 2;
		height: 74rpx;
		padding: 0 10rpx;
		background: #FFFFFF;
		border-radius: 37rpx 0rpx 0rpx 37rpx;
		border: 1rpx solid #fd58ad;
		border-right: none;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

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

	.time {
		position: absolute;
		top: 150rpx;
		left: 0;
		right: 0;
		text-align: center;
		align-items: center;
		font-weight: 400;
		font-size: 25rpx;
		color: #000000;
	}

	.card {
		height: 100%;
	}

	.prompt {
		margin-top: 30rpx;
		font-size: 22rpx;
		color: #666666;
		text-align: center;

	}

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




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



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

	.resetprimary {
		width: 181rpx;
		height: 83rpx;
		background: #179D10;
		border-radius: 14rpx;
		/* border: 2rpx solid #ffffffff; */
		font-weight: bold;
		font-size: 24rpx;
		color: #ffffffff;
		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>