<template>
	<view class="content">
		<!-- <view class="user_name">
			<view class="text_user">无线名称</view>
			<u-input class="user_pass" v-model="userInfo.name" border="bottom" placeholder="请输入您的无线名称"></u-input>
			<view class="text_user">无线密码</view>
			<view class="password">
				<u-input class="user_pass" :type="type" border="bottom" v-model="userInfo.password"
					placeholder="请输入您的无线密码">
					<template slot="suffix">
						<u-icon name="eye" @click="showpassword"></u-icon>
					</template>
				</u-input>
			</view>
		</view> -->
		<view class="but_login" @click="writeData">发送</view>
		<!-- <view class="title">蓝牙设备</view> -->
		<view class="uist">
			<view @click="createBLEConnection(item)" class="item" v-for="(item,index) in list" :key='index'>
				<text>{{item.name}}</text>
				<!-- <view>{{item.deviceId}}</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				notify: '',
				serviceId: '',
				deviceId: '',
				userInfo: {
					name: '',
					password: '',
				},
				type: 'password',
				bluthlist: [],
				devicesList: [],
				list: [],
				actlanya:{}
			}
		},
		onLoad() {
			
		},
		onShow() {
			uni.closeBluetoothAdapter({
			  success(res) {
			    console.log(res)
			  }
			})
			this.openBluetoothAdapter();
		},
		methods: {
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: res => {
						this.startBluetoothDevicesDiscovery();
					},
					fail: res => {
						if (res.errCode === 10001) {
							uni.showToast({
								title: '请打开蓝牙',
								icon: 'none'
							});
							uni.onBluetoothAdapterStateChange(res => {
								// console.log('蓝牙适配器状态发生变化：', res)
								if (res.available) {
									//这里是调用开启蓝牙搜索
									this.startBluetoothDevicesDiscovery();
								}
							});
						}
					}
				});
			},
			startBluetoothDevicesDiscovery() {
				let arrlists = []
				let that = this;
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: res => {
						uni.onBluetoothDeviceFound(devices => {
							// 监听到新设备后重新获取设备列表
							// console.log(devices)
						});
						setTimeout(function() {
						  uni.stopBluetoothDevicesDiscovery({
							success: function(res) {
							//   console.log('停止搜索蓝牙设备成功');
							
							  // 获取蓝牙设备列表
							  uni.getBluetoothDevices({
								success: function(res) {
									let filteredArray = res.devices.filter(item => item.name.trim() !== "");
									console.log('获取蓝牙设备列表成功', [...new Set(filteredArray)]);
									// that.list = res.devices;
									console.log(res.devices);
									res.devices.forEach(item => {
										if (item.name != "") {
										// if (item.name.slice(0, 7) == 'PaperTakingMachine') {
										// item.name = 'PaperTakingMachine'
										// if (item.name.slice(0, 7) == 'EDIFIER') {
										// item.name = 'EDIFIER'
											arrlists.push(item)
										} 
									})
									that.list = [...new Set(arrlists)]
								}
							  });
							  
							  
							  
							  
							  
							  
							  
							  uni.getConnectedBluetoothDevices({
							    success: function(res) {
							      console.log('已连接的蓝牙设备列表:', res.devices);
							      res.devices.forEach(device => {
							        console.log('设备名称:', device.name);
							        console.log('设备地址:', device.deviceId);
							      });
							    },
							    fail: function(err) {
							      console.error('获取已连接蓝牙设备失败:', err);
							    }
							  });
							  
							  
							  
							}
						  });
						}, 60000);
					}
				});
			},
			//4、建立连接    给个点击蓝牙事件调用这个回调函数即可
			createBLEConnection(device) {
				console.log(device.deviceId)
				this.actlanya = device;
				const deviceId = device.deviceId;
				uni.createBLEConnection({
					deviceId,
					success: res => {
						// console.log(res.errMsg, '连接')
						uni.showLoading({
							title: '连接蓝牙设备中...'
						});
						if (res.errMsg == 'createBLEConnection:ok') {
							// console.log("连接成功")
							uni.showLoading({
								title: '连接成功'
							});
							this.getServiceId();
							setTimeout(() => {
								uni.hideLoading();
								// uni.navigateTo({
								// 	url: '/pages/device/wifilist/index'
								// })
							}, 1000)
						} else {
							uni.showLoading({
								title: '连接失败'
							});
						}
					},
					fail: res => {
						console.log(res)
					}
				});
			   //连接成功后停止蓝牙搜索
				this.stopBluetoothDevicesDiscovery();
			},
			// 获取服务id
			getServiceId() {
				console.log(this.actlanya.deviceId)
				let that = this;
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: that.actlanya.deviceId,
						success(res) {
							console.log("获取服务Id", res)
							let model = res.services[1];
							that.deviceId = that.actlanya.deviceId;
							that.serviceId = model.uuid;
							console.log("deviceId", that.deviceId)
							console.log("serviceId", that.serviceId)
							// 调用蓝牙监听和写入功能
							that.getCharacteId();
						},
						fail: res => {
							console.log(res)
						}
					})
				}, 2000);
			},
			// 获取蓝牙低功耗设备某个服务中所有特征
			getCharacteId(){
				let that = this;
				console.log(that.deviceId)
				console.log(that.serviceId)
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId, // 蓝牙设备id
					serviceId: that.serviceId, // 蓝牙服务UUID
					success(res) {
						console.log('数据监听', res);
						// that.notify = res.characteristics[0].uuid
						// uni.setStorageSync("writeId", res.characteristics[1].uuid);
						// that.startNotice();
						
						// for (var i = 0; i < res.characteristics.length; i++) {
						// 	if (res.characteristics[i].properties.notify === true) {
						// 		that.characteristics = res.characteristics[i];
						// 		that.characteristicId = res.characteristics[i].uuid;
						// 	}

						// 	if (res.characteristics[i].properties.write === true) {
						// 		that.characteristics = res.characteristics[i];
						// 		that.writeId = res.characteristics[i].uuid;
						// 	}
						// }
						// uni.setStorageSync("characteristicId", that.characteristicId);
						// uni.setStorageSync("writeId", that.writeId);
						
						
						// res.characteristics.forEach(item => {
						// 	if (item.properties.notify === true) {
						// 		// 监听
						// 		that.notify = item.uuid;
						// 		console.log(that.notify)
						// 		that.startNotice();
						// 	}
						// 	// 002
						// 	if (item.properties.write === true) {
						// 		// 写入
						// 		let writeId = item.uuid;
						// 		console.log(item.uuid)
						// 		uni.setStorageSync("writeId", item.uuid);
						// 	}
						// });
					},
					fail(err) {
						console.log("数据监听失败", err)
					}
				})
			},
			// 启用低功耗蓝牙设备特征值变化时的notify功能
			startNotice(){
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					characteristicId: that.notify,
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					state: true,
					success(res) {
						// 监听低功耗蓝牙设备的特征值变化
						uni.onBLECharacteristicValueChange(result => {
							console.log("监听低功耗蓝牙设备的特征值变化", result);
							if (result.value) {
								let decoder = new TextDecoder('utf-8');
								let data = decoder.decode(result.value);
								// let data = result.value;
								console.log('帽子返回数据', data)
							}
						})
					}
				});
			},
			// 蓝牙发送数据
			writeData(buffer){
				let that = this;
				console.log(that.deviceId)
				console.log(uni.getStorageSync("writeId"))
				console.log(that.serviceId)
				return new Promise((resolve, reject) => {
					uni.writeBLECharacteristicValue({
						deviceId: that.deviceId,
						characteristicId: uni.getStorageSync("writeId"),
						serviceId: that.serviceId,
						value: '1',
						success(res) {
							console.log("writeBLECharacteristicValue success", res);
							resolve();
						},
						fail(err) {
							console.log("报错了", err);
							reject();
						}
					});
				});
			},
			// onBLECharacteristicValueChange() {
			// 	console.log("开始接收")

			// 	var that = this;
			// 	uni.onBLECharacteristicValueChange((res) => {
			// 		// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，所以 ArrayBuffer 转 16进制 在转字符串

			// 		that.www = that.hexCharCodeToStr(that.buf2hex(res.value));
					
			// 	});
			// },
						
						
						
			// 获取搜索到的设备信息
			// getBlue() {
			// 	var that = this
			// 	uni.getBluetoothDevices({
			// 		success(res) {
			// 			console.log("获取设备成功", res)
			// 			// that.bluthlist = res.devices
			// 		},
			// 		fail(err) {
			// 			// console.log("获取设备失败", err)
			// 		}
			// 	})
			// 	setTimeout(() => {
			// 	    uni.stopBluetoothDevicesDiscovery({
			// 	        success: (res) => {
			// 	            // console.log("停止搜索成功", res);
			// 	        },
			// 	        fail: (error) => {
			// 	            // console.log("停止搜索失败", error);
			// 	        }
			// 	    });
			// 	}, 5000);  // 10秒后停止搜索
			// },
			//停止蓝牙搜搜      
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery();
				this.discoveryStarted = false;
			},
			login() {
				let _this = this;
				if (_this.userInfo.name.length == 0) {
					this.$u.toast('请输入您的手机号')
					return
				}
				if (_this.userInfo.password.length == 0) {
					this.$u.toast('请输入您的密码')
					return
				}
				return
				const params = {
					url: '/login',
					data: {
						username: _this.userInfo.name,
						password: _this.userInfo.password,
					},
				}
				this.$request(params).then(res => {
					uni.setStorageSync('token', res.token);
					_this.$wskj.switchTab('/pages/home_index/home');
				})
				//_this.$wskj.switchTab('/pages/home_index/home');
			},
			// 密码隐藏显示
			showpassword() {
				this.type = this.type === 'password' ? 'text' : 'password';
			},
		}
	}
</script>

<style lang="less">
	.title{
		font-family: PingFangSC, PingFang SC;
		font-weight: 600;
		font-size: 42rpx;
		color: #333333;
		text-align: center;
	}
	
	.uist{
		padding: 0 60rpx;
		.item{
			display: flex;
			align-items: center;
			justify-content: space-between;
			line-height: 100rpx;
			border-bottom: 1px solid #ccc;
			text{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 34rpx;
				color: #333333;
				font-weight: bold;
			}
			view{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 30rpx;
				color: #333333;
			}
		}
	}
	
	/deep/ .u-input {
		border: 2rpx solid #dadbde;
		border-radius: 10rpx;
	}

	.wx_login {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 28px;

		.iv_login {
			width: 78rpx;
			height: 78rpx;
		}
	}

	.third_party {
		display: flex;
		margin-left: 66rpx;
		margin-top: 120rpx;
		align-items: center;

		.border {
			width: 238rpx;
			border-bottom: 2rpx solid #999999;
		}

		.third {
			padding: 0rpx 20rpx;
		}
	}

	.content {
		margin-top: 30rpx;

		.privacy_policy {
			margin-top: 20rpx;
			margin-left: 87rpx;
			font-size: 24rpx;

			.text {
				color: #FB4B4E;
			}

		}

		.login_bg {
			height: 180px;
			width: 100%;
			background: linear-gradient(91deg, #FCD4D2 0%, #FDEDEE 100%);
			// view 显示一行
			display: flex;
			// view 俩边撑开
			justify-content: space-around;

			.login_title {
				color: #FFFFFF;
				margin-top: 70px;
			}

			.iv_login {
				width: 100px;
				height: 100px;
				bottom: -30%;
			}

		}

		.but_login {
			width: 400rpx;
			text-align: center;
			justify-content: center;
			line-height: 88rpx;
			font-weight: 500;
			margin: 0 auto;
			color: white;
			height: 88rpx;
			border-radius: 44rpx 44rpx 44rpx 44rpx;
			background: linear-gradient(89deg, #FFBFBC 0%, #FB262A 100%);
		}

		.user_name {
			margin-top: -50rpx;
			background-color: wheat;
			border-radius: 20px 20px 0px 0px;
			background: white;
			padding: 100rpx 60rpx;

			.user_phone {
				font-size: 12px;
				padding-top: 38rpx;
				padding-bottom: 28rpx;
				border-bottom: 2rpx solid #999999;
			}

			.text_user {
				margin-top: 60rpx;
				font-size: 16px;
				font-weight: 600;
			}

			.user_pass {
				margin-top: 20rpx;
				font-size: 12px;
			}

			.password {
				display: flex;

				.iv_pass {
					height: 30rpx;
					width: 30rpx;
				}

				.user_pass {
					margin-top: 20rpx;
					font-size: 12px;
				}
			}
		}
	}
</style>