<template>
	<view class="single">
		<!-- 房间信息 -->
		<view class="room-header">
			<text class="room-title">多人 - 15071690房间</text>
		</view>
		<!-- 功能菜单 -->
		<view class="header">
			<view class="list-container">
				<view class="list-item">
					<text class="number">1</text>
					<text class="text">添加玩家</text>
				</view>
				<view class="list-item">
					<text class="number">2</text>
					<text class="text">转让房主</text>
				</view>
				<view class="list-item">
					<text class="number">3</text>
					<text class="text">语音播报</text>
					<text class="voice-status">{{}}</text>
				</view>
				<view class="list-item">
					<text class="number">4</text>
					<text class="text">台板(茶水)</text>
				</view>
			</view>
		</view>

		<!-- 玩家表格 -->
		<view class="container">
			<!-- 表格标题 -->
			<view class="table-header">
				<text class="col-player">玩家</text>
				<text class="col-score">得分</text>
				<text class="col-action">操作</text>
			</view>

			<!-- 分享提示 -->
			<view class="share-remind">
				<text class="remind-text">觉得好用可去首页分享给好友或群聊~</text>
			</view>

			<!-- 玩家列表 -->
			<view class="player-list">
				<!-- 自己 -->
				<view class="player-row own-row" v-for="(item,index) in roomUsers">
					<view class="player-info">
						<view class="player-avatar">
							<!-- 使用相对定位的容器包裹image和text -->
							<view class="avatar-container">
								<image :src="item.avatars"></image>

								<!-- 	<text class="self-badge" v-if="isSelf ==true ">自己</text> -->
							</view>
						</view>
						<view class="player-name">
							<text>玩家{{item.nickName}}</text>
						</view>
					</view>
					<text class="player-score">
						{{item.score}}
					</text>
					<view class="player-action">
						<button class="btn-batch" @click="giveScore">给分</button>
					</view>
				</view>



			</view>

			<!-- 编辑提示 -->
			<view class="edit-remind">
				<text class="remind-text">点击自己头像编辑用户头像和昵称~</text>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="footer">
			<button class="btn-detail">给分详情</button>
			<button class="btn-settle">结算房间</button>
		</view>
		<div class="give-score" v-if="IsGive">
			<div class="give-contain">
				<!-- 标题 -->
				<div class="give-title">给分!!!</div>

				<!-- 输入框 -->
				<input type="number" placeholder="填写要给对方的分数" v-model="Score" />

				<!-- 按钮区域 -->
				<div class="give-footer">
					<button class="btn btn-cancel" @click="closeGive">取消</button>
					<button class="btn btn-confirm">确定</button>
				</div>
			</div>
		</div>
	</view>
</template>


<script setup>
	import {
		ref,
		onUnmounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const isSelf = ref(true)
	const voiceEnabled = ref(true)
	const socketTask = ref(null) // 改为使用 uni-app 的 SocketTask
	const IsGive = ref(false)
	const roomUsers = ref([])
	const Score = ref(0)

	onLoad((options) => {
		console.log("556", options.roomUserInfo)
		let roomUserInfo = null;

		if (options.roomUserInfo) {
			// 先解码，再解析JSON
			const decodedInfo = decodeURIComponent(options.roomUserInfo);
			roomUserInfo = JSON.parse(decodedInfo);
			console.log('解析后的数据:', roomUserInfo);

			if (roomUserInfo?.playerType === 'business') {
				const userId = roomUserInfo.createUser;
				const exists = roomUsers.value.some(user => user.userId === userId);
				if (!exists) {
					roomUsers.value.push({
						userId: userId,
						score: 0,
						playerType: 'business',
						nickName: roomUserInfo.nickName,
						avatars: roomUserInfo.avatars
					});
				}
			} else if (roomUserInfo?.playerType === 'user') {
				const userId = roomUserInfo.createUser;
				const exists = roomUsers.value.some(user => user.userId === userId);
				if (!exists) {
					roomUsers.value.push({
						userId: userId,
						score: 0,
						playerType: 'user',
						nickName: roomUserInfo.nickName,
						avatars: roomUserInfo.avatars
					});
				}
			}
			console.log("888888888888", roomUserInfo)
			// 初始化WebSocket连接
			initWebSocket(roomUserInfo);
		}


	});

	// 初始化WebSocket连接 - 使用 uni-app 的 SocketTask API
	const initWebSocket = (roomUserInfo) => {
		try {
			// 关闭现有连接（如果有）
			if (socketTask.value) {
				closeWebSocket();
			}

			console.log('正在创建WebSocket连接...', roomUserInfo.userId, roomUserInfo.roomId);

			// 使用 uni-app 的 connectSocket API 而不是 new WebSocket()
			socketTask.value = uni.connectSocket({
				url: `ws://localhost:8080/websocket/${roomUserInfo.roomId}/${roomUserInfo.userId}`,
				success: (res) => {
					console.log('WebSocket连接创建成功', res);
				},
				fail: (err) => {
					console.error('WebSocket连接创建失败', err);
				}
			});

			// 监听连接打开事件
			socketTask.value.onOpen(() => {
				console.log('WebSocket连接成功');
				// 连接成功后发送加入房间的消息
				sendJoinRoomMessage(roomUserInfo);
			});

			// 监听接收消息事件
			socketTask.value.onMessage((event) => {
				try {
					console.log('📨 收到服务器原始消息:', event.data); // 首先打印原始数据
					const message = JSON.parse(event.data);
					handleWebSocketMessage(message);
				} catch (error) {
					console.error('消息解析错误:', error);
				}
			});

			// 监听连接关闭事件
			socketTask.value.onClose((event) => {
				console.log('WebSocket连接关闭:', event);
			});

			// 监听错误事件
			socketTask.value.onError((error) => {
				console.error('WebSocket连接错误:', error);
			});

		} catch (error) {
			console.error('WebSocket初始化失败:', error);
		}
	}

	// 发送加入房间的消息 - 适配 SocketTask API
	const sendJoinRoomMessage = (roomUserInfo) => {
		if (socketTask.value) {
			const joinMsg = {
				type: 'join_room',
				roomId: roomUserInfo.roomId,
				userId: roomUserInfo.userId,
				userInfo: {
					nickName: roomUserInfo.nickName,
					avatars: roomUserInfo.avatars // 修正拼写错误
				}
			};

			// 使用 SocketTask 的 send 方法
			socketTask.value.send({
				data: JSON.stringify(joinMsg),
				success: () => {
					console.log('加入房间消息发送成功');
				},
				fail: (err) => {
					console.error('消息发送失败:', err);
				}
			});
		}
	}

	// 处理WebSocket消息（保持不变）
	const handleWebSocketMessage = (message) => {
		console.log('收到消息:', message);

		switch (message.type) {
			case 'user_joined':
				handlePlayerJoin(message.data);
				break;
			case 'user_left':
				handlePlayerLeave(message.data);
				break;
			case 'score_update':
				handleScoreUpdate(message.data);
				break;
			default:
				console.log('未知消息类型:', message);
		}
	}

	// 处理玩家加入（保持不变）
	const handlePlayerJoin = (playerData) => {
		const exists = roomUsers.value.some(user => user.userId === playerData.userId);
		if (!exists) {
			roomUsers.value.push({
				userId: playerData.userId,
				score: 0,
				playerType: playerData.playerType || 'user',
				nickName: playerData.nickName,
				avatars: playerData.avatars
			});
		}
	}

	// 处理玩家离开（保持不变）
	const handlePlayerLeave = (playerData) => {
		roomUsers.value = roomUsers.value.filter(user => user.userId !== playerData.userId);
	}

	// 处理分数更新（保持不变）
	const handleScoreUpdate = (scoreData) => {
		const user = roomUsers.value.find(user => user.userId === scoreData.userId);
		if (user) {
			user.score = scoreData.newScore;
		}
	}
	//给分
	const giveScore = () => {
		IsGive.value = true
	}
	//取消给分
	const closeGive = () => {
		IsGive.value = false
	}
	//确认给分
	const confirmGive = () => {
		IsGive.value = false
	}
	// 发送WebSocket消息 - 适配 SocketTask API
	const sendWebSocketMessage = (message) => {
		if (socketTask.value) {
			socketTask.value.send({
				data: JSON.stringify(message),
				success: () => {
					console.log('消息发送成功');
				},
				fail: (err) => {
					console.error('消息发送失败:', err);
				}
			});
		} else {
			console.error('WebSocket未连接，无法发送消息');
		}
	}

	// 关闭WebSocket连接 - 适配 SocketTask API
	const closeWebSocket = () => {
		if (socketTask.value) {
			socketTask.value.close({
				success: () => {
					console.log('WebSocket连接已关闭');
					socketTask.value = null;
				},
				fail: (err) => {
					console.error('关闭连接失败:', err);
				}
			});
		}
	}

	// 页面卸载时关闭连接
	onUnmounted(() => {
		closeWebSocket();
	});

	// 其他功能方法保持不变...
</script>
<style scoped lang="less">
	.single {
		width: 100%;
		margin: 0;
		padding: 0;
		box-sizing: border-box;
		background-color: #f5f7fa;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}


	/* 房间标题 */
	.room-header {
		padding: 25rpx 30rpx;
		background-color: #0055ff;
		text-align: center;

		.room-title {
			font-size: 36rpx;
			color: #ffffff;
			font-weight: bold;

		}
	}

	/* 功能菜单 */
	.header {
		background-color: #ffffff;
		border-bottom: 1rpx solid #f0f0f0;

		.list-container {
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 30rpx 20rpx;

			.list-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 15rpx;
				position: relative;

				.number {
					width: 80rpx;
					height: 80rpx;
					background: #f5f5f5;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 32rpx;
					color: #666;
					font-weight: normal;
				}

				.text {
					font-size: 24rpx;
					color: #666;
				}

				.voice-status {
					position: absolute;
					top: 65rpx;
					font-size: 20rpx;
					color: #0055ff;
				}
			}
		}
	}

	/* 表格容器 */
	.container {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		/* 表格标题 */
		.table-header {
			display: flex;
			align-items: center;
			padding: 25rpx 30rpx;
			background-color: #f8f9fa;
			border-bottom: 1rpx solid #e8e8e8;
			font-weight: bold;
			font-size: 30rpx;
			color: #333;

			.col-player {
				flex: 2;
				text-align: left;
			}

			.col-score {
				flex: 1;
				text-align: center;
			}

			.col-action {
				flex: 1;
				text-align: center;
			}
		}

		/* 分享提示 */
		.share-remind {
			padding: 20rpx;
			background-color: #fff5f5;
			border-bottom: 1rpx solid #ffe6e6;

			.remind-text {
				font-size: 26rpx;
				color: #ff4444;
				text-align: center;
			}
		}

		/* 玩家列表 */
		.player-list {
			.player-row {
				display: flex;
				align-items: center;
				padding: 25rpx 30rpx;
				border-bottom: 1rpx solid #f5f5f5;

				&:last-child {
					border-bottom: none;
				}

				.player-info {
					flex: 2;
					display: flex;
					align-items: center;
					gap: 20rpx;

					.player-avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						background-color: #e0e0e0;
						display: flex;
						align-items: center;
						justify-content: center;



						.avatar-container {
							position: relative;
							width: 100%;
							height: 100%;

							image {
								width: 100%;
								height: 100%;
								border-radius: 50%;
							}

							.self-badge {
								position: absolute;
								top: -10rpx;
								/* 调整到合适位置 */
								right: -10rpx;
								/* 调整到合适位置 */
								padding: 4rpx 8rpx;
								background-color: orange;
								color: white;
								border-radius: 20rpx;
								font-size: 20rpx;
								border: 2rpx solid white;
								z-index: 10;
								/* 确保在小圆点内 */
								min-width: 40rpx;
								text-align: center;
								line-height: 1.2;
							}
						}
					}

					.player-name {
						font-size: 30rpx;
						color: #333;
						display: flex;
						align-items: center;
						gap: 10rpx;
					}
				}

				.player-score {
					flex: 1;
					text-align: center;
					font-size: 36rpx;
					font-weight: bold;
					color: #0055ff;
				}

				.player-action {
					flex: 1;
					display: flex;
					justify-content: center;

					button {
						padding: 15rpx 25rpx;
						font-size: 26rpx;
						border-radius: 6rpx;
						border: none;
						font-weight: bold;
					}

					.btn-batch {
						background-color: #0055ff;
						color: #ffffff;
					}

					.btn-score {
						background-color: #28a745;
						color: #ffffff;
					}
				}
			}
		}

		/* 编辑提示 */
		.edit-remind {
			padding: 20rpx;
			background-color: #f0f8ff;
			border-top: 1rpx solid #e6f2ff;

			.remind-text {
				font-size: 26rpx;
				color: #0055ff;
				text-align: center;
			}
		}
	}

	/* 底部操作栏 */
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		padding: 20rpx;
		background: white;
		border-top: 1rpx solid #e0e0e0;
		gap: 20rpx;

		button {
			flex: 1;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 8rpx;
			font-size: 32rpx;
			font-weight: bold;
			border: none;
		}

		.btn-detail {
			background: #0055ff;
			color: white;
		}

		.btn-settle {
			background: white;
			color: #0055ff;
			border: 1rpx solid #0055ff;
		}
	}

	//给分
	/* 弹窗遮罩 - 优化版 */
	.give-score {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		/* 垂直居中 */
		z-index: 1000;
		background: rgba(0, 0, 0, 0.5);
		backdrop-filter: blur(10rpx);
		padding: 40rpx;
		/* 添加边距防止在小屏幕上贴边 */
	}

	/* 弹窗主体 - 优化版 */
	.give-contain {
		width: 90%;
		max-width: 560rpx;
		min-width: 300rpx;
		/* 最小宽度限制 */
		background: #fff;
		border-radius: 24rpx;
		padding: 60rpx 40rpx 40rpx;
		/* 调整内边距 */
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
		animation: popup-show 0.3s ease-out;
	}

	/* 标题优化 */
	.give-title {
		font-size: 36rpx;
		/* 稍微调小字号 */
		font-weight: bold;
		text-align: center;
		margin-bottom: 50rpx;
		color: #333;
	}

	/* 输入框优化 */
	.give-contain input {
		width: 100%;
		height: 96rpx;
		/* 微调高度 */
		margin: 0 0 50rpx;
		/* 简化边距 */
		padding: 0 30rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 16rpx;
		font-size: 32rpx;
		/* 调小字号 */
		font-weight: bold;
		text-align: center;
		background: #f8f8f8;
		box-sizing: border-box;
		/* 确保宽度计算正确 */
		transition: all 0.2s ease;
		/* 添加过渡效果 */
	}

	.give-contain input:focus {
		border-color: #07c160;
		background: #fff;
		box-shadow: 0 0 0 4rpx rgba(7, 193, 96, 0.1);
		/* 添加聚焦阴影 */
		outline: none;
	}


	.give-footer {
		display: flex;
		gap: 10rpx;
	}

	.btn {
		flex: 1;
		height: 88rpx;
		/* 增加按钮高度 */
		border-radius: 16rpx;
		/* 增加圆角 */
		font-size: 32rpx;
		font-weight: 500;
		border: none;
		cursor: pointer;
		transition: all 0.2s ease;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn-cancel {
		background: #f5f5f5;
		/* 改为浅灰色背景 */
		color: #666;
		border: 2rpx solid #e0e0e0;
	}

	.btn-cancel:active {
		background: #e8e8e8;
		/* 点击反馈 */
	}

	.btn-confirm {
		background: #07c160;
		color: #fff;
		font-weight: bold;
	}

	.btn-confirm:active {
		background: #06a652;
		/* 点击时颜色加深 */
		transform: scale(0.98);
		/* 点击反馈 */
	}

	/* 动画优化 */
	@keyframes popup-show {
		from {
			opacity: 0;
			transform: scale(0.9) translateY(40rpx);
		}

		to {
			opacity: 1;
			transform: scale(1) translateY(0);
		}
	}

	/* 响应式优化 */
	@media (max-width: 480rpx) {
		.give-score {
			padding: 20rpx;
		}

		.give-contain {
			padding: 50rpx 30rpx 30rpx;
		}

		.give-title {
			font-size: 32rpx;
			margin-bottom: 40rpx;
		}

		.give-contain input {
			height: 88rpx;
			font-size: 28rpx;
			margin-bottom: 40rpx;
		}

		.btn {
			height: 80rpx;
			font-size: 28rpx;
		}

		.give-footer {

			gap: 20rpx;
		}
	}
</style>