<template>
	<view class="wrapper">
		<view class="footer">
			<!-- <button type="primary" size="mini" @click="reset">重新搜索</button> -->
			<!-- <button type="primary" size="mini" @click="getBluetoothDevices">获取蓝牙设备信息</button> -->
			<!-- <button type="primary" size="mini" @click="getBLEDeviceServices">获取服务</button> -->
<!-- 			<button type="primary" size="mini" @click="getBLEDeviceCharacteristics">进入特征</button> -->
			<button type="primary" size="mini" @click="stopBluetoothDevicesDiscovery">停止搜索蓝牙</button>
		</view>
		<view class="list">
			
		</view>
		<view v-for="(item, index) in list" :key="index" class="list">
			<view class="item">
				<text>设备名称：{{ item.name }}</text>
				<!-- <button class="button" type="default" size="mini" @click="createBLEConnection(item)">{{item.connected ? '断开' :'连接'}}</button> -->
			</view>
			<view  class="item">
				<text>设备deviceId：{{ item.deviceId }}</text>
			</view>
			<view  class="item">
				<text>信号强度RSSI：{{ item.RSSI }}</text>
			</view>
			<!-- <view  class="item">
				<text>距离：{{ item.RSSI | RSSI }}m</text>
				<button  class="button" type="default" size="mini" @click="getRssi(item)">刷新</button>
			</view> -->
		</view>
	</view>
</template>

<script>
	//定位需要根据算法 RSSI的值莱确定
	let timeoff = null
	import {bluetoothInt,bluetoothLoc} from '@/common/api.js'
	export default {
		data() {
			return {
				list:[],
				deviceId:'',
				serviceId:'',
				characteristics:[],
				characteristicId:'',
				blueObj:{},
				times:'',
				location:{
					
				}
			}
		},
		filters:{
			RSSI(val){
				if(val){  //A为距离设备1米时的rssi 绝对值。 n为环境衰减因子。
					let A = 40
					let n = 6
					return Math.pow(10,((Math.abs(val) - A) / (10 * n))).toFixed(2)
				}
			}
		},
		watch:{
			list(val){
				
			}
		},
		destroyed(){
			this.stopBluetoothDevicesDiscovery()
			
			clearInterval(timeoff)
		},
		onLoad(){
			uni.openBluetoothAdapter({
				success:(res)=> { 
					uni.getBluetoothAdapterState({//蓝牙的匹配状态
						success:(res1)=>{
							console.log(res1,'本机设备的蓝牙已打开')
							bluetoothInt().then(res =>{
								console.log(res)
								this.blueObj = res.data
								this.startBluetoothDeviceDiscovery()
								this.getLocation()
								this.startInt()
							}).catch(e =>{
								
							})
							
						},
						fail(error) {
							uni.showToast({icon:'none',duration:3000,title: '查看手机蓝牙是否打开'});
						}
					});
					
				},
				fail:err=>{ 
					uni.showToast({icon:'none',title: '查看手机蓝牙是否打开'});
				}
			})
		},
		methods: {
			reset(){
				clearInterval(timeoff)
				uni.openBluetoothAdapter({
					success:(res)=> { 
						uni.getBluetoothAdapterState({//蓝牙的匹配状态
							success:(res1)=>{
								this.startInt()
							},
							fail(error) {
								uni.showToast({icon:'none',duration:3000,title: '查看手机蓝牙是否打开'});
							}
						});
						
					},
					fail:err=>{ 
						uni.showToast({icon:'none',title: '查看手机蓝牙是否打开'});
					}
				})
			},
			stopBluetoothDevicesDiscovery(){
				clearInterval(timeoff)
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						uni.closeBluetoothAdapter()
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			 startInt(){
				if(this.blueObj.flag == 1) return
				timeoff = setInterval( async () =>{
					this.list = Array.from(new Set(this.list))
					let str = ''
					this.list.map((item) =>{
						str+=item.name+','+item.RSSI+";"
					})
					str+=uni.getStorageSync('storage_users').uid+";"+this.location.latitude+','+this.location.longitude
					console.log(str)
					try{
						let data = await bluetoothLoc({rssis:str})
						uni.stopBluetoothDevicesDiscovery()
						setTimeout(() =>{
							this.getLocation()
							this.startBluetoothDeviceDiscovery()
						},1000)
					}
					catch(e){
						console.log(e)
						clearInterval(timeoff)
					}
				},this.blueObj.seconds*1000)
			},
			getLocation(){
				uni.getLocation({
					type: 'gcj02 ',
					geocode: true,
					success:async (res)  => {
						this.location = res
					},
					fail: (e) => {
						console.log(e)
						plus.nativeUI.toast("获取位置失败")
					}
				});
			},
			getRssi(item){
				if(item.connected){
					uni.getBLEDeviceRSSI({
						deviceId:item.deviceId,
						success(res) {
							console.log(res)
							item.RSSI = res.RSSI
						},
					})
				}
				else{
					uni.createBLEConnection({
					  deviceId:item.deviceId,
					  success(res) {
						console.log(res)
						uni.getBLEDeviceRSSI({
							deviceId:item.deviceId,
							success(res) {
								console.log(res)
								item.RSSI = res.RSSI
							},
						})
						console.log("蓝牙连接成功")
					  },fail(res) {
						uni.showToast({icon:'none',title: '蓝牙连接失败'});
						console.log("蓝牙连接失败",res)
					  }
					})
				}
			},
			startBluetoothDeviceDiscovery(){
				this.list = []
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('startBluetoothDevicesDiscovery success', res)
						// 发现外围设备
						this.onBluetoothDeviceFound()
					},fail:err=>{
						console.log(err,'错误信息')
					}
				})
			},
			// 发现外围设备
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					if(res.devices[0].localName.indexOf(this.blueObj.preName) != '-1'){
						if(this.list.indexOf(res.devices[0].deviceId)==-1){
							this.list.push({
								name:res.devices[0].name,
								deviceId:res.devices[0].deviceId,
								RSSI:res.devices[0].RSSI,
								connected:false
							})
						}
						this.list = Array.from(new Set(this.list))
					}
					
				})
			},
			//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				console.log("获取蓝牙设备");
				uni.getBluetoothDevices({
					success: res => {
						console.log('获取蓝牙设备成功:');
						console.log(res.devices);
					}
				});
			},
			//选择设备连接吧deviceId传进来
			createBLEConnection(item){
				//连接蓝牙
				this.deviceId = item.deviceId
				if(item.connected){
					uni.closeBLEConnection({
						deviceId:item.deviceId,
					})
				}
				else{
					uni.createBLEConnection({
					  deviceId:this.deviceId,
					  success(res) {
						console.log(res)
						console.log("蓝牙连接成功")
					  },fail(res) {
						console.log("蓝牙连接失败",res)
					  }
					})
				}
				
			},
			// 停止搜寻蓝牙设备
			
			//获取蓝牙特征
			getBLEDeviceCharacteristics(){
				console.log("进入特征");
				setTimeout(()=>{
					uni.getBLEDeviceCharacteristics({
					  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					  deviceId:this.deviceId,
					  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					  serviceId:this.serviceId,
					  success:(res)=>{
						console.log(res,'特征getBLEDeviceCharacteristics')
						this.characteristics = res.characteristics
						console.log(this.characteristics)
						res.characteristics.forEach((item)=>{
								this.characteristicId = item.uuid
								//console.log('characteristicId:', item.uuid)
								//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
						})
					  },
					  fail:(res)=>{
						console.log(res)
					  }
					})
				},1000)
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices(){
				setTimeout(()=>{
					uni.getBLEDeviceServices({
					  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					  deviceId:this.deviceId,
					  success:(res)=>{
						console.log('device services:', res)
						//res.services.forEach((item)=>{
							//if(item.uuid.indexOf("00001803")!=-1){
								this.serviceId = res.services[3].uuid;
						//		console.log(this.serviceId)
								//获取特征
								this.getBLEDeviceCharacteristics()
					//		}
					//	})
					  }
					})
				},1000)
			},
		}
	}
</script>

<style scoped lang="scss">
	.wrapper{
		padding: 50rpx;
		.footer{
			display: flex;
		}
		.list{
			margin:30rpx 0;
			.item{
				display: flex;
				border: 1px solid #F5F5F5;
				box-sizing: border-box;
				padding:10px 10px; 
				justify-content: space-between;
				align-items: center;
				.button{
					margin:0;
				}
			}
		}
	}
</style>
