<!-- 蓝牙平台限制 todo https://uniapp.dcloud.io/api/system/bluetooth?id=stopbluetoothdevicesdiscovery -->
<template>
	<view>
		<uni-nav-bar id="nav-bar" status-bar="true" @clickLeft="onBack()" title="选中设备型号" color="#000000" fixed="true" :border="false">
			<view slot="left">
				<view class=" flex align-center margin-left">
					<image class="p-left-arrow" src="../../../static/p-left-arrow.png"></image>
				</view>
			</view>

		</uni-nav-bar>
		<view v-if="devicesList.length==0" class="text-xs text-center text-gray margin-top">
			<text>下拉搜索设备 {{devicesList.length}}</text>
		</view>
		<view v-else class="card-view padding-top padding-bottom">
			<view class="cu-list menu margin-left margin-right">
				<view class="cu-item" :class="true?'arrow':''" v-for="(item,index) in devicesList" :key="index">
					<view class="content" @tap="_onConnectDevice(item,$event)">
						<image :src="item.icon" mode="aspectFit"></image>
						<text class="text-grey">{{item.cname}}</text>
					</view>
				</view>
			</view>


		</view>

	</view>


</template>

<script>
	import BLE from '@/util/util-js/BLE.js'
	import {
		mapState
	} from 'vuex';

	export default {
		computed: mapState(['bOpenBluetooth', 'bOpenSuccess', 'bListenAdapterStateChange', 'bListenDeviceFound']),
		data() {
			return {
				// 设备列表
				devicesList: []
			}
		},
		onLoad() {
			this.Init();
			// #ifdef APP-PLUS
			this.searchDevice();
			// #endif

		},
		onShow() {
			uni.$on('updateGetDevices', this.onGetDevices);
		},
		onHide() {
			uni.$off('updateGetDevices', this.onGetDevices);
		},
		methods: {
			Init() {
				//假如没有初始化蓝牙，就来后再初始化
				if (!this.bOpenBluetooth) {
					/**
					 * 蓝牙部分操作
					 * */
					//初始化蓝牙模块
					BLE.openBluetoothAdapter({
						success: (res) => {
							this.$store.state.bOpenSuccess = true;
							this.$store.state.bOpenBluetooth = true;
						},
						fail: (fail) => {
							//fail 返回
							//给蒙层提示,提示用户打开蓝牙，显示引导层
							// this.$store.state.bGuidePages = true;
							// this.guideCurrent = 2;
							this.$store.state.bOpenSuccess = false;
							this.$store.state.bOpenBluetooth = false;
							uni.showToast({
								title: '蓝牙尚未开启!',
								icon: 'none'
							})
						},
						complete: () => {
							//初始化模块后，开始监听手机蓝牙状态
							if (this.bListenAdapterStateChange) return;

							this.$store.state.bListenAdapterStateChange = true;
							uni.onBluetoothAdapterStateChange((res) => {
								console.log('adapterState changed, now is', res)
								// 手机蓝牙状态
								this.$store.state.bOpenBluetooth = res.available;
								if (this.bOpenBluetooth && !this.bOpenSuccess) {
									this.Init();
								}
							})


						}
					});
					//监听断开事件
					BLE.onBLEConnectionStateChange();
				}
			},
			onBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			/**
			 * 开始查找设备
			 * */
			startBluetoothDeviceDiscovery() {
				//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功，则开始查找设备
				let self = this;
				setTimeout(function() {
					if (self.bOpenBluetooth) {
						uni.startBluetoothDevicesDiscovery({
							//services: ['fff0'],
							success: res => {
								if (!self.bListenDeviceFound) {
									self.$store.state.bListenDeviceFound = true;
									self.onBluetoothDeviceFound();
								}
							},
							fail: res => {
								uni.showToast({
									icon: "none",
									title: "查找设备失败！",
									duration: 3000
								})
							}
						});
					} else {
						uni.showToast({
							icon: "none",
							title: "请打开手机蓝牙！",
							duration: 3000
						})
						console.log("未初始化蓝牙是配饰器：" + self.bOpenBluetooth);
					}
				}, 300);
			},

			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				let _self = this;
				console.log("发现外围设备 onBluetoothDeviceFound:");
				uni.onBluetoothDeviceFound(devices => {
					/**
					 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
					 */
					console.log("onBluetoothDeviceFound:", devices);

					uni.$emit('updateGetDevices', devices);
				});
			},

			onGetDevices() {
				let _self = this;
				uni.getBluetoothDevices({
					success: res => {
						let devicesList = res.devices;
						console.log("搜索的设备对应的信息:", res);
						//中间值
						let _tempList = [];

						//在这里查找对应名称的设备
						for (let i = 0; i < devicesList.length; i++) {
							let eq = devicesList[i];
							//蹦床的设备名字
							if (eq.name.indexOf("BBC") > -1) {
								// eq.cname = "蹦床";
								// eq.ename = "Trampoline";
								// eq.icon = "/static/trampoline1.png";
								// eq.mIcon = "/static/trampoline.png";
								// let E = 2.718281828459045;
								// let _dis = Math.pow(E, (Math.abs(eq.RSSI) - 66.78) / 16.56);
								// console.log('距离:', _dis);
								eq.cname = "绑带蓝牙";
								eq.ename = "BT04";
								eq.icon = "/static/trampoline1.png";
								eq.mIcon = "/static/trampoline.png";

								_tempList.push(eq);
							} else if (eq.name.indexOf("BT04-E") > -1) {
								eq.cname = "绑带蓝牙";
								eq.ename = "BT04";
								eq.icon = "/static/trampoline1.png";
								eq.mIcon = "/static/trampoline.png";

								_tempList.push(eq);
							} else if (eq.name.indexOf("ITAG") > -1) {
								eq.cname = "绑带蓝牙定位";
								eq.ename = "ITAG";
								eq.icon = "/static/trampoline1.png";
								eq.mIcon = "/static/trampoline.png";

								_tempList.push(eq);
							} else {
								eq.cname = eq.name;
								eq.icon = "/static/logo.png";
								eq.mIcon = "/static/logo.png";
							}
						}

						if (_tempList.length != 0) {
							uni.showToast({
								icon: "none",
								title: "查找设备成功！",
								duration: 1000
							})
							_self.devicesList = [];

							for (let i = 0, l = _tempList.length; i < l; i++) {
								_self.devicesList.push(_tempList[i]);
							}
						} else {
							uni.showToast({
								icon: "none",
								title: "未搜索到设备！",
								duration: 1000
							})
						}
						//停止搜索设备
						uni.stopPullDownRefresh();
						_self.stopBluetoothDevicesDiscovery();

					},
					fail: e => {
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
					}
				});
			},

			onPullDownRefresh(e) {
				//假如没有初始化蓝牙，就来后再初始化
				console.warn("************BLE.bOpenBluetooth 初始化蓝牙适配器 == ", this.bOpenBluetooth);
				this.Init();
				this.searchDevice();
			},
			searchDevice() {
				this.startBluetoothDeviceDiscovery();
			},
			// 提示点击连接设备
			_onConnectDevice(item, event) {
				// console.log(item, event);
				if (!this.bOpenBluetooth) {
					uni.showToast({
						title: "蓝牙未初始化",
						icon: "none"
					})
					return;
				}
				uni.showModal({
					title: "连接",
					content: "是否连接对应设备",
					confirmText: '是的',
					success: (res) => {
						if (res.confirm) {
							if (item.deviceId) {
								//连接设备后,
								this.$store.commit('addBLEDevice', item);
								uni.navigateBack({
									delta: 1
								})
							}
						}
					}
				})
			}
		}

	}
</script>

<style>
</style>
