<template>
	<view class="weightPages">
		<view class="content ">
			<view class="title" v-if="isConnection == 0">连接中，请稍后</view>
			<view class="title" v-if="isConnection == 1">连接成功，请开始测量</view>
			<view class="title" v-if="isConnection == 2" @click="openBluetoothAdapter">连接失败，点击重新连接</view>
			<view class="text">{{text}}</view>
			<view class="image">
				<image src="/BLEPages/static/j03.gif" class="image3"></image>
			</view>
			<view class="tips">
				<text>请确保：</text>
				<text>1.请确定设备是开机状态</text>
				<text>2.请确定手机蓝牙、位置信息已打开</text>
				<text>3.ios系统需打开设置—>应用—>微信里的蓝牙权限</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	var myTime;
	export default {
		data() {
			return {
				text: "",
				weight: "",
				imp: 0,
				macAddr: "",
				deviceId: "",
				serviceId: "",
				Unload: false,
				stopblue: true,
				isConnection: 0,
			}
		},
		computed: {
			...mapState(["user", "isConnected", "isBluetoothTyle", 'appTheme']),
			info() {
				return this.user
			}
		},
		onUnload: function() {
			let that = this
			if (!that.Unload) {
				that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
				clearTimeout(myTime);
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
				uni.switchTab({
					url: "/pages/index/index"
				})
				console.log("页面返回onUnload")
			}
		},
		watch: {
			isConnected: function() {
				let that = this
				if (!that.isConnected) {
					that.handleBack()
					that.isConnection = 2
				}
			},
			isBluetoothTyle: function() {
				let that = this
				if (!that.isBluetoothTyle) {
					that.handleBack()
					that.isConnection = 2
				}
			},
			stopblue: function() {
				let that = this
				if (!that.stopblue) {
					console.log("停止成功", that.weight, that.imp)
					if (that.imp == 0) {
						uni.showModal({
							title: '提示',
							content: "体脂测量失败，是否保存本次测量结果？",
							cancelText: "放弃",
							confirmText: "保存",
							success(res) {
								if (res.confirm) {
									that.imp = 0
									that.handleGetMeasure()
								} else {
									that.Unload = true
									that.startBluetoothDeviceDiscovery()
									that.closeBLEConnection()
									that.closeBluetoothAdapter()
									uni.switchTab({
										url: "/pages/index/index"
									})
								}
							}
						})
					} else {
						that.handleGetMeasure()
					}
				}
			}
		},
		onLoad(options) {
			let that = this
			that.text = ""
			// 导航栏颜色
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.appTheme,
			})
			if (options && options.deviceId) {
				that.deviceId = options.deviceId
				that.openBluetoothAdapter()
			}
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
		},
		methods: {
			// 重新连接
			openBluetoothAdapter() {
				let that = this
				that.text = ""
				that.stopblue = true
				uni.openBluetoothAdapter({
					success: e => {
						that.isConnection = 0
						that.startBluetoothDeviceDiscovery()
						console.log('初始化蓝牙成功:' + e.errMsg);
					},
					fail: e => {
						that.isConnection = 2
						that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
					}
				});
			},
			// 监听蓝牙连接状态
			onBLEConnectionStateChange() {
				let that = this
				uni.onBLEConnectionStateChange(function(res) {
					console.log("蓝牙连接状态", JSON.stringify(res));
					if (!res.connected) {
						that.Unload = true
						that.isConnection = 2
						clearTimeout(myTime);
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
					}
					that.$store.commit("changeConnected", res.connected);
				})
			},
			// 开始搜寻附近的蓝牙外围设备
			startBluetoothDeviceDiscovery() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: res => {
						that.isConnection = 0
						that.onBluetoothDeviceFound();
					},
					fail: res => {
						that.isConnection = 2
						that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				var that = this;
				that.isConnection = 0
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						if (device.name.indexOf('ELS') != -1 || (device.localName && device.localName
								.indexOf('PC') != -1)) {
							clearTimeout(myTime);
							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()
							if (device.deviceId.indexOf(that.deviceId) !== -1 || device.macAddr.indexOf(
									that.deviceId) !== -1) {
								let dw1 = "kg"
								let dw2 = "kg"
								let value = that.$tools.ab2hex(device.advertisData, "")
								let status = value.substring(2, 4) //测量状态
								let data = parseInt(value.substring(4, 8), 16)
								let msg = parseInt(value.substring(8, 9), 16).toString(2)
								let msg0 = parseInt(value.substring(9, 10), 16).toString(2)
								let type = that.$tools.PrefixZero(msg0, 4).substring(3, 4) //实时、稳定
								let zfz = that.$tools.PrefixZero(msg0, 4).substring(2, 3) //正负值
								let num = that.$tools.PrefixZero(msg0, 4).substring(0, 2) //小数点
								let dw = that.$tools.PrefixZero(msg, 4).substring(0, 4) //单位
								console.log("体重", data, )
								console.log("状态", type)
								console.log("正负值", zfz)
								console.log("小数点", num)
								console.log("单位", dw, )
								if (dw == "0001") {
									dw1 = '斤'
									dw2 = "jin"
								}
								if (dw == "0011") {
									dw1 = 'lb'
									dw2 = 'lb'
								}
								if (num == "01") {
									data = data / 10
								}
								if (num == "10") {
									data = data / 100
								}
								if (num == "11") {
									data = data / 1000
								}
								if (type == "0") {
									that.text = "您的实时体重是：" + data + dw1
								}
								if (type == "1") {
									that.text = "您的稳定体重是：" + data + dw1
								}
								if (status == "01") {
									that.imp = parseInt(value.substring(10, 14), 16)
									that.text = "您的体重是：" + data + dw1
									that.macAddr = device.macAddr
									that.deviceId = device.deviceId;
									that.weight = data + dw2
									uni.stopBluetoothDevicesDiscovery({
										success: e => {
											return that.stopblue = false
										},
									});
									return
								} else if (status == "FF" || status == "02") {
									that.text = status == "FF" ? "测量失败或不稳定" : '超出测量范围'
									that.isConnection = 2
									that.stopBluetoothDevicesDiscovery();
									return
								}

							}

						}
					})
				});
				that.handleMyTime()
			},
			handleMyTime() {
				var that = this;
				myTime = setTimeout(function() {
					if (!that.macAddr) {
						clearTimeout(myTime);
						that.Unload = true
						that.isConnection = 2
						that.devicesList = []
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
					}
				}, 20000);
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log("停止搜索蓝牙设备", e)
					},
				});
			},
			// 保存测量结果
			handleGetMeasure() {
				console.log("保存结果")
				let that = this
				that.$model.getmeasure({
					weight: that.weight,
					imp: that.imp ? that.imp : 0,
					ecode: that.macAddr,
					height: that.info.height,
					familyid: that.info.familyid,
				}).then(res => {
					if (res.code == 0) {
						that.$tools.msg("测量成功")
						that.$store.dispatch("getUserInfo", {
							familyid: that.info.familyid,
						});
						that.$store.dispatch("getResult", {
							birthday: that.info.birthday,
							familyid: that.info.familyid,
							height: that.info.height,
							sex: that.info.sex,
						});
					} else {
						console.log("测量失败", res.message)
						that.$tools.msg(res.message)
					}
					that.Unload = true
					setTimeout(function() {
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
						uni.switchTab({
							url: "/pages/index/index"
						})
					}, 200)
				})
			},
			handleBack(ind) {
				let that = this
				that.Unload = true
				clearTimeout(myTime)
				that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
			},
			/**
			 * 断开蓝牙模块
			 */
			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">
	.image3 {
		width: 200px !important;
		height: 340px !important;
	}
</style>