<template>
	<view class="container">
		<view class="tips">请在设备开机状态下，搜索设备</view>
		<view class="item" @click="openBluetoothAdapter">开始搜索设备</view>
		<view class="devices_summary">已发现 {{devices.length}} 个设备：</view>
		<view>
			<scroll-view class="device_list" scroll-y scroll-with-animation v-if="popup">
				<view v-for="(item,index) in devices" :key="index" @tap="createBLEConnection(item)" class="device_item">
					<view>
						<text>{{item.localName ||item.name}}</text>
					</view>
					<view>mac地址:{{item.macAddr || item.deviceId}}</view>
				</view>
			</scroll-view>
		</view>
		<view class="tishi">
			<view class="text">
				<icon class="t-icon t-icon-tishi"></icon> 设备绑定流程说明
			</view>
			<view class="dv">
				<text>1、打开手机蓝牙和位置信息</text>
				<text>2、ios系统需打开设置—>应用—>微信里的蓝牙权限</text>
				<text>3、设备亮屏状态下搜索蓝牙</text>
				<text>4、选择蓝牙进行绑定</text>
			</view>
		</view>
	</view>
</template>

<script>
	let that;
	let myTime;
	import {
		mapState
	} from "vuex";
	export default {
		data() {
			return {
				macAddr: "",
				code: "",
				deviceId: "",
				popup: false,
				devices: [],
				id: 0
			}
		},
		computed: {
			...mapState(["user", "isConnected", "isBluetoothTyle"]),
		},
		onLoad(options) {
			that = this
			that.id = options.id
			that.$Bluetooth.onBLEConnectionStateChange()
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})

		},
		onUnload() {
			console.log("onUnload")
			let that = this
			if (!that.Unload) {
				uni.hideLoading()
				that.$Bluetooth.closeBluetoothAdapter() // 断开蓝牙模块
				that.$Bluetooth.stopBluetoothDevicesDiscovery() // 取消蓝牙搜索
			}
		},
		methods: {
			// 初始化蓝牙
			openBluetoothAdapter() {
				let that = this
				uni.openBluetoothAdapter({
					success: e => {
						console.log("蓝牙初始化成功")
						that.startBluetoothDeviceDiscovery()
					},
					fail: e => {
						console.log('初始化蓝牙失败:' + e.errMsg);
						that.$Bluetooth.getBluetoothAdapter(e)
					}
				});
			},
			// 开始搜寻附近的蓝牙外围设备
			startBluetoothDeviceDiscovery() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true, //是否允许重复上报同一设备
					success: res => {
						that.onBluetoothDeviceFound();
					},
					fail: res => {}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				var that = this;
				const foundDevices = []
				wx.showLoading({
					title: '设备搜索中',
				})
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (device.name.indexOf("YPC") != -1) {
							clearTimeout(myTime);
							let buff = device.name.slice(7, 19)
							device.macAddr = that.$Bluetooth.str2Num(buff)
							device.deviceId = that.$Bluetooth.str2Num(buff)
							that.handleDevice(device)
							return
						}
						if (device.name.indexOf("G02") != -1) {
							clearTimeout(myTime);
							let buff = device.advertisData.slice(3, 9)
							device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
							let tempMac = Array.from(device.mac)
							tempMac.reverse()
							device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
							that.handleDevice(device)
							return
						}
						if (device.name.indexOf("Yihejia_Lung") != -1) {
							console.log("肺活量", device, '04:0D:84:48:E0:9B')
							device.macAddr = device.deviceId
							clearTimeout(myTime);
							that.handleDevice(device)
							return
						}
					})
				});
				that.handleMyTime()
			},
			handleDevice(device) {
				let that = this
				const foundDevices = that.devices
				const idx = that.$tools.inArray(foundDevices, "deviceId", device.deviceId)
				that.deviceId = device.deviceId;
				if (idx === -1) {
					that.devices.push(device);
				} else {
					that.devices[idx] = device
				}
				that.popup = true
			},
			handleMyTime() {
				var that = this;
				myTime = setTimeout(function() {
					if (!that.devices.length) {
						that.islink = -1
						that.$tools.showModal("没有查找到设备")
					}
					uni.hideLoading()
					clearTimeout(myTime);
					that.$Bluetooth.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
				}, 15000);
			},
			// 连接蓝牙
			createBLEConnection(e) {
				let that = this;
				that.$Bluetooth.stopBluetoothDevicesDiscovery()
				that.macAddr = e.macAddr
				uni.showModal({
					title: '提示',
					content: '是否绑定该设备?',
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							that.getActive()
						} else {
							that.$tools.msg("您已取消操作")
						}
					}
				})
			},
			getActive() {
				let that = this
				that.$model.getBinding({
					device_id: that.id,
					device_mac: that.macAddr
				}).then(res => {
					that.$Bluetooth.closeBluetoothAdapter()
					that.devices = []
					if (res.code == 0) {
						that.$tools.msg('绑定成功！')
						that.$store.dispatch('getUserDeviceList')
						that.$store.dispatch('getUserInfo', {
							aud_id: uni.getStorageSync('userid')
						})
						setTimeout(function() {
							uni.switchTab({
								url: "/pages/index/index"
							})
						}, 500)
					} else {
						that.$tools.msg(res.msg)
					}
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.content {
		min-height: calc(100vh - 66px);
		padding: 0;
		border-top: 66px solid #F9FAFC;
		background-color: #fff;
	}

	.tishi {
		width: 100%;
		font-size: 14px;
		line-height: 25px;
		font-weight: bold;
		position: absolute;
		bottom: 20px;
		padding-left: 15px;

		.text {
			display: flex;
			align-items: center;

			icon {
				margin-right: 5px;
			}
		}

		text {
			font-weight: 500;
			font-size: 12px;
			color: #999;
			width: 100%;
			display: block;
		}
	}

	.item {
		width: 70%;
		height: 40px;
		line-height: 38px;
		text-align: center;
		background: #f7f7f7;
		border: 1px solid #dfdfdf;
		font-weight: bold;
		margin: auto;
		border-radius: 15px;
		margin-top: 15px;
	}

	.devices_summary {
		width: 100%;
		height: 40px;
		line-height: 40px;
		text-align: center;
		font-size: 16px;
		color: #666;
	}

	.device_list {
		flex: 1;
		width: 100%;
		height: auto;
		max-height: 340px;
		margin-top: 0;
		margin-bottom: 10px;
		position: absolute;
		bottom: 160px;
		top: 170px;

		.device_item {
			font-size: 14px;
			padding: 7px 10px;
			color: #999;
			border-bottom: 1px solid #dfdfdf;

			text {
				display: inline-block;
				font-size: 14px;
				font-weight: bold;
				color: #666;
				margin-bottom: 5px;
			}
		}
	}

	.tips {
		font-size: 14px;
		text-align: center;
		color: #e83a1e;
		background: #f7e4c8;
		padding: 5px 0;
		margin-top: 15px;
	}
</style>