<template>
	<view>
		<view class="title" @click="openBluetoothAdapter" style="margin-bottom: 10px;">初始化蓝牙</view>
		<input class="classInput" type="" :value="stringToSend" @input="stringToSendInputHandle" />
		<view class="title" @click="writeBLECharacteristicValue" style="margin-top: 10px;">触发执行</view>
		<view class="title" @click="closeBluetoothAdapter" style="color: red;margin-top:40px;">断开蓝牙</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				onBluetoothDeviceFoundcustom: '',
				deviceId: '',
				stringToSend: '$D50504010300#', // D50604010000
				setInterTimeBEL: null
			}
		},
		onLoad() {
		},
		methods: {
			// // 输入框改变时触发
			// stringToSendInputHandle(e) {
			// 	console.log('输入框改变时触发', e);
			// 	this.stringToSend = e.target.value
			// },
			// 打开GPS定位！！！打开GPS定位新买的荣耀才能触发uni.onBluetoothDeviceFound监听！！！！
			checkAndOpenGPS() {
				var Context = plus.android.importClass("android.content.Context");
				var LocationManager = plus.android.importClass("android.location.LocationManager");
				var main = plus.android.runtimeMainActivity();

				// 获取系统的 LocationManager 服务
				var locationManager = main.getSystemService(Context.LOCATION_SERVICE);

				// 检查 GPS 是否开启
				var isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
				var isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); // 检查网络定位服务
				// 位置服务已开启，不进行任何操作
				if (isGPSEnabled || isNetworkEnabled) {
					console.log("位置服务已开启");
					this.openBluetoothAdapter()
				} else {
					console.log("位置服务未开启，跳转到设置页面");
					// 位置服务未开启，引导用户打开 GPS 设置页面
					var Intent = plus.android.importClass("android.content.Intent");
					var Settings = plus.android.importClass("android.provider.Settings");
					var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					main.startActivity(intent);

					// 提示用户手动开启 GPS
					plus.nativeUI.alert("请手动开启GPS！");
				}
			},
			// 初始化蓝牙
			openBluetoothAdapter() {
				let that = this
				that.closeBluetoothAdapter()
				console.log('初始化蓝牙');
				uni.openBluetoothAdapter({
					success(res) {
						console.log(res)
						that.startBluetoothDevicesDiscovery()
					},
					fail(res) {
						console.log('初始化蓝牙失败', res)
						setTimeout(() => {
							that.openBluetoothAdapter()
						}, 5000)
					}
				})
			},
			// 开始搜索蓝牙设备
			startBluetoothDevicesDiscovery() {
				console.log('开始搜索蓝牙设备');
				let that = this
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
						that.onBluetoothDeviceFound()
					}
				})
			},
			// 监听设备发现
			onBluetoothDeviceFound() {
				let that = this
				this.onBluetoothDeviceFoundcustom = uni.onBluetoothDeviceFound((res) => {
					console.log('监听设备发现', res.devices[0]);
					if (res.devices[0].name === 'ACP60205') {
						console.log('hello，厉害，找到啦，啦啦啦~~~');
						// 连接成功后，停止设备搜索
						uni.stopBluetoothDevicesDiscovery();
						that.deviceId = res.devices[0].deviceId; // 获取设备ID
						that.createBLEConnection()
						// setTimeout(()=>{this.getBLEDeviceServices()},3000)
					}
				})
			},
			// 获取服务列表 + 获取特征列表
			getBLEDeviceServices() {
				let that = this
				uni.getBLEDeviceServices({
					deviceId: that.deviceId,
					success: (res) => {
						console.log('服务列表', res.services);
						res.services.forEach(service => {
							uni.getBLEDeviceCharacteristics({
							 	deviceId: that.deviceId,
								serviceId: service.uuid,
								success: function(charRes) {
									console.log('特征列表', charRes.characteristics);
								},
								fail: function(err) {
									console.error('获取特征失败', err)
								}
							});
						});
					},
					fail: function(err) {
						console.error('获取服务失败', err)
					}
				})

			},
			// 连接到设备
			createBLEConnection() {
				let that = this
				console.log('连接到设备that.deviceId', that.deviceId);
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success: function() {
						console.log('连接成功')
						that.belStatus()
					},
					fail: function(err) {
						console.error('连接失败', err)
						setTimeout(() => {
							that.openBluetoothAdapter()
						}, 5000)
					}
				})
			},

			// 检测BEL是否连接状态
			belStatus() {
				clearInterval(this.setInterTimeBEL)
				this.setInterTimeBEL = setInterval(() => {
					this.getConnectedBluetoothDevices()
				}, 5000)
			},
			// 检查设备连接状态
			getConnectedBluetoothDevices() {
				let that = this
				uni.getConnectedBluetoothDevices({
					success(res) {
						console.log('当前已连接的设备:', res.devices);
						if (res.devices.length <= 0) {
							that.openBluetoothAdapter()
							clearInterval(that.setInterTimeBEL)
						}
					},
					fail(err) {
						console.log('获取已连接设备失败:', err)
						that.openBluetoothAdapter()
					}
				})
			},
			// 发送蓝牙内容
			writeBLECharacteristicValue() {
				let that = this
				// 要发送的字符串
				// $D50504030231#
				// D5---5米距离
				// 06---
				const dataToSend = that.stringToByteArray(that.stringToSend)
				console.log(' dataToSend.buffer', dataToSend.buffer)
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId, // 设备ID
					serviceId: '0000ffe0-0000-1000-8000-00805f9b34fb', // 服务ID
					characteristicId: '0000ffe1-0000-1000-8000-00805f9b34fb', // 特征ID
					value: dataToSend.buffer,
					writeType: 'write',
					success: () => {
						console.log('发送内容成功')
					},
					fail: (err) => {
						console.error('发送内容失败', err)
					}
				})
			},
			// 处理发送的内容
			stringToByteArray(str) {
				const byteArray = new Uint8Array(str.length);
				for (let i = 0; i < str.length; i++) {
					byteArray[i] = str.charCodeAt(i)
				}
				return byteArray;
			},
			// 断开蓝牙
			closeBluetoothAdapter(title) {
				let that = this
				uni.closeBluetoothAdapter({
					success() {
						console.log('蓝牙适配器关闭成功');
					},
					fail(err) {
						console.log('关闭蓝牙适配器失败: ', err);
					}
				});
			},
		}
	}
</script>

<style>
	.title {
		font-size: 36rpx;
		color: #8f8f94;
		text-align: center;
	}

	.classInput {
		border: 1px solid #ccc;
		height: 80rpx;
		width: 300px;
		text-align: center;
		margin: auto;

	}
</style>