<template>
	<view class="content weightPages">
		<view class="content ">
			<view class="status">{{textLink}}</view>
			<view class="text">{{textW}}</view>
			<view class="text">{{textH}}</view>
			<view class="image">
				<image src="/pageTwo/static/F018P01.gif" class="image3"></image>
			</view>
			<view class="tips">
				<view>提示：</view>
				<text>1.请确定设备已开机</text>
				<text>2.请确定手机蓝牙及位置信息已打开</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	var myTime;
	export default {
		data() {
			return {
				textW: "",
				textH: "",
				height: "",
				weight: "",
				imp: 0,
				macAddr: "",
				deviceId: "",
				serviceId: "",
				uuid1: "",
				uuid2: "",
				uuid3: "",
				Unload: false,
				isConnection: 0,
				data01: {},
				data02: {},
				BLEResult: {},
				textLink: ""
			}
		},
		computed: {
			...mapState(["user", "isConnected", "isBluetoothTyle"]),
			userInfo() {
				return this.user
			}
		},
		onUnload: async function() {
			let that = this
			if (!that.Unload) {
				clearTimeout(myTime)
				that.$store.state.devicesList2 = []
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
			}
		},
		watch: {
			isConnected: function() {
				let that = this
				if (!that.isConnected) {
					console.log('F01PRO：isConnected-' + that.isConnected)
					let text = '测量过程中已与设备连接中断，请重新连接设备再开始测量'
					that.$tools.showModal(text)
				}
			},
			isBluetoothTyle: function() {
				let that = this
				if (!that.isBluetoothTyle) {
					console.log('F01PRO：isBluetoothTyle-' + that.isBluetoothTyle)
					let text = '蓝牙已关闭，请重新打开蓝牙后再开始测量'
					that.$tools.showModal(text)
				}
			},
		},
		onLoad(options) {
			let that = this
			console.log("options", options)
			that.deviceId = options.deviceId
			that.createBLEConnection()
			that.onBLEConnectionStateChange()
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
		},
		methods: {
			// 连接蓝牙
			createBLEConnection() {
				let that = this;
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						that.textLink = "蓝牙连接中"
						setTimeout(function() {
							that.getBLEDeviceServices()
						}, 1000)
					},
					fail: res => {
						that.textLink = "设备连接失败，返回首页重新连接"
						console.log("设备连接失败，请重新连接", res, that.deviceId);
					}
				});
			},
			// 监听蓝牙连接状态
			onBLEConnectionStateChange() {
				let that = this
				uni.onBLEConnectionStateChange(function(res) {
					console.log("监听蓝牙连接状态", res.connected)
					that.$store.commit("changeConnected", res.connected);
				})
			},
			/**
			 * 获取设备的UUID
			 */
			getBLEDeviceServices() {
				let serviceList = [];
				let that = this;
				uni.getBLEDeviceServices({
					deviceId: that.deviceId,
					success: res => {
						console.log("获取设备的UUID成功", res)
						serviceList = res.services;
						for (let i = 0; i < serviceList.length; i++) {
							let service = serviceList[i];
							if (service.uuid.indexOf('FFE0') != -1) {
								that.serviceId = service.uuid;
								that.getBLEDeviceCharacteristics(that.deviceId, service.uuid);
								console.log("设备的FFE0的serviceId： ", that.serviceId);
								break;
							}
						}
					},
					fail: res => {
						that.textLink = "设备连接失败，返回首页重新连接"
						console.log('获取设备的UUID失败:', res)
					}
				});
			},
			/**
			 * 获取指定服务的特征值
			 */
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				let characteristicsList = [];
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success: res => {
						console.log("服务的特征值成功", res)
						characteristicsList = res.characteristics;
						for (let i = 0; i < characteristicsList.length; i++) {
							let item = characteristicsList[i];
							if (item.uuid.indexOf('0000FFE1') != -1) {
								that.uuid1 = item.uuid //下发数据
							} else if (item.uuid.indexOf('0000FFE2') != -1) {
								that.uuid2 = item.uuid //监听数据
							} else if (item.uuid.indexOf('0000FFE3') != -1) {
								that.uuid3 = item.uuid //写入设置
								that.writeBLECharacteristicValue("a603420100466a")

							}
						}

						// 打开监听
						that.textLink = "蓝牙连接成功，请开始测量"
						uni.notifyBLECharacteristicValueChange({
							deviceId,
							serviceId,
							characteristicId: that.uuid2,
							state: true,
						})
						uni.notifyBLECharacteristicValueChange({
							deviceId,
							serviceId,
							characteristicId: that.uuid3,
							state: true,
						})

						uni.onBLECharacteristicValueChange((characteristic) => {
							const raw = new Uint8Array(characteristic.value);
							// console.log("raw", raw)

							let payload = that.$tools.ab2hex(characteristic.value, '')
							let type = payload.substring(8, 10)
							// let sex = that.userInfo.gender == 1 ? "01" : "00"
							// let age = that.userInfo.age.toString(16)
							// let height = Math.round(that.userInfo.height)
							// let j = Number(26 + 5 + 1 + sex + age + height).toString(16)
							// let arr = "A700260501" + sex + age + height.toString(16) + "00" + j.substr(
							// 	j.length - 2, 2) + "7A"

							// let j = Number(38 + 5 + 1 + 1 + 17 + 151).toString(16)
							// let arr = "A70026050101169700"+ j.substr(j.length - 2, 2) + "7A"

							console.log("开始测量", payload)
							if (payload == "a603420100466a" || type == '03') {
								// 男性，22岁，180身高
								that.writeBLECharacteristicValue("a7002605010116b400f77a")
							}
							if (type == "10" || type == "30" || type == "40") { //体脂模式
								let typeInfo = payload.substring(12, 14)
								let data = parseInt(payload.substring(14, 20), 16)
								let msg = parseInt(payload.substring(20, 22), 16).toString(2)
								let dw = that.$tools.PrefixZero(msg, 8).substring(4, 8)
								let num = that.$tools.PrefixZero(msg, 8).substring(0, 4)
								let dw1 = "kg"
								if (dw == "0001") {
									dw1 = '斤'
								}
								if (dw == "0110") {
									dw1 = 'lb'
								}
								if (num == "0001") {
									data = data / 10
								}
								if (num == "0010") {
									data = data / 100
								}
								if (num == "0011") {
									data = data / 1000
								}
								if (typeInfo == "01") {
									that.textW = "您的实时体重是：" + data + dw1
								}
								if (typeInfo == "02") {
									that.textW = "您的体重是：" + data + dw1
									that.weight = data + dw1
								}
							}
							if (type == "14" || type == "41") { //身高模式
								let height = parseInt(payload.substring(12, 16), 16)
								let numH = parseInt(payload.substring(18, 20), 16)
								if (numH == "1") {
									height = height / 10
								}
								if (numH == "2") {
									height = height / 100
								}
								that.textH = "您的身高是：" + height + "cm"
								that.height = height
								console.log("身高模式:", that.height)
							}
							if (type == "11") { //阻抗模式
								let typeInfo = payload.substring(12, 14)
								if (typeInfo == "01") { //测量中
									that.textLink = '正在测量体脂：请双手紧握扶手'
								}
								if (typeInfo == "02") {
									that.imp = 0
									that.textLink = ""
								}
								if (typeInfo == "04") {
									that.textLink = ""
									that.imp = parseInt(payload.substring(16, 20), 16)
								}
								console.log("阻抗:", that.imp)
							}
							if (type == '15') {
								let typeInfo = payload.substring(12, 14)
								if (typeInfo == "01") {
									that.data01 = {
										fat_r: parseInt(payload.substring(14, 18), 16) / 10,
										sfr: parseInt(payload.substring(18, 22), 16) / 10,
										visceral: parseInt(payload.substring(22, 26), 16),
										muscle: parseInt(payload.substring(26, 30), 16) / 10,
										kcal: parseInt(payload.substring(30, 34), 16),
										bodyage: parseInt(payload.substring(34, 36), 16),
									}
								}
								if (typeInfo == '02') {
									that.data02 = {
										bone: parseInt(payload.substring(14, 18), 16) / 10,
										water: parseInt(payload.substring(18, 22), 16) / 10,
										protein: parseInt(payload.substring(22, 26), 16) / 10,
										bmi: parseInt(payload.substring(26, 30), 16) / 10,
										fatlevlval: parseInt(payload.substring(30, 32), 16) / 10,
									}
								}
								console.log("体脂数据", that.data01, that.data02)
								that.BLEResult.info = Object.assign(that.data01, that.data02)
							}
							if (type == "80") { //测量结束
								that.BLEResult.weight = that.weight
								that.BLEResult.adc = that.imp ? that.imp : 0
								that.BLEResult.height = (that.height ? that.height : that.userInfo
									.height) + 'cm'
								that.BLEResult.aud_id = that.userInfo.id
								console.log("体脂成功：", that.BLEResult)
								that.handleGetMeasure(that.BLEResult)
							}
						})
					},
					fail: res => {
						console.log('获取特征值失败:', JSON.stringify(res))
					}
				})
			},
			writeBLECharacteristicValue(str) {
				var that = this;
				let buf = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				}))
				console.log("buffer", str)
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.uuid3,
					value: buf.buffer,
					success: res => {
						console.log('下发指令成功', res.errMsg)
					},
					fail: res => {
						console.log("下发指令失败", res);
					},
				})
			},
			// 保存测量结果
			handleGetMeasure(data) {
				console.log("保存结果")
				let that = this
				that.$model.getmeasurefunit(data).then(res => {
					if (res.code == 0) {
						that.$store.dispatch('getUserInfo', {
							aud_id: uni.getStorageSync('userid')
						})
						that.$store.dispatch("getResult", {
							aud_id: uni.getStorageSync('userid')
						})
						setTimeout(() => {
							uni.showToast({
								title: '测量成功'
							})
						}, 500)
					} else {
						uni.showToast({
							title: res.message,
							icon: "error"
						})
					}
					that.Unload = true
					uni.switchTab({
						url: "/pages/home/home"
					})
					setTimeout(function() {
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
					}, 500)
				})
			},
			/**
			 * 断开蓝牙模块
			 */
			closeBluetoothAdapter() {
				let that = this;
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('F01PRO：蓝牙模块关闭成功');
					}
				})
			},
			/**
			 * 断开蓝牙连接
			 */
			closeBLEConnection() {
				var that = this;
				uni.closeBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						console.log('F01PRO：断开蓝牙连接成功');
						that.$store.commit("changeConnected", false);
					}
				});
			},
		},
	}
</script>

<style scoped lang="scss">
	.image3 {
		width: 200px !important;
		height: 340px !important;
	}

	.status {
		width: 70%;
		font-size: 16px;
		height: 35px;
		line-height: 35px;
		text-align: center;
		border-radius: 15px;
		margin: 15px auto;
		background-color: #ffdda6;
	}
</style>