<template>
	<view class="page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<cus-header title='配置网络'></cus-header>
		<template v-if="!nodevice">
			<div class="search adffcac">
				<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/04/379c752c-13f5-4668-9977-e8cad9cd0fa4.gif"></image>
				<p>正在搜索可配网设备</p>
			</div>
		</template>
		<template v-else>
			<div class="empty adffcac">
				<div class="title">{{ emptyState.title }}</div>
				<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/04/5824159f-0bd8-4399-be6c-7d309e2a35dc.png"></image>
				<div class="tip">{{ emptyState.tip }}</div>
				<div class="warn adfac" @tap="alertShow=true">
					<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/04/19ca1b06-9bfd-4ae6-9c1c-eec45a86f0a0.png"></image>
					<span>找不到设备怎么办 ></span>
				</div>
			</div>
		</template>

		<div class="zt_btn" v-if="nodevice" @tap="searchAgain">再次搜索</div>

		<u-popup :show="alertShow" :round="56" mode="center" @close="alertShow=false">
			<div class="alert">
				<div class="title">找不到设备怎么办</div>
				<p style="margin-top: 53rpx;">1.请确保可配网的设备在手机旁边</p>
				<p>2.如果没有开机，请先按住开关键直到指示灯亮起</p>
				<p>3.开机状态下，按配网键1次进入配网模式</p>
				<div class="btn" @tap="alertShow=false">我知道了</div>
			</div>
		</u-popup>

		<u-popup :show="show" :round="64" mode="bottom" @close="show=false">
			<div class="connect adffcac">
				<div class="title">找到一个待配网的设备</div>
				<image src="https://transcend.ringzle.com/xiaozhi-app/profile/2025/06/04/6f06a2de-5d6c-4596-9a0c-77971d6ea230.png"></image>
				<div class="tip">序列号：{{lanya.deviceId}}</div>
				<div class="btn" @tap="connectWiFi">连接</div>
			</div>
		</u-popup>
	</view>
</template>

<script>
	var xBlufi = require("@/utils/blufi/xBlufi.js");
	let _this = null;
	export default {
		data() {
			return {
				nodevice: false, // 是否未找到设备
				show: false, // 是否显示连接弹窗
				alertShow: false, // 是否显示帮助弹窗
				lanya: null, // 找到的蓝牙设备信息
				devicesList: [],
				searching: false, // 是否正在搜索
				type: '', // 设备类型
				errorType: '', // 'timeout' 或 'bluetoothOff'，用于区分错误类型
				timeoutTimer: null // 搜索超时定时器
			}
		},
		computed: {
			// 根据错误类型动态生成提示文案
			emptyState() {
				if (this.errorType === 'bluetoothOff') {
					return {
						title: '蓝牙未开启',
						tip: '请检查手机蓝牙是否已开启'
					};
				}
				if (this.errorType === 'timeout') {
					return {
						title: '搜索超时',
						tip: '没有找到可用设备？'
					};
				}
				// 默认情况
				return {
					title: '搜索失败',
					tip: '没有找到可用设备？'
				};
			}
		},
		onShow() {
			this.init();
		},
		onLoad: function(option) {
			this.type = option.type || '';
			_this = this; // 保留页面实例的引用，供回调函数使用
		},
		onUnload() {
			// 页面卸载时，停止监听并清除定时器，防止内存泄漏
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			if (this.timeoutTimer) {
				clearTimeout(this.timeoutTimer);
				this.timeoutTimer = null;
			}
		},
		methods: {
			// 初始化页面状态
			init() {
				this.nodevice = false;
				this.show = false;
				this.alertShow = false;
				this.lanya = null;
				this.devicesList = [];
				this.searching = false;
				this.errorType = '';

				// 清理上一次的定时器
				if (this.timeoutTimer) {
					clearTimeout(this.timeoutTimer);
					this.timeoutTimer = null;
				}
				
				// 重新注册监听事件并开始搜索
				xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent); // 先移除旧监听
				this.Search();
				xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent); // 再添加新监听
			},
			// 再次搜索
			searchAgain() {
				this.init();
			},
			// 蓝牙事件回调处理
			funListenDeviceMsgEvent: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
						console.log(options, 'TYPE_STATUS_CONNECTED')
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result && options.data.length > 0) {
							_this.devicesList = options.data;
							// 优先查找 'cx-' 前缀的设备，其次是 'BLUFI_DEVICE'
							let ly = _this.devicesList.find(d => d.name.indexOf('cx-') > -1);
							if (!ly) ly = _this.devicesList.find(d => d.name.indexOf('BLUFI_DEVICE') > -1);

							if (ly) {
								console.log(ly, '找到设备');
								// 找到设备后，清除超时定时器
								if (_this.timeoutTimer) {
									clearTimeout(_this.timeoutTimer);
									_this.timeoutTimer = null;
								}
								// 停止蓝牙搜索
								xBlufi.notifyStartDiscoverBle({
									'isStart': false
								});
								_this.lanya = ly;
								_this.nodevice = false;
								_this.show = true;
							}
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
						wx.hideLoading();
						if (options.result) {
							wx.showToast({
								title: '连接成功',
								icon: 'none'
							});
							console.log(options.data, '连接成功');
							wx.navigateTo({
								url: '/pagesMy/wifiSet?deviceId=' + options.data.deviceId + '&name=' +
									options.data.name + '&type=' + _this.type
							});
						} else {
							wx.showModal({
								title: '连接失败',
								content: '请检查：\n1.设备是否离手机太远;\n2.设备是否已被其他手机连接;\n3.请尝试重启设备后再试。',
								showCancel: false
							});
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
						if (!options.result) {
							// 蓝牙未开启
							wx.showToast({
								title: '蓝牙未开启',
								icon: 'none'
							});
							_this.nodevice = true;
							_this.errorType = 'bluetoothOff'; // 设置错误类型为蓝牙未开启
						} else {
							// 蓝牙搜索开始
							_this.searching = true;
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
						_this.searching = false;
						if (options.result) {
							console.log('蓝牙停止搜索ok');
						} else {
							console.log('蓝牙停止搜索失败');
						}
						break;
				}
			},
			// 开始或停止搜索设备
			Search: function() {
				if (this.searching) {
					xBlufi.notifyStartDiscoverBle({
						'isStart': false
					});
				} else {
					xBlufi.notifyStartDiscoverBle({
						'isStart': true
					});
					
					// 启动搜索时，设置一个超时定时器
					this.timeoutTimer = setTimeout(() => {
						// 检查15秒后是否仍未找到设备
						if (!_this.lanya) {
							xBlufi.notifyStartDiscoverBle({ 'isStart': false }); // 停止搜索
							_this.nodevice = true;
							_this.errorType = 'timeout'; // 设置错误类型为超时
							console.log('搜索超时');
						}
					}, 15000); // 设置15秒超时
				}
			},
			// 连接WiFi
			connectWiFi: function() {
				wx.showLoading({
					title: '连接蓝牙设备中...',
				})
				xBlufi.notifyConnectBle({
					isStart: true,
					deviceId: _this.lanya.deviceId,
					name: _this.lanya.name
				});
			}
		}
	}
</script>

<style scoped lang="less">
	.page {
		width: 100%;
		padding: 0 0 300rpx;
		background: #FFFFFF;
		box-sizing: border-box;
	}

	.search {
		image {
			width: 620rpx;
			height: 620rpx;
			margin-top: 120rpx;
		}

		p {
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 36rpx;
			color: #111111;
			line-height: 36rpx;
			text-align: center;
			margin-top: 80rpx;
		}
	}

	.empty {
		.title {
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 36rpx;
			color: #111111;
			line-height: 36rpx;
			text-align: center;
			margin-top: 158rpx;
		}

		&>image {
			width: 400rpx;
			height: 366rpx;
			margin-top: 48rpx;
		}

		.tip {
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #111111;
			line-height: 36rpx;
			text-align: center;
			margin-top: 53rpx;
		}

		.warn {
			background: rgba(27, 80, 255, 0.06);
			border-radius: 28rpx;
			padding: 10rpx 24rpx;
			margin-top: 48rpx;

			image {
				width: 26rpx;
				height: 26rpx;
			}

			span {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 26rpx;
				color: #1B50FF;
				line-height: 37rpx;
				margin-left: 8rpx;
			}
		}
	}

	.zt_btn {
		width: calc(100% - 120rpx);
		position: fixed;
		left: 60rpx;
		bottom: 201rpx;
	}

	.alert {
		padding: 54rpx 40rpx 0;

		.title {
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 36rpx;
			color: #111111;
			line-height: 36rpx;
			text-align: center;
			margin-bottom: 19rpx;
		}

		p {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 30rpx;
			color: #111111;
			line-height: 65rpx;
			text-align: left;
			margin-top: 24rpx;
		}

		.btn {
			width: calc(100% - 108rpx);
			height: 90rpx;
			background: #D9F159;
			border-radius: 16rpx;
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #252525;
			line-height: 90rpx;
			text-align: center;
			margin: 113rpx 54rpx 0;
			letter-spacing: 2rpx;
		}
	}

	.connect {
		padding: 66rpx 40rpx 30rpx;

		.title {
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 36rpx;
			color: #111111;
			line-height: 36rpx;
			text-align: center;
		}

		image {
			width: 504rpx;
			height: 254rpx;
			margin-top: 37rpx;
		}

		.tip {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 30rpx;
			color: #111111;
			line-height: 36rpx;
			margin-top: 40rpx;
		}

		.btn {
			width: 100%;
			height: 90rpx;
			background: #D9F159;
			border-radius: 16rpx;
			font-family: PingFang-SC, PingFang-SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #252525;
			line-height: 90rpx;
			text-align: center;
			margin-top: 101rpx;
			letter-spacing: 2rpx;
		}
	}
    /* 公共样式，用于居中 */
	.adffcac{
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.adfac{
		display: flex;
		align-items: center;
	}
</style>