<template>
	<view class="content" :style="{borderTopColor:appTheme}">
		<view class="tips">请在设备开机状态下，搜索设备</view>
		<view class="item" @click="handleWeight">开始搜索设备</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>
		<userLogin :url="'active'" :code='code'></userLogin>
	</view>
</template>

<script>
	var myTime;
	import {
		mapState
	} from "vuex";
	import userLogin from "@/components/userLogin.vue"
	export default {
		data() {
			return {
				token: "",
				macAddr: "",
				code: "",
				deviceId: "",
				popup: false,
				devices: [],
			}
		},
		components: {
			userLogin
		},
		computed: {
			...mapState(["user", "isBluetoothTyle", "appTheme"])
		},
		async onLoad(options) {
			let that = this
			// 导航栏颜色
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.appTheme,
			})
			// 
			console.log("设备code码", options)
			if (options) {
				that.code = options.code
			}
			that.token = uni.getStorageSync('token')
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
			await that.login()
		},
		methods: {
			login() {
				let that = this
				uni.login({
					success(res) {
						if (res.code) {
							if (res.errMsg = "login:ok") {
								that.$model.onlogin({
									code: res.code,
								}).then(res => {
									if (res.code == 2) {
										uni.clearStorageSync()
										uni.removeStorageSync('token')
										uni.removeStorageSync('changeUser')
										uni.setStorageSync('tenantid', res.data.tenantid)
										uni.setStorageSync('sessionid', res.data.sessionid)
										uni.setStorageSync('iswxphone', res.data.iswxphone)
										that.$store.dispatch("getConfig", {
											tenantId: uni.getStorageSync('tenantid')
										})
									} else {
										uni.setStorageSync('userid', res.data.userid)
										uni.setStorageSync('sessionid', res.data.sessionid)
										uni.setStorageSync('token', res.data.token)
										uni.setStorageSync('iswxphone', res.data.iswxphone)
										uni.setStorageSync('tenantid', res.data.tenantid)
										uni.setStorageSync('refreshtoken', res.data.refreshtoken)
										that.$store.dispatch("getConfig", {
											tenantId: uni.getStorageSync('tenantid')
										})
									}
								}).catch(e => {})
							}
						}
					}
				})
			},
			handleWeight() {
				let that = this
				that.devices = []
				if (!that.token) {
					uni.redirectTo({
						url: '/pageTwo/login/login?url=active' + '&code=' + that.code
					})
					// that.$store.commit("changeUserLogin", true)
					return
				}
				uni.openBluetoothAdapter({
					success: e => {
						that.$store.commit("changeBluetooth", true);
						that.startBluetoothDeviceDiscovery()
					},
					fail: e => {
						console.log("openBluetoothAdapter失败", e)
						return that.$tools.getBluetoothAdapter(e)
					}
				});
			},
			startBluetoothDeviceDiscovery() {
				let that = this;
				wx.showLoading({
					title: '设备搜索中',
				})
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: res => {
						wx.hideLoading()
						that.onBluetoothDeviceFound();
					},
					fail: res => {
						wx.hideLoading()
						console.log("startBluetoothDeviceDiscovery失败", res)
					}
				});
			},
			onBluetoothDeviceFound() {
				var that = this;
				const foundDevices = []
				wx.showLoading({
					title: '设备搜索中',
				})
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						device.advertisData = device.advertisData ? device.advertisData : ''
						device.advertisServiceUUIDs = device.advertisServiceUUIDs ? device
							.advertisServiceUUIDs : ""


						if (!device.name && !device.localName) {
							let value = that.$tools.ab2hex(device.advertisData, "")
							let id = value.substring(12, 16)
							if (value.indexOf('c0') !== -1 && id == '0a11') {
								wx.hideLoading()
								device.name = 'PC-B'
								let buff = device.advertisData.slice(-6)
								device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
								let tempMac = Array.from(device.mac)
								device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
								that.handleDevice(device)
								return
							}
							if (value.indexOf('c0') !== -1 && id == '0002') {
								wx.hideLoading()
								device.name = 'PCL-体脂秤'
								let buff = device.advertisData.slice(-6)
								device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
								let tempMac = Array.from(device.mac)
								device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
								that.handleDevice(device)
								return
							}
							return
						}
						if (device.name.indexOf("FitTrack") !== -1 || device.name.indexOf("SWAN") !== -1) {
							clearTimeout(myTime);
							let buff = device.advertisData.slice(2, 8)
							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("WSD") !== -1) {
							clearTimeout(myTime);
							wx.hideLoading()
							let buff = device.advertisData.slice(3, 9)
							device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
							let tempMac = Array.from(device.mac)
							device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
							that.handleDevice(device)
							return;
						}
						if (device.name.indexOf("EL") !== -1 && device.advertisServiceUUIDs != '') {
							clearTimeout(myTime);
							wx.hideLoading()
							let buff = device.advertisData.slice(0, 8)
							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.toLowerCase().indexOf('ailink') != -1 || (device.localName && device.localName.toLowerCase().indexOf('ailink') != -1)) {
							clearTimeout(myTime);
							wx.hideLoading()
							let buff = device.advertisData.slice(-6)
							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("My") != -1) {
							clearTimeout(myTime);
							wx.hideLoading()
							let buff = device.advertisData.slice(-6)
							device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
							let tempMac = Array.from(device.mac)
							device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
							that.handleDevice(device)
							return;
						}
					})
				});
				that.handleMyTime()
			},
			handleDevice(device, buff) {
				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) {
						clearTimeout(myTime);
						wx.hideLoading()
						that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
						uni.showModal({
							title: '提示',
							content: '请确定蓝牙已打开！是否继续？',
							cancelText: "取消",
							confirmText: "继续",
							success(res) {
								if (res.confirm) {
									that.startBluetoothDeviceDiscovery()
								} else {
									that.$tools.msg("您已取消操作")
								}
							}
						})
					} else {
						clearTimeout(myTime);
						that.stopBluetoothDevicesDiscovery()
					}
				}, 30000);
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log("停止搜索蓝牙设备", e)
					},
				});
			},
			// 连接蓝牙
			createBLEConnection(e) {
				let that = this;
				that.stopBluetoothDevicesDiscovery()
				that.macAddr = e.macAddr
				that.getCode()
			},
			getCode() {
				let that = this;
				clearTimeout(myTime);
				uni.showModal({
					title: '提示',
					content: '是否激活该设备?',
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							that.getActive()
						} else {
							that.$tools.msg("您已取消操作")
						}
					}
				})
			},
			getActive() {
				let that = this
				that.$model.getdevactive({
					code: that.code,
					sn: that.macAddr
				}).then(res => {
					that.$tools.msg(res.message)
					that.closeBluetoothAdapter()
					that.closeBLEConnection()
					that.devices = []
					if (res.code == 0) {
						setTimeout(function() {
							uni.reLaunch({
								url: "/pages/index/index"
							})
						}, 500)
					}
				})
			},
			/**
			 * 断开蓝牙模块
			 */
			closeBluetoothAdapter() {
				let that = this;
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('蓝牙模块关闭成功');
					}
				})
			},
			/**
			 * 断开蓝牙连接
			 */
			closeBLEConnection() {
				var that = this;
				uni.closeBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						console.log('断开蓝牙连接成功');
					}
				});
			},
		}
	}
</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: 190px;

		.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>