<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" :class="item.bRatio?'hardware-border':''">
			<view class="flex justify-between align-center">
				<view class="flex justify-start align-center">
					<image style="margin-left: 30rpx; width: 200rpx;height: 120rpx;" :src="item.icon" mode="aspectFit"></image>
					<view>
						<view style="margin: 20rpx 50rpx; font-weight: bold; font-size: 18px; color: #565656;">{{item.cname}}</view>
						<view style="margin-left: 50rpx; font-size: 12px;" class="make-text-bPurple">{{item.describe}}</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>
		<!-- <button @click="onGetDevice()"> onGetDevice</button> -->

	</view>


</template>

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

	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		computed: mapState(['bOpenBluetooth', 'bOpenSuccess', 'bListenAdapterStateChange', 'bListenDeviceFound',
			'BLEConnectDevice', 'BLEGetServices', 'cIndex', 'bConnection', 'bVerifiedConnection', 'BLEInfoList',
			'BLEDeviceShowList', 'finallyUseDevice'
		]),
		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,
			}
		},
		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') {
						let item = Object.assign({}, selfarr[index]);
						this.devicesList.push(item);
					}
				})
			}
			uni.$on('callbackCloseBLE', this.hardCallbackCloseBLE);
			uni.$on('listenerBLE', this.onListenerBLE);

		},
		onUnload() {
			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.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;
			}


		},
		onHide() {
			//如果蓝牙弹出匹配框，会触发onHide。这时候处理蓝牙连接流程检测应等onShow 时候，再检测
			this.bShow = false;
		},
		methods: {
			...mapMutations(['initAdapter', 'onCreateBLESuccess', 'onGetBLEDeviceServices', 'onOnlyCloseBLEConnection',
				'onGetRSSITransDistance',
				'addBLEDevice', 'onWriteBLEConnectionValue', 'deleteBLEDevice', 'B_GetBondedDevices', 'B_OpenBLESetting'
			]),
			//
			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);
				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";

				reqUtil.requestData(config.URL.BLEFINDHASBIND, {
					mac: mac,
				}).then(
					res => {
						console.log('BLEFINDHASBIND:', 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;
										_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;
							_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() {
				// console.log(this.cIndex, this.BLEDeviceShowList, this.BLEConnectDevice);
				// uni.showToast({
				// 	icon: "none",
				// 	title: "连接设备成功！",
				// 	duration: 2000
				// })
				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.bRatio = true;
						this.currentItem = eq;
						/**
						 * 已验证的连接设置true
						 */
						this.$store.state.bVerifiedConnection = true;

						setTimeout(() => {
							this.onCheckBondDevice();
						}, 5000)
						
					}
				}
			},
			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();
				}
			},
			hardCallbackCloseBLE() {
				//如果限制不走重连
				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() {
				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.onBluetoothDeviceFound();
					},
					fail: res => {
						console.log("搜索失败！");
						_self.initAdapter(() => {
							_self.startBluetoothDeviceDiscovery();
						});
					}
				});
				// 2.没有搜索到的，一段时间后处理。比如手机已经连接了设备，但是app 里面搜索不到，也没记录使用过的。
				if (_self.searchTimeOut) {
					clearTimeout(_self.searchTimeOut);
					_self.searchTimeOut = null;
				}
				_self.searchTimeOut = setTimeout(() => {
					//1.搜索12秒钟之后，停止搜索
					_self.stopBluetoothDevicesDiscovery();
					//搜索失败后,再检查是否和手机配对的设备连接
					_self.onBondedDeviceConnect();
					
				}, 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) {
							//如果搜索的设备名 不是对应当前设备类型，过滤
							// if (device.name.indexOf(_self.currentItem.deviceName) == -1) return;
							if (_self.currentItem.deviceName.indexOf('PBox') == -1 && _self.currentItem.deviceName.indexOf('BGBox') == -
								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(() => {
								//停止蓝牙加速计
								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(() => {
										//停止蓝牙加速计
										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;
					console.log("this.currentItem ==:", this.currentItem, this.bOpenBluetooth, this.BLEConnectDevice);
					if (this.BLEConnectDevice) {
						this.onOnlyCloseBLEConnection({
							getSuccess: () => {
								if (this.currentItem)
									this.currentItem.bRatio = false;

								this.currentItem = null;
								this.currentItem = item;
								this.startBluetoothDeviceDiscovery();
							}
						});
						return;
					}
					this.currentItem = null;
					this.currentItem = item;
					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
				})
			},
			onGetDevice(){
				uni.getBluetoothDevices({
					success(res) {
						console.log("getBluetoothDevices:", res)
					}
				})
				
				uni.getConnectedBluetoothDevices({
					success(res) {
						console.log("getConnectedBluetoothDevices:", res)
					}
				})
				
				
			}
		}

	}
</script>

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