<template>
	<view class="wrapper">
		<CustomNavbar title="蓝牙扫描" @gobackDeal="gobackDeal('blueSearch')">
		</CustomNavbar>
		<view class="" style="text-align: center; color: #000; font-size: 32rpx; margin-top:20rpx;">
			{{ pageLoadText }}
		</view>
		<view class="body-wrapper">
			<!-- 横向均分 -->
			
			<!-- <view class="found"></view> -->

			<view class="devices_summary found">已发现 {{ devices.length }} 个BLE设备：</view>
			<scroll-view class="device_list" scroll-y scroll-with-animation>
				<view :data-device-id="item.deviceId" :data-device-name="item.name || item.localName" @tap="goto_Comm"
					class="device_item" hover-class="device_item_hover" v-for="(item, index) in devices" :key="index">
					<view style="font-size: 32rpx; color: #000">{{ item.name }}</view>

					<view style="font-size: 27rpx; color: #676767">RSSI: {{ item.RSSI}}dBm</view>

					<view style="font-size: 27rpx; color: #676767">{{ item.deviceId}}</view>
				</view>
			</scroll-view>
			
		</view>
		<button :loading="misScanding" class="button_sp" hover-class="button_sp2"
			@tap="openBluetoothAdapter">{{ scandbutName }}</button>
	</view>
</template>

<script>
	import {
		showCustomModal,
		showCustomToast,
		commonStateCodeDeal,
		popuper,
		storager,
		pager
	} from "../../common/util.js"
	import CustomNavbar from '@/pages/component/CustomNavbar.vue';
	import {
		blueToothMixin
	} from '../../common/mixin.js'

	function inArray(arr, key, val) {
		for (let i = 0; i < arr.length; i++) {
			if (arr[i][key] === val) {
				return i;
			}
		}
		return -1;
	}

	// ArrayBuffer转16进度字符串示例
	function ab2hex(buffer) {
		var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
			return ('00' + bit.toString(16)).slice(-2);
		});
		return hexArr.join('');
	}
	export default {
		mixins: [blueToothMixin],
		components: {
		    CustomNavbar,
		  },
		onBackPress(options) {
			this.gobackDeal()
			return true
		},
		data() {
			return {
				devices: [],
				connected: false,
				chs: [],
				misScanding: false,
				scandbutName: '搜索蓝牙设备',
				name: '',
				deviceId: '',
				redirectUrl: '/pages/home/home' // 目标跳转过来的页面，连接后直接跳转过去.默认跳转首页
				// canWrite: false
			};
		},
		onShow() {
			uni.hideLoading()
		},
		onLoad(options) {
			
		},
		methods: {
			gobackDeal(){
				uni.reLaunch({
					// url: '/pages/home/home'// this.redirectUrl,
					url: '/pages/home/home'
				});
			},
			openBluetoothAdapter() {
				this.misScanding = false;
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log('openBluetoothAdapter success', res);
						this.startBluetoothDevicesDiscovery();
					},
					fail: (res) => {
						console.log(JSON.stringify(res))
						if (res.errCode === 10001) {
							uni.showToast({
								title: '蓝牙未开启，请确认后重试',
								icon: 'none'
							})
							uni.onBluetoothAdapterStateChange(function(res) {
								console.log('onBluetoothAdapterStateChange', res);
								if (res.available) {
									this.startBluetoothDevicesDiscovery();
								}
							});
						}
					}
				});
			},
			startBluetoothDevicesDiscovery() {
				var that = this;
				if (this._discoveryStarted) {
					this.stopBluetoothDevicesDiscovery();
					return;
				}
				// this.setData({
				this.misScanding = true
				this.scandbutName = '正在搜索，点击停止'
				this.devices = []
				this.chs = []
				// });
				//console.log('lisn3188---------- misScanding = ', this.misScanding)
				this._discoveryStarted = true;
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: (res) => {
						setTimeout(function() {
							console.log('----BluetoothDevicesDiscovery finish---- ');
							if (that._discoveryStarted) {
								that.stopBluetoothDevicesDiscovery();
							}
						}, 20000);
						console.log('startBluetoothDevicesDiscovery success', res);
						this.onBluetoothDeviceFound();
					}
				});
			},

			stopBluetoothDevicesDiscovery() {
				this._discoveryStarted = false;
				uni.stopBluetoothDevicesDiscovery();
				// this.setData({
				this.misScanding = false
				this.scandbutName = '重新刷新列表'
				// });
				//console.log('lisn3188---------- misScanding = ', this.misScanding)
			},

			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					res.devices.forEach((device) => {
						if (!device.name && !device.localName) {
							return;
						}
						const foundDevices = this.devices;
						console.log('设备列表', foundDevices)
						// 查找当前已发现蓝牙数据，如果可以匹配到，则更新对应数据
						const idx = inArray(foundDevices, 'deviceId', device.deviceId);
						// const data = {};
						if (idx === -1) { // 如果没有发现列表已有蓝牙数据则新增
							this.devices[foundDevices.length] = device;
						} else {
							this.devices[idx] = device;
						}
						const tempDevices = JSON.parse(JSON.stringify(this.devices))
						this.devices = tempDevices

						// this.setData(data);
					});
				});
			},

			goto_Comm(e) {
				popuper.showLoading({
					title: '设备连接中...'
				})
				// this.$globalData.ble_device = e.currentTarget.dataset;
				const deviceInfo = e.currentTarget.dataset
				this.deviceId = deviceInfo.deviceId
				this.stopBluetoothDevicesDiscovery();
				uni.setStorageSync('deviceInfo', deviceInfo)
					console.log('*****开始连接蓝牙');
				this.startLink()
				// uni.reLaunch({
				// 	url: '/pages/home/home'
				// });
			},
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter();
				this._discoveryStarted = false;
			}
		}
	};
</script>
<style lang="scss">
	.wrapper{
		width: 100vw;
		height: calc(100vh-44rpx);
		padding-top: 44rpx;
		background: linear-gradient(180deg, #007AFF 0%, #419AFF 16%, #EFF1F4 43%);
	}
	.body-wrapper{
		margin: 0 auto;
		/* display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		gap: 20rpx; */
		width: 690rpx;
		height: 70vh;
		padding-top: 20rpx;
		background: #FFFFFF;
		border-radius: 10rpx;
		.found{
			width: 642rpx;
			height: 60rpx;
			margin: 20rpx auto;
			background: #D5D7DB;
			border-radius: 30rpx;
			font-size: 29rpx;
			color: #000000;
			line-height: 60rpx;
			text-align: center;
		}
	}
	page {
		color: #333;
	}

/* 	.devices_summary {
		padding: 10px;
		font-size: 16px;
		background-color: hsl(216, 5%, 22%);
		color: #fff;
		align-items: center;
		justify-content: center;
		display: flex;
	} */

	.device_list {
		max-height: 60vh;
		margin: 50px 5px;
		margin-top: 5px;
		// border: 1px solid #eee;
		border-radius: 5px;
		width: auto;
	}

	.device_item {
		border-bottom: 1px solid #E3E6EC;
		padding: 10px;
		color: #666;
	}

	.device_item_hover {
		background-color: rgba(0, 0, 0, 0.1);
	}

	.connected_info {
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #f0f0f0;
		padding: 10px;
		padding-bottom: 20px;
		margin-bottom: env(safe-area-inset-bottom);
		font-size: 14px;
		min-height: 100px;
		box-shadow: 0px 0px 3px 0px;
	}

	.connected_info .operation {
		position: absolute;
		display: inline-block;
		right: 30px;
	}

	.button_sp {
		// margin-left: 10px;
		// margin-right: 10px;
		// margin-top: 5px;
		// background-color: #10b7ff;
		// color: #fff;
		// font-size: 15px;
		width: 686rpx;
		height: 70rpx;
		background: #007AFF;
		border-radius: 35px;
		font-size: 29rpx;
		color: #FFFFFF;
		margin-top: 20rpx;
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.button_sp2 {
		margin-left: 10px;
		margin-right: 10px;
		margin-top: 5px;
		background-color: #757575;
		color: #fff;
	}

	.flex-wrp {
		height: auto;
		display: flex;
		background-color: #ffffff;
	}

	/*横向布局  */
	.layout_horizontal {
		display: flex;
		/*row 横向  column 列表  */
		flex-direction: row;
	}

	/*纵向布局  */
	.layout_vertical {
		height: 100rpx;
		display: flex;
		/*row 横向  column 列表  */
		flex-direction: column;
	}

	/*划线  */
	.line {
		background-color: blue;
		height: 5px;
		width: 100%;
	}

	.div {
		background-color: white;
		height: 10px;
		width: 10px;
	}
</style>