<script>
var xBlufi = require("./utils/blufi/xBlufi.js")
var call
var data_call
var ble_id = "1231"
var ble_url

var user_info

// 在文件顶部添加一个变量来存储当前连接的MAC地址
var current_connected_mac = null;

export default {
	globalData: {
		userInfo: null,
		topicTypeIndex: 0,
		token: "",
		isShow: true,
		bleInfo: {
			current_connected_mac: null,
			ble_id: "1231",
			ble_url: null,
			devicesList: [],
			xBlufi: xBlufi
		}
	},
	created() {
		// #ifdef APP-PLUS
		plus.navigator.closeSplashscreen()
		// #endif  
		console.log('App @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Launch')
		// #ifndef APP-PLUS
		console.log('App 1111111111111Launch')
		xBlufi.initXBlufi(1);
		console.log("xBlufi初始化", xBlufi) // 修改日志输出，确保输出有意义的信息  
		xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent); // 取消注释，确保事件监听被正确设置  
		xBlufi.notifyStartDiscoverBle({
			'isStart': true
		})
		// #endif	

		// 添加以下代码，将方法绑定到 uni 全局对象
		uni.$emit('init_app_methods', {
			set_ble_mac: this.set_ble_mac.bind(this)
		})
	},
	onLaunch(options) {
		uni.setInnerAudioOption({
			obeyMuteSwitch: false
		})
		
	},
	onShow: function () {

	},
	onHide: function () {

	},
	methods: {
		get_ble_name(callback) {
			if (callback != undefined) {
				xBlufi.notifyConnectBle({
					isStart: false,
					deviceId: ble_id,
					name: ""
				})
				console.log('关闭蓝牙接口', ble_id);
				call = callback
			}
		},
		get_ble_data(callback) {
			if (callback != undefined)
				data_call = callback;
		},
		set_ble_mac(mac) {
			const bleInfo = this.globalData.bleInfo
			// 如果MAC地址与当前连接的相同，则不重复连接
			if (mac === bleInfo.current_connected_mac) {
				console.log('设备已连接，无需重复连接')
				return
			}
			if (mac != undefined && bleInfo.devicesList) {
				const device = bleInfo.devicesList.find(device => 
					device.name && device.name.toLowerCase().includes(mac.toLowerCase())
				)
				if (device) {
					bleInfo.ble_url = ''
					uni.hideLoading()
					bleInfo.ble_id = device.deviceId
					bleInfo.xBlufi.notifyConnectBle({
						isStart: true,
						deviceId: device.deviceId
					})
					uni.showToast({
						title: "连接蓝牙设备中",
						icon: 'none',
						duration: 1500
					})
					bleInfo.xBlufi.notifyInitBleEsp32({
						deviceId: device.deviceId
					})
					// 更新全局MAC地址
					bleInfo.current_connected_mac = mac
				} else {
					uni.showToast({
						title: "未找到匹配的设备",
						icon: 'none',
						duration: 1500
					})
				}
			}
		},
		set_ble_id(id, url) {
			console.log("id", id)
			if (id != undefined) {
				ble_url = url
				uni.hideLoading()
				ble_id = id
				xBlufi.notifyConnectBle({
					isStart: true,
					deviceId: id
					// name
				})
				uni.showToast({
					title: "连接蓝牙设备中",
					icon: 'none',
					duration: 3500
				})
				xBlufi.notifyInitBleEsp32({
					deviceId: id
				})
			}
		},
		ble_send(data) {
			if (data != undefined) {
				xBlufi.notifySendCustomData({
					customData: data,
				});
			}
		},
		get_user_iphone(data) {
			return user_info;
		},
		set_user_iphone(data) {
			console.log("电话存储")
			uni.setStorage({
				key: 'user_info',
				data: data,
				success: () => {
					console.log('已经缓存，userInfo:', data.phone);
					resolve('success')
				}
			});
			user_info = data
		},
		call(e) {
			call = e;
		},
		funListenDeviceMsgEvent(options) {
			switch (options.type) {
				case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
					if (!options.result) {
						// 清除全局MAC地址
						this.globalData.bleInfo.current_connected_mac = null;
						const pages = getCurrentPages();
						const currentPage = pages[pages.length - 1];
						console.log("当前页面路径", currentPage.route)
						if (currentPage.route != 'pages/index/index') {
							uni.showModal({
								title: '设备提示！',
								content: '与设备断开请重联',
								showCancel: false,
								success: function (res) {
									uni.reLaunch({
										url: '/pages/index/index'
									});
								}
							});
						}
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT:
					uni.hideLoading();
					if (!options.result) {
						uni.hideLoading();
						uni.showModal({
							title: '温馨提示',
							content: '配网失败，请确认是2.4G模式并且账户密码正确',
							showCancel: false //是否显示取消按钮
						});
					} else {
						if (options.data.progress == 100) {
							let ssid = options.data.ssid;
							uni.hideLoading();
							uni.showModal({
								title: '温馨提示',
								content: `连接成功路由器`,
								showCancel: false,
								//是否显示取消按钮
								success: function (res) {
									// uni.navigateBack()
									uni.navigateTo({
										url: '/pages/dd/xiaoai'
									});
									console.log("确定成功之后 返回 ");
								}
							});
						}
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
					if (data_call != undefined) {
						data_call(options.data)
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
					if (options.result) {
						this.globalData.bleInfo.devicesList = options.data; // 假设你想在组件内部使用这个变量，应该这样设置  
						console.log("获取设备列表", this.globalData.bleInfo.devicesList)
						if (call != undefined) {
							console.log("获取设备列表", this.globalData.bleInfo.devicesList)
							call(this.globalData.bleInfo.devicesList)
						}
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
					console.log("连接回调：" + JSON.stringify(options));
					if (options.result) {
						uni.hideLoading();
						uni.showToast({
							title: '连接成功',
							icon: 'none'
						});
						console.log("连接进入：", ble_url);
						// uni.navigateTo({ url: ble_url });
					}
					else {
						uni.showToast({
							title: '连接超时，请重新链接',
							icon: 'none'
						});
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
					if (!options.result) {
						uni.showToast({
							title: '蓝牙未开启解决方法',
							icon: 'none',
							duration: 3000
						});
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
					if (options.result) {
						console.log('蓝牙停止搜索ok');
					} else {
						console.log('蓝牙停止搜索失败');
					}
					break;
			}
		}
	}
}
</script>

<style lang="scss">
/*每个页面公共css */
@import "uview-ui/index.scss";
@import "./common/css/iconfont.css";

// 自定义tabar样式修改
/deep/.u-tabbar__content__item__text {
	font-size: 20rpx !important;
	bottom: 10rpx !important;
}

page {
	background-color: #f8f8f8;
}
</style>
