<template>
	<view>
		<uni-nav-bar id="nav-bar" status-bar="true" @clickLeft="onBack()" @clickRight="onNavUpdateDevice()"
			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>
			<view slot="right">
				<view class=" flex align-center " style="margin-right: 10rpx;">
					<image style="width: 60rpx;height: 50rpx;" src="../../../static/devicesIconSimple/upgrade.png">
					</image>
				</view>
			</view>
		</uni-nav-bar>
		<view class="card-view padding-top padding-bottom" v-for="(item,index) in devicesList" :key="index"
			:id="'task_'+index" :class="item.bRatio?'hardware-border':''" :style="{'z-index': threeZIndex}">
			<view class="flex justify-between align-center">
				<view class="flex justify-start align-center">
					<image style="margin-left: 20rpx; width: 200rpx;height: 120rpx;" :src="item.icon" mode="aspectFit">
					</image>
					<view style="width: 350rpx;margin-left: 10rpx;">
						<view style="margin: 20rpx 0rpx; font-weight: bold; font-size: 18px; color: #565656;">
							{{item.cname}}
						</view>
						<view style="font-size: 12px; white-space:pre-wrap;" class="make-text-bPurple">{{item.describe}}{{item.bOldDevice?'(旧手柄)':''}}
						</view>
					</view>

				</view>
				<image style="margin-right: 60rpx; width: 60rpx;height: 60rpx;"
					:src="item.bRatio?'/static/devicesOther/radio-b.png':'/static/devicesOther/radio-g.png'"
					mode="aspectFit" @tap="_onRadio(item,$event)"></image>
			</view>
		</view>



		<view v-if="currentIndex<5" class="position-absolute-center" style="z-index: 1; width: 750rpx;display: flex;">
			<swiper class="swiper" :style="{height:currentHeight+'px'}" :circular="circular" :vertical="true"
				disable-touch="true" :current="currentIndex" @click="onSwiperClick" @change="onSwiperChange">
				<!-- 1 @touchmove.stop='stopTouchMove' -->
				<swiper-item class="flex justify-center align-center" @click="onSwiperItemClick">
					<view style="width: 590rpx; height: 626rpx; margin-top: 50rpx;" class="position-relative">
						<view class="bluetooth-guide-number" style="position: absolute;left: 94rpx;top: 8rpx;">1</view>
						<!-- <image style="width: 590rpx; height: 626rpx;"
							src="../../../static/guide/blutooth/guide-ble-1@2x.png">
						</image> -->
						<view style="width: 590rpx; height: 512rpx;" class="flex position-relative">
							<image style="width: 424rpx;height: 412rpx; margin-top: 100rpx;"
								src="../../../static/guide/blutooth/guide-ble-tip.png"></image>
							<image style="width: 102rpx;height: 102rpx; margin-top: 116rpx; margin-left: 56rpx;"
								src="../../../static/guide/blutooth/guide-ble-toggle.png"></image>
							<view class="position-absolute-right-top">
								<image style="width: 406rpx;height: 94rpx; "
									src="../../../static/guide/blutooth/guide-toggle-tip.png"></image>
								<view class="position-absolute-center text-regular"
									style="width: 438rpx;height: 96rpx;top: 26rpx;left: 40rpx;">
									确保手机蓝牙处于开启状态</view>
							</view>
						</view>
						<view class="position-relative" style="top: 10rpx;">
							<image style="width: 520rpx; height:166rpx;top: 10rpx;left: 26rpx;"
								src="../../../static/guide/blutooth/boxMid@2x.png">
							</image>
							<view class="position-absolute-center text-regular"
								style="width: 438rpx;height: 96rpx;top: 18rpx;">
								切记请不要直接连接蓝牙,确保手柄没被任何手机连接,如果有请断开连接。</view>
						</view>
					</view>

				</swiper-item>
				<!-- 2 -->
				<swiper-item class="flex justify-center align-center flex-direction">

					<image style="width: 354rpx; height: 306rpx; margin-bottom: 28rpx;"
						src="../../../static/guide/blutooth/guide-ble-device.png">
					</image>
					<view class="position-relative">
						<image style="width: 520rpx; height:166rpx;" src="../../../static/guide/blutooth/boxMid@2x.png">
						</image>
						<view class="position-absolute-center text-regular"
							style="width: 438rpx;height: 96rpx;top: 26rpx;">长按游戏设备开关3秒，设备灯连续闪烁为可连接状态</view>
					</view>
					<view class="bluetooth-guide-number" style="margin-top: 36rpx;">2</view>
				</swiper-item>
				<!-- 3 -->
				<swiper-item class="flex justify-start align-center flex-direction">

					<view :style="{height:threeTipHeight+'px'}"></view>
					<view class="flex justify-end">
						<view class="bluetooth-guide-number" style="margin-top: 32rpx;">3</view>
						<view class="position-relative">
							<image style="width: 462rpx; height:206rpx;"
								src="../../../static/guide/blutooth/boxRight@2x.png">
							</image>
							<view class="position-absolute-center text-regular"
								style="width: 392rpx;height: 144rpx;top: 44rpx;">选择设备类型连接，按钮勾选上表示手柄连接成功。如果连接失败请重试</view>
						</view>
					</view>

				</swiper-item>
				<!-- 4 -->
				<swiper-item class="flex justify-center align-center flex-direction">

					<image style="width: 446rpx; height: 384rpx; margin-bottom: 28rpx; margin-top: 100rpx;"
						src="../../../static/guide/blutooth/guide-ble-bind.png">
					</image>
					<view class="position-relative">
						<image style="width: 520rpx; height:166rpx;" src="../../../static/guide/blutooth/boxMid@2x.png">
						</image>
						<view class="position-absolute-center text-regular"
							style="width: 438rpx;height: 96rpx;top: 26rpx;">请将手柄十字键朝上插入绑带中，用绑带将手柄朝上绑在右脚脚踝上</view>
					</view>
					<view class="bluetooth-guide-number" style="margin-top: 36rpx;">4</view>
				</swiper-item>
				<!-- 5 -->
				<swiper-item class="flex justify-start align-center flex-direction">

					<view :style="{height:threeTipHeight+'px'}"></view>
					<view class="position-relative">
						<image style="width: 520rpx; height:162rpx;" src="../../../static/guide/blutooth/boxMid@2x.png">
						</image>
						<view class="position-absolute-center flex align-center justify-center"
							style="width: 438rpx;top: 32rpx;">
							<image style="width: 60rpx;height:60rpx;margin-right: 28rpx;"
								src="../../../static/guide/blutooth/guide-ble-finish@2x.png"></image>
							<view class=" text-regular " style="width: 336rpx;height: 90rpx;">
								连接手柄成功后，返回主界面选择关卡开始游戏吧</view>
						</view>

					</view>
				</swiper-item>

			</swiper>
		</view>

	</view>


</template>

<script>
	import config from '@/common/config.js';
	import reqUtil from '@/util/util-js/requstUtil.js';
	import ble from '@/util/util-js/BLE.js';

	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		computed: mapState(['bOpenBluetooth', 'bOpenSuccess', 'bListenAdapterStateChange', 'bListenDeviceFound',
			'BLEConnectDevice', 'BLEGetServices', 'cIndex', 'bConnection', 'bVerifiedConnection', 'BLEInfoList',
			'BLEDeviceShowList', 'finallyUseDevice', 'systemInfo', 'guideUnlockState'
		]),
		data() {
			return {
				// 设备列表
				devicesList: [],
				currentItem: null,
				//设置一个旧的连接item
				oldItem: null,
				searchObj: null,
				//设置搜索超时时间
				searchTimeOut: null,
				option: null,
				saveObj: null,
				//搜索提示定时器
				searchMac: null,
				//
				getServicesTimeout: null,
				writeMacTimeout: null,
				//限制关闭连接
				bLimitClose: false,

				//是否需要检测发起的连接蓝牙是否匹配上
				bTestBondConnect: true,
				//是否显示
				bShow: true,
				//切换连接
				bSwitch: false,

				//提示
				circular: false,
				currentHeight: 0,
				threeTipHeight: 0,
				threeZIndex: 0,
				currentIndex: 5,
			}
		},
		onLoad(op) {
			// if (op.deviceType) {
			// 	console.log(op);
			// 	this.option = op;
			// }
			//目前是固定这个值，去掉了一级页面
			// this.option = {
			// 	cname: "手柄盒子",
			// 	deviceType: 'BLEHandle'
			// };
			// if (this.option.deviceType == 'BLEHandle') {
			// 	this.BLEInfoList.forEach((item, index, selfarr) => {
			// 		if (item.deviceType == 'BLEHandle' || item.deviceType == 'BLERope') {
			// 			let item = Object.assign({}, selfarr[index]);
			// 			this.devicesList.push(item);
			// 		}
			// 	})
			// }
			this.BLEInfoList.forEach((item, index, selfarr) => {
				//item.deviceType == 'BLEHandle' || 
				if (item.deviceType == 'BLERope') {
					let item = Object.assign({}, selfarr[index],{bOldDevice:false});
					this.devicesList.push(item);
				}
			})
			uni.$on('retryConnectBLESuccess', this.onRetryConnectBLESuccess);
			uni.$on('callbackCloseBLE', this.hardCallbackCloseBLE);
			uni.$on('listenerBLE', this.onListenerBLE);


			this.currentHeight = this.systemInfo.windowHeight;

			if (this.guideUnlockState.firstDisconnectBluetooth) {

				this.currentIndex = 0;
				let guideUnlockState = Object.assign(this.guideUnlockState, {
					firstDisconnectBluetooth: false
				});
				this.setGuideUnlockState(guideUnlockState);
			}
		},
		onUnload() {
			uni.$off('retryConnectBLESuccess', this.onRetryConnectBLESuccess);
			uni.$off('callbackCloseBLE', this.hardCallbackCloseBLE);
			uni.$off('listenerBLE', this.onListenerBLE);

			//清除定时器
			this.onClearTimeout();
		},
		onShow() {
			this.bShow = true;
			this.bLimitClose = false;
			// console.log(this.cIndex, this.BLEDeviceShowList, this.BLEConnectDevice, this.devicesList);
			//this.bConnection &&
			if (this.bVerifiedConnection && this.BLEConnectDevice) {
				for (let i = 0; i < this.devicesList.length; i++) {
					let eq = this.devicesList[i];
					if (
						(eq.ename.indexOf("mobilePhoneBandage") > -1 && this.BLEConnectDevice.id == 0) ||
						(eq.ename.indexOf("hotman") > -1 && this.BLEConnectDevice.id == 1) ||
						(eq.ename.indexOf("BLEHandle") > -1 && this.BLEConnectDevice.id == 2) ||
						(eq.ename.indexOf("rope") > -1 && this.BLEConnectDevice.id == 3)) {
						eq.bRatio = true;
						this.currentItem = eq;

						// setTimeout(() => {
						// 	this.onCheckBondDevice();
						// }, 5000)


					}
				}
			} else {
				//如果没连接的话，设置一下显示状态
				for (let i = 0; i < this.devicesList.length; i++) {
					let eq = this.devicesList[i];
					eq.bRatio = false;
				}
				// this.currentItem = null;
			}


		},
		onReady() {
			let view = uni.createSelectorQuery().select('#task_0');
			view.boundingClientRect(data => {
				// console.log('参数:' + JSON.stringify(data));
				//13 是间隔
				this.threeTipHeight = data.top + data.height + 13;
			}).exec();
		},
		onHide() {
			//如果蓝牙弹出匹配框，会触发onHide。这时候处理蓝牙连接流程检测应等onShow 时候，再检测
			this.bShow = false;
		},
		methods: {
			...mapMutations(['initAdapter', 'onCreateBLESuccess', 'onGetBLEDeviceServices', 'onOnlyCloseBLEConnection',
				'onGetRSSITransDistance',
				'addBLEDevice', 'onWriteBLEConnectionValue', 'deleteBLEDevice', 'B_GetBondedDevices',
				'B_OpenBLESetting', 'setGuideUnlockState'
			]),
			//
			onClearTimeout() {
				// 退出后，清除计时器
				if (this.searchMac) {
					clearTimeout(this.searchMac);
					this.searchMac = null;
				}
				//servicesTimeout
				if (this.getServicesTimeout) {
					clearTimeout(this.getServicesTimeout);
					this.getServicesTimeout = null;
				}
				//写入指令writeMacTimeout
				if (this.writeMacTimeout) {
					clearTimeout(this.writeMacTimeout);
					this.writeMacTimeout = null;
				}

				if (this.searchTimeOut) {
					clearTimeout(this.searchTimeOut);
					this.searchTimeOut = null;
				}
			},
			//监听回调
			onListenerBLE(res) {
				console.log('onListenerBLE:', res, this.saveObj);
				if (res.type !== 'mac') return;
				//如果mac 回调了不用提示
				if (this.searchMac) {
					clearTimeout(this.searchMac);
					this.searchMac = null;
				}
				let _self = this;
				let mac = res.value;
				// console.log('mac =====', mac);
				//用返回的mac 判断，如果非法，则断开连接
				//就判断一下是否
				//测试
				// mac="BB:34:24:22:77:88";
				// mac="è¾ƒè¾";
				//判断mac地址是否是合理的格式
				var tempMacRegExp =
					/[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
				if (!tempMacRegExp.test(mac)) {
					uni.hideToast();
					uni.showModal({
						title: '验证信息',
						content: '获取Mac地址失败，请重新连接。'
					})
					//关闭当前连接
					_self.onOnlyCloseBLEConnection({
						getSuccess: () => {
							_self.currentItem = null;
							_self.saveObj = null;
						}
					});
					return;
				}

				reqUtil.requestData(config.URL.BLEFINDHASBIND, {
					mac: mac,
				}).then(
					res => {
						console.log('BLEFINDHASBIND:' + mac + " = " + JSON.stringify(res));
						if (res.code == 0) {
							//code = 0 是新的地址，没绑定过
							//绑定设备使用者
							reqUtil.requestData(config.URL.BLEBIND, {
								mac: mac,
							}).then(
								res => {
									// console.log('BLEBIND:', res);
									if (res.code == 0) {
										//绑定成功，添加设备
										if (_self.saveObj == null) return;
										
										//添加一个mac地址到saveObj
										console.log('添加了mac前saveObj',_self.saveObj);
										_self.saveObj = Object.assign({}, _self.saveObj, {
											deviceMac: mac,
											bOldDevice: res.data!=null?res.data.bOldDevice:false
										});
										console.log('添加了mac后saveObj：',_self.saveObj);
										_self.addBLEDevice(_self.saveObj);
										_self.ConnectionSuccess();
									}
								},
								e => {
									console.log(e);
									//绑定失败, 关闭当前连接
									_self.onOnlyCloseBLEConnection({
										getSuccess: () => {
											_self.currentItem.bRatio = false;
											_self.currentItem = null;
											_self.saveObj = null;
										}
									});
								}
							);

						} else if (res.code == 721) {
							// console.log("~~:",_self.saveObj);
							//是自己绑定的,添加设备
							if (_self.saveObj == null) return;
							//添加一个mac地址到saveObj
							console.log('code=721,添加了mac前saveObj',_self.saveObj);
							_self.saveObj = Object.assign({}, _self.saveObj, {
								deviceMac: mac,
								bOldDevice: res.data!=null?res.data.bOldDevice:false
							});
							console.log('code=721,添加了mac后saveObj：',_self.saveObj);
							_self.addBLEDevice(_self.saveObj);
							_self.ConnectionSuccess();


						} else if (res.code == 711 || res.code == 722) {
							//res.code = 711  蓝牙设备不是我们自己的
							//res.code = 722  蓝牙设备别人使用过
							uni.hideToast();
							uni.showModal({
								title: '连接失败',
								content: '当前手柄已经被其它账号绑定。'
							})
							//关闭当前连接
							_self.onOnlyCloseBLEConnection({
								getSuccess: () => {
									_self.currentItem = null;
									_self.saveObj = null;
								}
							});
						}
					},
					e => {
						console.log(e);
					}
				);
			},
			/**
			 * 连接设备成功
			 */
			ConnectionSuccess() {
				for (let i = 0; i < this.devicesList.length; i++) {
					let eq = this.devicesList[i];
					if (
						(eq.ename.indexOf("mobilePhoneBandage") > -1 && this.BLEConnectDevice.id == 0) ||
						(eq.ename.indexOf("hotman") > -1 && this.BLEConnectDevice.id == 1) ||
						(eq.ename.indexOf("BLEHandle") > -1 && this.BLEConnectDevice.id == 2) ||
						(eq.ename.indexOf("rope") > -1 && this.BLEConnectDevice.id == 3)) {

						eq.bRatio = true;
						this.currentItem = eq;
						/**
						 * 已验证的连接设置true
						 */
						this.$store.state.bVerifiedConnection = true;
						/**
						 * 根据名字兼容旧设备
						 */
						let _tempMac = this.saveObj.deviceMac.replace(/:/g,"");
						let _fourStr = _tempMac.substring(_tempMac.length - 4,_tempMac.length);
						console.log("格式化去掉冒号后mac：",_tempMac,"==",_fourStr);
						let _tempInt = ble.hex2int(_fourStr);
						console.log("格式化去掉冒号后_tempInt：",_tempInt);
						//这里判断旧设备，因为目前这批新设备，用的也是202012的名字，所以这里处理兼容旧设备就行了
						//用mac判断区分，一起有100个是旧设备，还有部分非标准的mac，根据后台字段判断
						//如果后台存在bOldDevice 字段，则根据字段判断是否是旧设备
						if (this.saveObj.name === "BGBox_202012" 
						&& _tempInt<=101 && _tempInt >=0 || this.saveObj.bOldDevice) {
							this.$store.state.bOldDeviceType = true;
							eq.bOldDevice = true;
							console.log("旧设备:", this.$store.state.bOldDeviceType);
						}else{
							console.log("旧设备",this.$store.state.bOldDeviceType);
							eq.bOldDevice = false;
						}

						uni.hideToast();
					}
				}
			},
			onCheckBondDevice() {
				console.log("onCheckBondDevice", this.bTestBondConnect);
				if (this.bTestBondConnect && this.bShow) {
					/**
					 * 假如手机没有匹配，断开连接
					 */
					console.log(2, this.finallyUseDevice);
					this.B_GetBondedDevices({
						deviceId: this.finallyUseDevice.deviceId,
						success: (bondedDevice) => {
							uni.hideToast();
							if (bondedDevice == null) {
								// if (plus.os.name == 'Android') 
								{
									//此问题 华为手机容易出现
									//android手机已配对的设备 不存在，但是app 又直接连接成功了。提示，并且断开app连接
									//1.关闭当前连接
									this.onOnlyCloseBLEConnection({
										getSuccess: () => {
											this.currentItem.bRatio = false;
											this.currentItem = null;
											this.saveObj = null;
										}
									});
									//2.跳转蓝牙设置
									uni.showModal({
										title: '蓝牙配对失败',
										content: '请跳转后点击配对BGBox_2020,成功后手动跳转回哔蹦重新连接。',
										success: (res) => {
											if (res.confirm) {
												this.B_OpenBLESetting();
											}
										}
									})
								}

							}
						}
					});
					this.bTestBondConnect = false;
				} else {
					uni.hideToast();
				}
			},
			onRetryConnectBLESuccess() {
				this.ConnectionSuccess();
			},
			hardCallbackCloseBLE() {

				if (this.BLEConnectDevice == null && this.currentItem && !this.bSwitch) {
					this.currentItem.bRatio = false;
					this.currentItem = null;
					this.saveObj = null;
				}
				//如果限制不走重连
				if (this.bLimitClose) return;

				console.log(this.currentItem, this.oldItem);
				if (this.oldItem && this.currentItem && this.currentItem.id == this.oldItem.id) {
					// this.$store.state.bConnection = false;
					if (this.currentItem.bRatio) {
						uni.showToast({
							title: '设备断开连接！',
							icon: 'none',
							duration: 2000,
							mask: true
						})
						this.currentItem.bRatio = false;
						this.oldItem = null;
						this.currentItem = null;
						//断开连接
						this.$store.state.bVerifiedConnection = false;
					}
				} else if (this.bConnection && this.BLEConnectDevice) {
					//假如匹配过程中断开连接
					this.$store.state.BLEConnectDevice = null;
					this.$store.state.bConnection = false;
					// uni.hideToast();
					// console.log("//假如匹配过程中断开连接");
					uni.showToast({
						title: '连接失败,尝试重新连接。',
						icon: 'none',
						mask: true,
						duration: 2000
					})
					if (this.getServicesTimeout) {
						clearTimeout(this.getServicesTimeout);
						this.getServicesTimeout = null;
					}
				}

			},
			/**
			 * 开始查找设备
			 * */
			startBluetoothDeviceDiscovery() {
				//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功，则开始查找设备
				let _self = this;
				if (_self.bOpenBluetooth) {
					//1.第一步还是先进行设备搜索
					_self.onCanStart();
				} else {
					_self.initAdapter(() => {
						_self.startBluetoothDeviceDiscovery();
					});
				}
			},
			/**
			 * 通过检测手机连接的设备进行连接，null 的话进行搜索操作
			 */
			onBondedDeviceConnect(data) {
				let _self = this;
				//获取手机本身已连接的硬件，
				//示例
				// {
				// 	"deviceId": "C5:5C:19:04:00:30",
				// 	"name": "BGBox_202012",
				// 	"RSSI": -74,
				// 	"localName": "BGBox_20201",
				// 	"advertisServiceUUIDs": ["00001812-0000-1000-8000-00805F9B34FB", "0000FFF0-0000-1000-8000-00805F9B34FB"]
				// }

				console.log("onBoded ***************:", _self.finallyUseDevice);

				_self.B_GetBondedDevices({
					deviceId: _self.finallyUseDevice == null ? null : _self.finallyUseDevice.deviceId,
					success: (bondedDevice) => {
						console.log("bondedDevice:", bondedDevice);
						//获取已和蓝牙连接的设备
						if (bondedDevice != null) {
							//如果用户匹配了对应的设备，直接用对应的设备来连接
							let setDevice = {
								"deviceId": bondedDevice.address,
								"name": bondedDevice.name,
								"RSSI": -74,
								"localName": "",
								"advertisServiceUUIDs": ["00001812-0000-1000-8000-00805F9B34FB",
									"0000FFF0-0000-1000-8000-00805F9B34FB"
								]
							}

							let obj = Object.assign({}, setDevice, _self.currentItem);
							//finallyUserDevice 就是最后一次使用搜索到的设备信息
							_self.saveObj = Object.assign({}, setDevice, {
								id: _self.currentItem.id
							});
							uni.showToast({
								title: '设备连接中...',
								icon: 'loading',
								duration: 10000,
								mask: true
							})
							console.log("GetBondedDevices:::===", setDevice, _self.currentItem, obj);
							// 先直连，然后判断版本
							_self._onConnectDevice(obj);

							//getBond后发起的连接，不需要检测了
							_self.bTestBondConnect = false;
						} else {
							console.log("没有获取到绑定的设备");
							uni.showToast({
								title: '获取匹配设备失败',
								icon: 'none',
								mask: true
							})
						}
					}
				});
			},
			//开始搜索
			onCanStart() {
				let _self = this;
				uni.showToast({
					title: '设备连接中...',
					icon: 'loading',
					duration: 15000,
					mask: true
				})
				// 1.已经搜索到的，根据蓝牙回调的mac 地址判断合法性。
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: res => {
						// console.log("startBluetoothDevicesDiscovery:", res);

						_self.bSwitch = false;
						_self.onBluetoothDeviceFound();
					},
					fail: res => {
						console.log("搜索失败！");
						_self.initAdapter(() => {
							_self.startBluetoothDeviceDiscovery();
						});
					}
				});
				// 2.没有搜索到的，一段时间后处理。比如手机已经连接了设备，但是app 里面搜索不到，也没记录使用过的。
				if (_self.searchTimeOut) {
					clearTimeout(_self.searchTimeOut);
					_self.searchTimeOut = null;
				}
				//搜索一段时间后，停止搜索
				if (plus.os.name == 'iOS') {
					_self.searchTimeOut = setTimeout(() => {
						_self.stopBluetoothDevicesDiscovery();
						//搜索失败后,再检查是否和手机配对的设备连接
						_self.onBondedDeviceConnect();
					}, 4000)
				} else {
					_self.searchTimeOut = setTimeout(() => {
						_self.stopBluetoothDevicesDiscovery();
					}, 8000)
				}
				
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						// console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				let _self = this;
				_self.searchObj = null;
				uni.onBluetoothDeviceFound(res => {
					/**
					 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
					 */
					// console.log("onBluetoothDeviceFound:", res);
					res.devices.forEach(device => {
						if (device.name.indexOf('PBox') > -1 || device.name.indexOf('BGBox') > -1 || device
							.name.indexOf('Rope') > -1) {
							//如果搜索的设备名 不是对应当前设备类型，过滤
							// if (device.name.indexOf(_self.currentItem.deviceName) == -1) return;
							if (_self.currentItem.deviceName.indexOf('PBox') == -1 &&
								_self.currentItem.deviceName.indexOf('BGBox') == -1 &&
								_self.currentItem.deviceName.indexOf('Rope') == -1
							) return;
							//寻找到对应设备时候，其余的返回
							if (_self.searchObj) return;
							_self.searchObj = device;
							if (_self.searchTimeOut) {
								clearTimeout(_self.searchTimeOut);
								_self.searchTimeOut = null;
							}
							//currentItem 是mode 页面选中的item
							let obj = Object.assign({}, device, _self.currentItem);

							_self.saveObj = Object.assign({}, {
								id: _self.currentItem.id
							}, device);

							// console.log(device, "****", obj, _self.saveObj, _self.currentItem)
							// 先直连，然后判断版本
							_self._onConnectDevice(obj);
							_self.stopBluetoothDevicesDiscovery();
						}
					})

				})
			},

			onBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			// 提示点击连接设备
			_onConnectDevice(item) {
				//servicesTimeout
				if (this.getServicesTimeout) {
					clearTimeout(this.getServicesTimeout);
					this.getServicesTimeout = null;
				}
				//写入指令writeMacTimeout
				if (this.writeMacTimeout) {
					clearTimeout(this.writeMacTimeout);
					this.writeMacTimeout = null;
				}
				//如果已经连接，加上服务不存在，直接获取服务
				if (this.bConnection && this.BLEGetServices && this.BLEGetServices.length == 0) {
					console.log("***直接获取服务*******");
					this.onGetBLEDeviceServices({
						item: item,
						success: (res) => {
							console.log("*****getBLEDeviceServices************");
							//连接成功了,设置旧的item
							this.oldItem = this.currentItem;
							uni.showToast({
								title: '正在验证设备信息...',
								icon: 'loading',
								duration: 10000,
								mask: true
							})
							// 初始化服务后，获取版本，判断
							// 停止蓝牙加速计
							this.writeMacTimeout = setTimeout(() => {
								//todo 停止蓝牙加速计
								// this.onWriteBLEConnectionValue({
								// 	value: "4"
								// });
								// 发送获取mac
								this.onWriteBLEConnectionValue({
									value: "M"
								});
								if (this.searchMac) {
									clearTimeout(this.searchMac);
									this.searchMac = null;
								}
								this.searchMac = setTimeout(() => {
									uni.hideToast();
									uni.showModal({
										title: '提示',
										content: '检测设备失败。\r\n1.再次尝试连接。\r\n2.或者重启手柄(Reset键位也可)后再尝试连接'
									})
									this.onOnlyCloseBLEConnection({
										getSuccess: () => {
											if (this.currentItem)
												this.currentItem.bRatio = false;

											this.currentItem = null;
										}
									});
								}, 6000)
							}, 3000)

						}
					});
					return;
				}
				//创建一个连接，需要对应close
				this.onCreateBLESuccess({
					item: item,
					getSuccess: () => {
						// console.log("****创建一个连接*******");
						this.getServicesTimeout = setTimeout(() => {
							this.onGetBLEDeviceServices({
								item: item,
								success: (res) => {
									// console.log("******getBLEDeviceServices************", res);
									//连接成功了,设置旧的item
									this.oldItem = this.currentItem;
									uni.showToast({
										title: '正在验证设备信息...',
										icon: 'loading',
										duration: 10000,
										mask: true
									})
									// 初始化服务后，获取版本，判断
									// 停止蓝牙加速计
									this.writeMacTimeout = setTimeout(() => {
										//todo 停止蓝牙加速计
										// this.onWriteBLEConnectionValue({
										// 	value: "4"
										// });
										// 发送获取mac
										this.onWriteBLEConnectionValue({
											value: "M"
										});
										if (this.searchMac) {
											clearTimeout(this.searchMac);
											this.searchMac = null;
										}
										this.searchMac = setTimeout(() => {
											uni.hideToast();
											uni.showModal({
												title: '提示',
												content: '检测设备失败。\r\n1.再次尝试连接。\r\n2.或者重启手柄(Reset键位也可)后再尝试连接'
											})
											this.onOnlyCloseBLEConnection({
												getSuccess: () => {
													if (this
														.currentItem
													)
														this
														.currentItem
														.bRatio =
														false;

													this.currentItem =
														null;
												}
											});
										}, 6000)
									}, 3000)

								}
							});
						}, 2500);
					}
				})
			},

			_onRadio(item, event) {

				if (!item.bRatio) {
					//设置默认值
					this.bTestBondConnect = true;
					if (this.BLEConnectDevice) {
						this.onOnlyCloseBLEConnection({
							getSuccess: () => {
								if (this.currentItem)
									this.currentItem.bRatio = false;

								this.currentItem = null;
								this.currentItem = item;
								this.bSwitch = true;
								console.log("this.currentItem1 ==:", this.currentItem, this.bOpenBluetooth,
									this.BLEConnectDevice);
								this.startBluetoothDeviceDiscovery();
							}
						});
						return;
					}
					this.currentItem = null;
					this.currentItem = item;
					// console.log("this.currentItem ==2:", this.currentItem, this.bOpenBluetooth, this.BLEConnectDevice);
					this.startBluetoothDeviceDiscovery();
				}
			},
			//跳转进入升级页面,
			onNavUpdateDevice() {
				// console.log('onNavUpdateDevice');
				// if (!this.option) {
				// 	uni.showToast({
				// 		title: 'option null',
				// 		icon: 'none'
				// 	})
				// 	return;
				// }
				//需要连接设备后，才能进入升级
				if (!this.currentItem || !this.currentItem.bRatio || !this.BLEConnectDevice) {
					uni.showToast({
						title: '请先连接硬件!',
						icon: 'none'
					})
					return;
				}

				// if (this.BLEConnectDevice.deviceType != this.option.deviceType) {
				// 	uni.showToast({
				// 		title: '设备类型不对',
				// 		icon: 'none'
				// 	})
				// 	return;
				// }

				this.bLimitClose = true;
				uni.navigateTo({
					// url: "../devices-update/devices-update?deviceType=" + this.option.deviceType
					url: "../devices-update/devices-update"
				})
			},
			onGetDevice() {
				uni.getBluetoothDevices({
					success(res) {
						console.log("getBluetoothDevices:", res)
					}
				})

				uni.getConnectedBluetoothDevices({
					success(res) {
						console.log("getConnectedBluetoothDevices:", res)
					}
				})


			},

			onSwiperChange(e) {
				let currentIndex = e.detail.current;
				// console.log(currentIndex);
				if (currentIndex === this._videoIndex) {
					return;
				}

				if (currentIndex === 2) {
					setTimeout(() => {
						this.threeZIndex = 2;
					}, 200)
				} else {
					this.threeZIndex = 0;
				}

				// let isNext = false;
				// if (currentIndex === 0 && this._videoIndex === this.videoList.length - 1) {
				// 	isNext = true;
				// } else if (currentIndex === this.videoList.length - 1 && this._videoIndex === 0) {
				// 	isNext = false;
				// } else if (currentIndex > this._videoIndex) {
				// 	isNext = true;
				// }

				// if (isNext) {
				// 	this._videoDataIndex++;
				// } else {
				// 	this._videoDataIndex--;
				// }

				// if (this._videoDataIndex < 0) {
				// 	this._videoDataIndex = this.videoDataList.length - 1;
				// } else if (this._videoDataIndex >= this.videoDataList.length) {
				// 	this._videoDataIndex = 0;
				// }

				// this.circular = (this._videoDataIndex != 0);

				// if (this._videoIndex >= 0) {
				//     this._videoContextList[this._videoIndex].pause();
				//     this._videoContextList[this._videoIndex].seek(0);
				// }

				// this._videoIndex = currentIndex;


			},
			//禁止用户手动滑动
			stopTouchMove() {
				// return;
			},
			onSwiperClick() {
				console.log('onSwiperClick');

				this.currentIndex++;

				if (this.currentIndex === 2) {
					setTimeout(() => {
						this.threeZIndex = 2;
					}, 200)
				} else {
					this.threeZIndex = 0;
				}


			},
			onSwiperItemClick(e) {
				console.log('onSwiperItemClick');


			}
		}

	}
</script>

<style>
	.hardware-border {
		border: 1rpx solid #9898FF;
		box-sizing: border-box;
	}

	.swiper {
		flex: 1;
		background-color: rgba(0, 0, 0, 0.32);
	}

	.swiper-item {
		flex: 1;
	}

	.bluetooth-guide-number {
		border-radius: 18px;
		border-width: 1rpx;
		width: 30px;
		height: 30px;
		text-align: center;
		line-height: 30px;
		color: #000000;
		/* border-color: #FFFFFF; */
		background-color: #FFFFFF;
		margin-right: 13px;
	}
</style>
