<template>
	<view class="container" :style="{ paddingTop: statusBarHeight + 'px' }">
		<!-- 背景装饰 -->
		<view class="bg-gradient"></view>

		<!-- 搜索列表页面 -->
		<view class="scan-section">
			<!-- 正在搜索设备 UI -->
			<view class="searching-box">
				<image class="search-icon" src="/static/images/pages_watch/icons/smartwatch_img.png" mode="aspectFit"></image>
				<view class="search-text-content">
					<view class="search-title">正在搜索设备...</view>
					<view class="search-subtitle">{{ currentSubtitle }}</view>
				</view>
			</view>

			<view class="header">
				<view class="title">搜索到{{ deviceList.length }}个设备</view>
				<view class="subtitle">请选择要连接的设备</view>
			</view>

			<view class="tips">
				提示：手表“设置”-“系统信息”中，查看“Mac地址”，匹配下列设备名称。
			</view>

			<scroll-view scroll-y class="device-list">
				<view v-for="(item, index) in deviceList" :key="index" class="device-card">
					<image class="device-icon" src="/static/images/pages_watch/icons/smartwatch_img.png" mode="aspectFit"></image>
					<view class="device-info">
						<view class="device-name">{{ item.mac || '未知设备' }}</view>
						<view class="device-signal" v-show="item.alreadyConnected">
							状态：{{connectionText(connectionState) }}
						</view>
						<view class="device-signal" v-show="!item.alreadyConnected">信号：{{ item.rssi }}</view>
					</view>
					<view class="connect-btn" @tap="startConnect(item)">{{ item.alreadyConnected ? '绑定' : '连接' }}</view>
				</view>
			</scroll-view>
		</view>

		<!-- 连接中弹窗 -->
		<u-popup :show="isConnecting" mode="bottom" round="24" :safeAreaInsetBottom="true" @close="closePopup">
			<view class="connecting-popup-content">
				<view class="popup-handle"></view>
				
				<view class="connecting-card">
					<image class="device-icon-small" src="/static/images/pages_watch/icons/smartwatch_img.png" mode="aspectFit"></image>
					<view>
						<view class="device-name-small">{{ connectingDevice ? connectingDevice.name : '未知设备' }}</view>
						<view class="device-name-small">{{ connectingDevice ? connectingDevice.mac : '' }}</view>
					</view>
				</view>

				<view class="status-header">
					<view class="status-title">{{ statusTitle }}</view>
					<view class="status-subtitle">{{ statusSubtitle }}</view>
				</view>

				<view class="watch-display">
					<image class="watch-large" src="/static/images/pages_watch/images/watch_img.png" mode="aspectFit"></image>
				</view>

				<view class="connect-tips">
					<view class="tip-title">提示：</view>
					<view class="tip-item">1、请同意设备的蓝牙配对请求；</view>
					<view class="tip-item">2、请同意设备的接收消息通知请求(设备上可能会有确认弹窗)。</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getWatchUserInfo,
		editMyfamily
	} from "@/api/pages_watch/user.js";
	import {
		editXHSDevice,
	} from "@/api/pages_watch/device.js"

	// 引入原生插件
	const fitCloudWatch = uni.requireNativePlugin('fitCloudWatch');

	export default {
		data() {
			return {
				statusBarHeight: 0,
				isConnecting: false,
				isScanning: false,
				deviceList: [],
				connectingDevice: null,
				currentSubtitle: '请确认设备在旁边',
				subtitleTimer: null,
				connectionState: 'DISCONNECTED', // CONNECTED, DISCONNECTED, CONNECTING
				fitCloudWatchUser: {},
				isFamily: false,
				selectUser: 0,
				xhsDeviceList: [],
				deviceType: 2, // 2新表
				statusTitle: '设备正在连接中...',
				statusSubtitle: '请勿离开本应用及本页面',
				retryCount: 0,
				maxRetries: 3
			}
		},
		computed: {
			connectionText() {
				const map = {
					'CONNECTED': '已连接',
					'DISCONNECTED': '未连接',
					'CONNECTING': '连接中...'
				};
				return (item) => {
					return map[item];
				}
			}
		},
		onLoad(option) {
			this.selectUser = Number(option.selectUser || 0)
			this.isFamily = option.selectUser != '0';
			
			const sys = uni.getSystemInfoSync();
			this.statusBarHeight = sys.statusBarHeight || 0;
			this.startSubtitleRotation();
			this.getUser();
		},
		onShow() {
			this.registerGlobalEvents();
			this.checkCurrentConnectionState();
		},
		onHide() {
			this.stopScan();
			this.removeGlobalEvents();
		},
		onUnload() {
			this.stopScan();
			this.removeGlobalEvents();
			if (this.subtitleTimer) {
				clearInterval(this.subtitleTimer);
			}
		},
		methods: {
			getUser() {
				getWatchUserInfo({
					isFamily: false
				}).then(res => {
					if (res.code == 200) {
						this.fitCloudWatchUser = res.user;
						if (this.isFamily) {
							const otherDevice = this.fitCloudWatchUser.otherDevice ? JSON.parse(this.fitCloudWatchUser.otherDevice) : [];
							const index = this.selectUser - 1;
							const currentMemberDeviceStr = otherDevice[index]?.newXhsDeviceId || '';
							this.xhsDeviceList = currentMemberDeviceStr ? currentMemberDeviceStr.split(',').map(id => ({ newXhsDeviceId: id })) : [];
						} else {
							const deviceIds = this.fitCloudWatchUser.newXhsDeviceId ? this.fitCloudWatchUser.newXhsDeviceId.split(',') : [];
							this.xhsDeviceList = deviceIds.map(id => ({ newXhsDeviceId: id }));
						}
					}
				})
			},
			// 检查当前连接状态 
			checkCurrentConnectionState() {
				this.deviceList = [];
				if (!fitCloudWatch) {
					this.startScan();
					return;
				}
				
				fitCloudWatch.getConnectionState({}, (res) => {
					console.log('当前连接状态:', res);
					if (res.state === 'CONNECTED' && res.mac) {
						this.connectionState = 'CONNECTED';
						const mac = res.mac;
						// 检查是否已经在 xhsDeviceList 中
						const isBound = this.xhsDeviceList.some(item => item.newXhsDeviceId === mac);
						if (!isBound) {
							// 如果没绑定，加入 deviceList 供用户点击“绑定”
							const connectedDevice = {
								mac: mac,
								name: res.name || '已连接设备',
								rssi: '--',
								alreadyConnected: true,
								connectionState: res.state
							};
							// 避免重复添加
							const index = this.deviceList.findIndex(item => item.mac === mac);
							if (index === -1) {
								this.deviceList.push(connectedDevice);
							} else {
								this.$set(this.deviceList, index, { ...this.deviceList[index], alreadyConnected: true });
							}
						}
					}
					// 无论是否已连接，都开启扫描以发现新设备
					this.startScan();
				});
			},
			registerGlobalEvents() {
				this.removeGlobalEvents();
				plus.globalEvent.addEventListener('onFitCloudDeviceFound', this.onDeviceFound);
				plus.globalEvent.addEventListener('onFitCloudConnectionStateChanged', this.onConnectionStateChanged);
				plus.globalEvent.addEventListener('onFitCloudConnectionError', this.onConnectionError);
			},
			removeGlobalEvents() {
				plus.globalEvent.removeEventListener('onFitCloudDeviceFound', this.onDeviceFound);
				plus.globalEvent.removeEventListener('onFitCloudConnectionStateChanged', this.onConnectionStateChanged);
				plus.globalEvent.removeEventListener('onFitCloudConnectionError', this.onConnectionError);
			},
			onDeviceFound(device) {
				console.log('onDeviceFound==:', device);
				const index = this.deviceList.findIndex(item => item.mac === device.mac);
				if (index === -1) {
					this.deviceList.push({ ...device, alreadyConnected: false });
				} else {
					// 如果原本是 alreadyConnected 的，保留这个状态
					const existing = this.deviceList[index];
					this.$set(this.deviceList, index, { ...device, alreadyConnected: existing.alreadyConnected || false });
				}
			},
			onConnectionStateChanged(res) {
				console.log('连接状态改变:', res);
				this.connectionState = res.state;
				if (res.state === 'CONNECTED') {
					this.retryCount = 0;
					this.statusTitle = '连接成功，正在绑定中...';
					this.statusSubtitle = '请耐心等待绑定结果';
					
					const mac = res.mac || (this.connectingDevice ? this.connectingDevice.mac : '');
					
					if (mac) {
						if(this.isConnecting) {
							// 弹窗打开才连接成功才自动绑定
							this.bindDevice(mac);
						} else {
							// 检查是否已经在 xhsDeviceList 中
							const isBound = this.xhsDeviceList.some(item => item.newXhsDeviceId === mac);
							
							if (!isBound) {
								// 如果没绑定，加入 deviceList 供用户点击“绑定”
								const connectedDevice = {
									mac: mac,
									name: res.name || '已连接设备',
									rssi: '--',
									alreadyConnected: true,
									connectionState: res.state
								};
								// 避免重复添加
								const index = this.deviceList.findIndex(item => item.mac === mac);
								if (index === -1) {
									this.deviceList.push(connectedDevice);
								} else {
									this.$set(this.deviceList, index, { ...this.deviceList[index], alreadyConnected: true });
								}
							}
						}
					}
				} else if (res.state === 'DISCONNECTED') {
					if (this.retryCount > 0 && this.retryCount < this.maxRetries) {
						// 正在重试中，忽略 DISCONNECTED 事件，让 onConnectionError 或下一次尝试处理
						return;
					}
					// 只有在没有重试或者重试完之后才置为关闭状态
					if (this.retryCount === 0 || this.retryCount >= this.maxRetries) {
						this.isConnecting = false;
						uni.showToast({ title: '已断开连接', icon: 'none' });
					}
				}
			},
			onConnectionError(res) {
				console.log('连接错误:', res);
				if (res.isRetry) {
					this.statusTitle = `连接重试中(${this.retryCount}/${this.maxRetries})...`;
					return;
				}
				
				if (this.retryCount < this.maxRetries) {
					this.retryCount++;
					this.statusTitle = `连接失败，正在第${this.retryCount}次重试...`;
					this.statusSubtitle = '请确保手表在手机附近';
					// 重新执行连接指令
					this.executeConnect(this.connectingDevice);
				} else {
					this.isConnecting = false;
					this.connectionState = 'DISCONNECTED';
					uni.showModal({
						title: '连接失败',
						content: '多次连接尝试失败，请检查手表是否已开启并靠近手机',
						showCancel: false,
						confirmText: '确定'
					});
				}
			},
			async startScan() {
				if (!fitCloudWatch) return;
				
				if (plus.os.name === 'Android') {
					const permissions = ['android.permission.ACCESS_FINE_LOCATION', 'android.permission.ACCESS_COARSE_LOCATION'];
					if (parseInt(plus.os.version) >= 12) {
						permissions.push('android.permission.BLUETOOTH_SCAN', 'android.permission.BLUETOOTH_CONNECT');
					}
					for (let p of permissions) {
						const granted = await new Promise(resolve => {
							plus.android.requestPermissions([p], res => resolve(res.granted.length > 0), () => resolve(false));
						});
						if (!granted) {
							uni.showToast({ title: '未获取蓝牙或定位权限', icon: 'none' });
							return;
						}
					}
				}

				this.isScanning = true;
				fitCloudWatch.startScan({}, (res) => {
					console.log('启动扫描==:', res);
					if (res.code !== 0) {
						this.isScanning = false;
						uni.showToast({ title: '启动扫描失败', icon: 'none' });
					}
				});
			},
			stopScan() {
				console.log('关闭扫描==:');
				if (!fitCloudWatch) return;
				fitCloudWatch.stopScan({}, () => {
					this.isScanning = false;
				});
			},
			startSubtitleRotation() {
				const subtitles = ['请确认设备在旁边', '请打开蓝牙和定位'];
				let index = 0;
				this.subtitleTimer = setInterval(() => {
					index = (index + 1) % subtitles.length;
					this.currentSubtitle = subtitles[index];
				}, 4000);
			},
			startConnect(device) {
				if (this.connectionState === 'CONNECTED') {
					// 如果点击的是已经连接的设备，则直接去绑定
					if (device.alreadyConnected || (this.connectingDevice && this.connectingDevice.mac === device.mac)) {
						this.bindDevice(device.mac);
						return;
					}
					uni.showToast({ title: '已有设备连接', icon: 'none' });
					return;
				}
				this.stopScan();
				this.connectingDevice = device;
				this.isConnecting = true;
				this.retryCount = 0;
				this.statusTitle = '设备正在连接中...';
				this.statusSubtitle = '请勿离开本应用及本页面';
				
				this.executeConnect(device);
			},
			executeConnect(device) {
				if (!device || !device.mac) return;
				
				this.connectionState = 'CONNECTING';
				const userId = (this.fitCloudWatchUser.userId || 'test') + '_' + device.mac;
				fitCloudWatch.connect({
					mac: device.mac,
					userId: userId,
					isBind: true,
					sex: this.fitCloudWatchUser.sex || true,
					age: this.fitCloudWatchUser.age || 25,
					height: this.fitCloudWatchUser.height || 175,
					weight: this.fitCloudWatchUser.weight || 70
				}, (res) => {
					if (res.code !== 0) {
						// 指令发送失败也尝试重试
						if (this.retryCount < this.maxRetries) {
							this.retryCount++;
							this.statusTitle = `指令发送失败，正在进行第${this.retryCount}次尝试...`;
							setTimeout(() => this.executeConnect(device), 2000);
						} else {
							this.isConnecting = false;
							this.connectionState = 'DISCONNECTED';
							uni.showToast({ title: '发送连接指令失败，请检查蓝牙状态', icon: 'none' });
						}
					}
				});
			},
			bindDevice(mac) {
				this.statusTitle = '正在绑定设备...';
				this.statusSubtitle = '正在同步云端数据';
				
				if (this.xhsDeviceList.some(item => item.newXhsDeviceId === mac)) {
					this.statusTitle = '设备已绑定';
					this.statusSubtitle = '即将返回主页';
					setTimeout(() => {
						uni.$emit('scanFitWatch')
						uni.navigateBack();
					}, 1500);
					return;
				}

				const newXhsDeviceId = this.xhsDeviceList.map(item => item.newXhsDeviceId);
				newXhsDeviceId.push(mac);
				if(!this.isConnecting) {
					uni.showLoading({
						title: '绑定中'
					});
				}
				const handleBindResult = (res) => {
					uni.hideLoading()
					if (res.code == 200) {
						this.statusTitle = '绑定成功';
						this.statusSubtitle = '正在跳转...';
						uni.showToast({ title: '绑定成功', icon: 'success' });
						setTimeout(() => {
							uni.$emit('scanFitWatch')
							uni.navigateBack()
						}, 1500);
					} else {
						this.statusTitle = '绑定失败';
						this.statusSubtitle = res.msg || '服务器异常';
						uni.showModal({
							title: '绑定失败',
							content: '设备已连接但绑定失败：' + (res.msg || '未知错误'),
							confirmText: '重试',
							cancelText: '取消',
							success: (modalRes) => {
								if (modalRes.confirm) {
									this.bindDevice(mac);
								} else {
									this.isConnecting = false;
								}
							}
						});
					}
				};
				if (this.isFamily) {
					
					console.log("qxj 222");
					
					const otherDevice = JSON.parse(this.fitCloudWatchUser.otherDevice || '[]');
					const index = this.selectUser - 1;
					
					// 安全判断：如果成员不存在，初始化一个空对象防止报错
					if (!otherDevice[index]) {
						otherDevice[index] = {};
					}
					// 赋值
					otherDevice[index] = {
						...otherDevice[index],
						newXhsDeviceId: newXhsDeviceId.join(',')
					}
					editMyfamily({ otherDevice: JSON.stringify(otherDevice) })
						.then(handleBindResult)
						.catch(() => handleBindResult({ code: 500, msg: '网络连接失败' }));
				} else {
					
					// this.bindDevice(mac);
					// return;
					
					console.log("qxj 111")
					editXHSDevice({
						newXhsDeviceId: newXhsDeviceId.join(','),
						deviceType: this.deviceType
					}).then(handleBindResult)
					  .catch(() => handleBindResult({ code: 500, msg: '网络连接失败' }));
				}
			},
			closePopup() {
				// 如果正在连接，允许关闭弹窗但不断开蓝牙？或者关闭时断开？
				// 参考 fitWatch2，通常连接中不建议关闭，或者关闭即放弃连接
				this.isConnecting = false;
				if (this.connectionState === 'CONNECTING') {
					fitCloudWatch.disconnect({}, () => {});
					this.connectionState = 'DISCONNECTED';
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	position: relative;
	background-color: #F5F7FA;
	overflow: hidden;
}

.bg-gradient {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 600rpx;
	background: linear-gradient(180deg, #FFEBD6 0%, rgba(245, 247, 250, 0) 100%);
	z-index: 0;
}

.scan-section {
	position: relative;
	z-index: 1;
	padding: 40rpx;
}

.searching-box {
	display: flex;
	align-items: center;
	padding: 40rpx 0;
	margin-top: 10rpx;

	.search-icon {
		width: 120rpx;
		height: 120rpx;
		margin-right: 30rpx;
	}

	.search-text-content {
		flex: 1;

		.search-title {
			font-size: 34rpx;
			font-weight: bold;
			color: #3B4144;
			margin-bottom: 12rpx;
		}

		.search-subtitle {
			font-size: 26rpx;
			color: #FF7700;
		}
	}
}

.connecting-popup-content {
	padding: 40rpx;
	background: linear-gradient(180deg, #FFEBD6 0%, #F5F7FA 30%, #F5F7FA 100%);
	border-radius: 24rpx 24rpx 0 0;
	min-height: 85vh;

	.popup-handle {
		width: 80rpx;
		height: 8rpx;
		background-color: rgba(0,0,0,0.1);
		border-radius: 4rpx;
		margin: 0 auto 40rpx;
	}
}

.header {
	text-align: center;
	margin-top: 60rpx;
	margin-bottom: 60rpx;
	
	.title {
		font-size: 44rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 16rpx;
	}
	
	.subtitle {
		font-size: 28rpx;
		color: #999;
	}
}

.tips {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 40rpx;
	line-height: 1.5;
}

.device-list {
	height: calc(100vh - 400rpx);
}

.device-card {
	background: #FFFFFF;
	border-radius: 24rpx;
	padding: 30rpx;
	margin-bottom: 24rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

	.device-icon {
		width: 80rpx;
		height: 80rpx;
		margin-right: 24rpx;
	}

	.device-info {
		flex: 1;
		
		.device-name {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 8rpx;
		}
		
		.device-signal {
			font-size: 24rpx;
			color: #999;
		}
	}

	.connect-btn {
		background: linear-gradient(90deg, #FF9933 0%, #FF7700 100%);
		color: #FFFFFF;
		font-size: 28rpx;
		padding: 12rpx 40rpx;
		border-radius: 40rpx;
		box-shadow: 0 4rpx 8rpx rgba(255, 119, 0, 0.3);
	}
}

// 连接中页面样式
.connecting-card {
	background: #FFFFFF;
	border-radius: 24rpx;
	padding: 20rpx 40rpx;
	margin-top: 20rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	
	.device-icon-small {
		width: 60rpx;
		height: 60rpx;
		margin-right: 20rpx;
	}
	
	.device-name-small {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
	}
}

.status-header {
	text-align: center;
	margin-top: 80rpx;
	
	.status-title {
		font-size: 44rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.status-subtitle {
		font-size: 28rpx;
		color: #FF7700;
		font-weight: 500;
	}
}

.watch-display {
	display: flex;
	justify-content: center;
	margin-top: 60rpx;
	margin-bottom: 80rpx;
	
	.watch-large {
		width: 360rpx;
		height: 360rpx;
	}
}

.connect-tips {
	padding: 0 40rpx;
	
	.tip-title {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 20rpx;
	}
	
	.tip-item {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 12rpx;
		line-height: 1.4;
	}
}
</style>
