<template>
	<view v-if="visible" class="popup-overlay" :class="{ 'popup-overlay-enter': showAnimation }">
		<view class="popup-fixed" :class="{ 'popup-scale-enter': showAnimation }">
			<view class="popup-container-bg">
				<image src="/static/UploadQrcode.png" class="popup-bg-image" mode="aspectFill"></image>
				<view class="popup-container">
					<text class="popup-title">
						微信扫码上传图片
					</text>
					<!-- 倒计时 -->
					<view class="timer-section">
						<text class="timer-text">上传剩余时间 {{ countdownText }}</text>
					</view>
					<!-- 主题指示器 -->
					<!-- <view class="theme-section">
						<view class="theme-line"></view>
						<text class="theme-text">哈利波特</text>
						<view class="theme-line"></view>
					</view> -->
					<!-- 警告信息 -->
					<view class="warning-section">
						<text class="warning-text">扫码过程中请勿关闭该弹窗</text>
					</view>
					<!-- 二维码区域 -->
					<view class="qr-section">
						<view class="qr-code-container" v-if="qrcode">
							<image :src="qrcode" class="qr-code-image" mode="aspectFit" />
						</view>
						<view class="qr-loading" v-else>
							<text class="loading-text">二维码生成中...</text>
						</view>
						<text class="qr-instruction">手机扫码即可参与</text>
					</view>
				</view>
			</view>
			<!-- 关闭按钮 -->
			<view class="close-button" @click="handleClose">
				<image src="/static/icon_close.png" class="close-icon" />
			</view>
			<!-- 二次确认弹窗 -->
			<PopupConfirm
				:visible="showConfirm"
				title="提示"
				content="当前二维码只对本次打开有效，是否退出？"
				confirmText="退出"
				cancelText="继续扫码"
				:closeOnOverlay="true"
				@confirm="onConfirmExit"
				@cancel="onCancelExit"
			/>
		</view>
	</view>
</template>
<script setup lang="uts">
	import { uploadQrcode, type ResponseData } from '../../utils/reques.uts'

	type PopupUploadProps = {
		visible : boolean
		closeOnOverlay : boolean
	}


	const qrcode = ref('')

	const getQrcode = async (fdParam : string) : Promise<void> => {
		try {
			const res = await uploadQrcode(fdParam) as ResponseData
			if (res.code == 0 && res.data != null) {
				const dataObj = res.data as UTSJSONObject
				qrcode.value = dataObj.getString('base_64_image') ?? ''
			} else {
				console.log('获取二维码失败:', res.message)
			}
		} catch (error) {
			console.log('请求二维码失败:', error)
		}
	}

	const WS_URL = 'ws://www.colorpark.cn:9910/?client=ai'
	const socketFd = ref('')
	let socketTask : SocketTask | null = null



	const closeSocket = () : void => {
		try {
			// 创建本地引用避免智能转换问题
			const currentSocketTask = socketTask
			if (currentSocketTask != null) {
				currentSocketTask.close({
					code: 1000,
					reason: 'close',
					success: (res : any) => {
						console.log('WebSocket 关闭成功')
					},
					fail: (err : any) => {
						console.log('WebSocket 关闭失败:', err)
					}
				})
				socketTask = null
			}
		} catch (e) {
			console.log('关闭 WebSocket 失败:', e)
		}
	}

	type PopupUploadEmits = {
		(e : 'close') : void
	}

	const props = withDefaults(defineProps<PopupUploadProps>(), {
		visible: false,
		closeOnOverlay: false
	})

	const emit = defineEmits<PopupUploadEmits>()

	// 3分钟倒计时（显示用）
	const countdownSeconds = ref(180)
	const countdownText = computed(() : string => {
		const m = Math.floor(countdownSeconds.value / 60)
		const s = countdownSeconds.value % 60
		const mm = m < 10 ? '0' + m : '' + m
		const ss = s < 10 ? '0' + s : '' + s
		return mm + '分' + ss + '秒'
	})

	// 定时器句柄
	let countdownInterval : number = -1
	let autoCloseTimer : number = -1

	const showAnimation = ref(false)
	// 二次确认弹窗显示状态
	const showConfirm = ref(false)

	const clearTimers = () : void => {
		if (countdownInterval != -1) {
			clearInterval(countdownInterval)
			countdownInterval = -1
		}
		if (autoCloseTimer != -1) {
			clearTimeout(autoCloseTimer)
			autoCloseTimer = -1
		}
	}

	const startCountdown = () : void => {
		clearTimers()
		countdownSeconds.value = 180
		countdownInterval = setInterval(() => {
			if (countdownSeconds.value > 0) {
				countdownSeconds.value = countdownSeconds.value - 1
			} else {
				clearTimers()
				emit('close')
			}
		}, 1000)
	}

	const handleOverlayClick = () => {
		if (props.closeOnOverlay == true) {
			clearTimers()
			closeSocket()
			emit('close')
		}
	}

	// 实际关闭逻辑（用于确认通过后或代码内部直接调用）
	const doClose = () : void => {
		clearTimers()
		closeSocket()
		emit('close')
	}

	// 关闭按钮点击，弹出二次确认
	const handleClose = () : void => {
		// 打开自定义二次确认弹窗
		showConfirm.value = true
	}

	// 确认退出与取消继续扫码的回调
	const onConfirmExit = () : void => {
		showConfirm.value = false
		doClose()
	}

	const onCancelExit = () : void => {
		showConfirm.value = false
	}

		const connectWebSocket = () : void => {
		try {
			socketFd.value = ''
			// 使用SocketTask对象管理WebSocket连接
			socketTask = uni.connectSocket({
				url: WS_URL,
				success: (res : any) => {
					console.log('WebSocket 连接请求成功')
				},
				fail: (err : any) => {
					console.log('WebSocket 连接请求失败:', err)
				}
			})

			// 创建本地引用避免智能转换问题
			const currentSocketTask = socketTask
			if (currentSocketTask != null) {
				// 监听连接打开
				currentSocketTask.onOpen((res) => {
					console.log('WebSocket 连接已打开')
				})

				// 监听消息接收
				currentSocketTask.onMessage((res) => {
					try {
						console.log('res',res)
						let data = res['data']
						
						// 正确处理消息数据类型
						let messageData : string = ''
						if (typeof data === 'string') {
							messageData = data as string
						} else {
							console.log('收到非字符串消息:', data)
							return
						}

						// 解析JSON消息
						const obj = JSON.parse(messageData) as UTSJSONObject
						console.log('收到消息类型:', obj)
						const fdNum = obj.getNumber('fd') ?? 0
						const type = obj.getString('type') ?? ''
						socketFd.value = fdNum.toString()
						if(type == 'clientId'){
							getQrcode('?fd=' + socketFd.value)
						} else {
							let objdata = obj.data as UTSJSONObject
							console.log('objdata:', objdata)
						let imageSrc = objdata.getString('path') ?? ''
						// 收到上传完成消息后直接关闭，无需用户二次确认
						doClose()
							uni.navigateTo({
								url: '/pages/camera/index?imageSrc=' + imageSrc
							})
							
						}
					} catch (e) {
						console.log('解析WebSocket消息失败:', e)
					}
				})

				// 监听连接错误
				currentSocketTask.onError((err : any) => {
					console.log('WebSocket 连接错误:', err)
				})

				// 监听连接关闭
				currentSocketTask.onClose((res : any) => {
					console.log('WebSocket 已关闭')
					socketTask = null
				})
			}

		} catch (e) {
			console.log('发起WebSocket连接失败:', e)
		}
	}

	// 监听 visible 属性，打开时连接 WebSocket，成功后获取二维码；关闭时清理
	watch(() : boolean => props.visible, (newVisible : boolean) : void => {
		if (newVisible) {
			qrcode.value = ''
			connectWebSocket()
			startCountdown()
			// 弹窗打开时，延迟一帧触发动画
			nextTick(() => {
				showAnimation.value = true
			})
		} else {
			clearTimers()
			closeSocket()
			// 弹窗关闭时，重置动画状态
			showAnimation.value = false
		}
	})

	onUnmounted(() => {
		clearTimers()
		closeSocket()
	})
</script>
<style>
	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: background-color 0.3s ease;
	}

	.popup-overlay-enter {
		background-color: rgba(0, 0, 0, 0.5);
	}

	.popup-fixed {
		margin-top: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		transform: scale(0.7);
		transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
	}

	.popup-scale-enter {
		transform: scale(1);
	}


	.popup-container {
		width: 498.61rpx;
		height: 547.92rpx;
		position: relative;
		z-index: 2;
	}

	.popup-container-bg {
		display: flex;
		justify-content: center;
		position: relative;
		width: 497.22rpx;
		height: 633.33rpx;
	}

	.popup-title {
		margin-top: 32rpx;
		font-weight: bold;
		font-size: 36rpx;
		color: #21061A;
		align-items: center;
		display: flex;
		justify-content: center;
		text-align: center;
	}

	.popup-bg-image {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}


	.icon-hand,
	.icon-lightning {
		font-size: 18rpx;
	}

	/* 倒计时区域 */
	.timer-section {
		margin-top: 30rpx;
		padding: 12rpx 20rpx 8rpx;
		align-items: center;
	}

	.timer-text {
		font-weight: 400;
		font-size: 20rpx;
		color: #A9A9B2;
	}

	/* 主题指示器 */
	.theme-section {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16rpx 40rpx;
		flex-direction: row;
	}

	.theme-line {
		height: 2rpx;
		background-color: #ddd;
		width: 43rpx;
	}

	.theme-text {
		white-space: nowrap;
		font-weight: 400;
		font-size: 19rpx;
		color: #000000;
	}

	/* 警告信息 */
	.warning-section {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16rpx 40rpx;

	}

	.warning-icon {
		color: #ff4444;
		font-size: 60rpx;
	}

	.warning-text {
		font-weight: 400;
		font-size: 21rpx;
		color: #F42733;
	}

	/* 二维码区域 */
	.qr-section {
		/* padding: 40rpx; */
		display: flex;
		align-items: center;
	}

	.qr-code-image {
		width: 188rpx;
		height: 189rpx;
	}


	.qr-instruction {
		margin-top: 33rpx;
		font-weight: bold;
		font-size: 23rpx;
		color: #000000;
		align-items: center;
		;
	}


	/* 关闭按钮 */
	.close-button {
		margin-top: 45rpx;
		width: 52rpx;
		height: 52rpx;
	}

	.close-icon {
		width: 52rpx;
		height: 52rpx;
	}
</style>