<template>
	<view class="weightPages">
		<view class="content ">
			<view class="status">{{textLink}}</view>
			<view class="quan">
				<view>
					<text class="weight">{{weight?weight:'0.00'}}</text>{{unit}}
				</view>
				<view class="typeInfo" v-if="typeInfo!=0">{{typeInfo==2?'稳定重量':'实时重量'}}</view>
			</view>
			<view class="btnGroup" v-if="isSave">
				<view :class="[IsLing?'disabled':'btnClose']" @click="handleIsLing">清零</view>
				<view class="baocun" @click="handleIsNum">锁定</view>
			</view>
			<view class="tips">
				<text>提示：</text>
				<text>1.请确定设备是开机状态</text>
				<text>2.请确定手机蓝牙、位置信息已打开</text>
			</view>
		</view>
		<!-- 手动记录 -->
		<view class="wrapper" v-if="isHeight">
			<view class="bg"></view>
			<view class="Blue">
				<view class="h4">测量结果提示</view>
				<view class="Blue-box">
					本次测量体重是：<text>{{weight}}{{unit}}</text>
				</view>
				<view class="Blue-box">
					上次测量身高是：<input v-model="height" type="digit" placeholder="请输入身高" />cm
				</view>
				<view class="Blue-box" v-if="userInfo.stage=='婴儿'">
					上次测量头围是：<input v-model="head" type="digit" placeholder="请输入头围" />cm
				</view>
				<view class="Blue-btn Blue-close" @click="handleBack">重新测量</view>
				<view class="Blue-btn" @click="handleGetMeasure">保存结果</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	let myTime;
	export default {
		data() {
			return {
				text: "",
				typeInfo: 0,
				head: "",
				weight: "",
				height: "",
				unit: "kg",
				Unload: false,
				isHeight: false,
				isSave: true, //保存按钮是否显示
				deviceId: "",
				serviceId: "",
				write: "",
				notify: "",
				islink: 0, //0连接中，1成功，-1失败
				textLink: "",
				isFinished: false, //是否锁定数据
				devicesList: [],
				IsLing: false, //是否点击清零按钮
				IsNum: false, //是否点击锁定按钮
			}
		},
		computed: {
			...mapState(["user", "isConnected", "isBluetoothTyle"]),
			userInfo() {
				return this.user
			}
		},
		onUnload: function() {
			let that = this
			if (!that.Unload) {
				clearTimeout(myTime)
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
				console.log("页面返回onUnload")
			}
		},
		onLoad(options) {
			let that = this
			that.typeInfo = 0
			that.height = that.userInfo.height
			that.head = that.userInfo.head_data
			that.deviceId = options.deviceId
			that.createBLEConnection()
			that.$Bluetooth.onBLEConnectionStateChange()
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
		},
		watch: {
			isConnected: function() {
				let that = this
				if (!that.isConnected) {
					let text = '测量过程中已与设备连接中断，请重新连接设备再开始测量'
					that.$tools.showModal(text)
				}
			},
			isBluetoothTyle: function() {
				let that = this
				if (!that.isBluetoothTyle) {
					let text = '蓝牙已关闭，请重新打开蓝牙后再开始测量'
					that.$tools.showModal(text)
				}
			},
			isFinished: function() {
				let that = this
				if (that.isFinished && that.typeInfo == 2) {
					setTimeout(function() {
						that.isHeight = true
					}, 500)
				}
			}
		},
		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);
					}
				});
			},
			/**
			 * 获取设备的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("FFF0") != -1) {
								that.serviceId = service.uuid;
								that.getBLEDeviceCharacteristics();
								console.log("设备的FFF0的serviceId： " + that.serviceId);
								break;
							}
						}
					},
					fail: res => {
						that.textLink = "设备连接失败，返回首页重新连接"
						console.log('获取设备的UUID失败:', res)
					}
				});
			},
			/**
			 * 获取指定服务的特征值
			 */
			getBLEDeviceCharacteristics() {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					success: res => {
						// * 读read: true, //,写write: true, //,通知notify: true
						for (let i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i];
							if (item.uuid.indexOf('0000FFF1') != -1) {
								that.notify = item.uuid
							} else if (item.uuid.indexOf('0000FFF2') != -1) {
								that.write = item.uuid
								that.writeBLECharacteristicValue("A6020500076A") // 清零
							}
						}
						that.textLink = "蓝牙连接成功，请开始测量"
						uni.notifyBLECharacteristicValueChange({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.notify,
							state: true,
						})
						uni.notifyBLECharacteristicValueChange({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.write,
							state: true,
						})
						that.isFinished = false
						setTimeout(function() {
							that.notifyBLECharacteristicValue()
						}, 600)
					},
					fail: res => {
						console.log('获取特征值失败:', JSON.stringify(res))
					}
				})
			},
			/**
			 * 开启订阅特征值
			 * read: true, //读,write: true, //写,notify: true, //广播
			 */
			notifyBLECharacteristicValue() {
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.notify,
					success(res) {
						that.isSave = true
						uni.onBLECharacteristicValueChange(function(res) {
							let value = that.$tools.ab2hex(res.value, "");
							let type = value.substring(4, 6) //  状态
							let typeInfo = value.substring(6, 8) //实时、稳定
							let weight = parseInt(value.substring(8, 14), 16) //体重
							let digit = value.substring(18, 19) // 小数
							let unit = value.substring(19, 20) //单位

							// 单位
							if (unit == "0") {
								that.unit = "kg"
							}
							if (unit == "1") {
								that.unit = "斤"
							}
							if (unit == "2") {
								that.unit = "st:lb"
							}
							if (unit == "3") {
								that.unit = "lb"
							}
							// 小数
							if (digit == "0") {
								weight = weight
							}
							if (digit == "1") {
								weight = weight / 10
							}
							if (digit == '2') {
								weight = weight / 100
							}
							if (digit == "3") {
								weight = weight / 1000
							}
							// 状态
							if (typeInfo == "01") {
								that.typeInfo = 1
								that.weight = weight
								that.IsLing = false
								that.isFinished = false
							}
							if (typeInfo == "02") {
								that.typeInfo = 2
								that.weight = weight
								that.isFinished = true
							}
							console.log("状态:", value, type, typeInfo, weight, that.unit, that.isFinished)
						});
					},
					fail(res) {
						console.log("测量失败", res.value);
					}
				});
			},
			// 清零
			handleIsLing() {
				let that = this
				if (!that.IsLing) {
					that.writeBLECharacteristicValue("A6020500076A")
					that.IsLing = true
				}
			},
			//锁定
			handleIsNum() {
				let that = this
				that.writeBLECharacteristicValue("A6020400066A")
			},
			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, buf)
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.write,
					value: buf.buffer,
					success: res => {
						console.log('下发指令成功', res.errMsg)
					},
					fail: res => {
						console.log("下发指令失败", res);
					},
				})
			},
			// 保存测量结果
			handleGetMeasure() {
				let that = this
				if (!that.height) {
					this.$tools.msg("请输入身高")
					return
				}
				that.$model.getmeasurefunit({
					adc: 0,
					weight: that.weight + that.unit,
					height: that.height,
					aud_id: that.userInfo.id,
					head_data: that.head ? that.head : 0
				}).then(res => {
					that.isHeight = false
					that.isSave = false
					if (res.code == 0) {
						that.$store.dispatch("getResult", {
							aud_id: uni.getStorageSync('userid')
						})
						that.$store.dispatch('getUserInfo', {
							aud_id: uni.getStorageSync('userid')
						})
						that.$tools.msg("测量成功")
					} else {
						that.$tools.msg("测量失败")
					}
					that.Unload = true
					uni.switchTab({
						url: "/pages/home/home"
					})
					setTimeout(function() {
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
					}, 200)
				})
			},
			//重新测量
			handleBack() {
				let that = this
				that.typeInfo = 0
				that.writeBLECharacteristicValue("A6020500076A") // 清零
				setTimeout(function() {
					that.isFinished = false
					that.isHeight = false
				}, 200)

			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log("停止搜索蓝牙设备", e)
					},
				});
			},
			// 监听蓝牙连接状态
			onBLEConnectionStateChange() {
				let that = this
				uni.onBLEConnectionStateChange(function(res) {
					console.log("监听蓝牙连接状态", res.connected)
					that.$store.commit("changeConnected", res.connected);
				})
			},
			/**
			 * 断开蓝牙模块
			 */
			closeBluetoothAdapter() {
				let that = this;
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('蓝牙模块关闭成功');
					}
				})
			},
			/**
			 * 断开蓝牙连接
			 */
			closeBLEConnection() {
				var that = this;
				uni.closeBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						console.log('断开蓝牙连接成功');
						that.$store.commit("changeConnected", false);
					}
				});
			},
		},
	}
</script>

<style scoped lang="scss">
	.content {
		background: #fff;
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.btnClose {
		color: #fff;
		background: linear-gradient(-90deg, #fccf4f, #fba418 80%) !important;
	}

	.baocun {
		color: #fff;
		background: linear-gradient(-90deg, #feaa50, #e96b13 80%) !important;
	}

	.quan {
		width: 400rpx;
		height: 400rpx;
		border: 8px solid #feaa50;
		border-radius: 50%;
		margin: 15px auto;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		box-shadow: 0px 0px 25px 10px #e96b13;
		animation: pulse 1s infinite;

		.weight {
			font-size: 50px;
			color: #000;
			font-weight: bold;
		}

		.typeInfo {
			width: 100%;
			text-align: center;
			font-size: 16px;
			color: #f0ae43;
		}
	}

	@keyframes pulse {
		0% {
			box-shadow: 0px 0px 25px 10px #e96b13;
		}

		50% {
			box-shadow: 0px 0px 25px 10px #fba418;
		}

		100% {
			box-shadow: 0px 0px 25px 10px #e96b13;
		}
	}

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

	.disabled {
		width: 150px;
		background-color: #DFDFDF;
		border: 1px solid #f7f7f7;
		color: #fff;
		text-align: center;
		padding: 7px;
		border-radius: 10px;
		margin: 15px auto;
	}

	.tips {
		font-size: 14px !important;
		margin-bottom: 20px;
	}
</style>