<template>
	<view class="weightPages">
		<view class="content ">
			<view class="status">{{bleTipsText}}</view>
			<view class="quan2">
				<view>
					<text class="weight">{{weightPage?weightPage:'0.00'}}</text>
				</view>
				<view class="typeInfo" v-if="typeInfo!=0">{{typeInfo==2?$t('StableWeight'):$t('realTimeWeight')}}</view>
			</view>
			<view class="tips">
				<text>{{$t("msgTitle")}}:</text>
				<text>1.{{$t("onDeviceBluetoothTips")}}</text>
				<text>2.{{$t("openDeviceeMeasureTips")}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	export default {
		data() {
			return {
				typeInfo: 0,
				weightPage: "",
				weight: "",
				height: "",
				unit: "kg",
				deviceId: "",
				serviceId: "",
				write: "",
				notify: "",
				imp: 0,
				leftHandImp: 0,
				rightHandImp: 0,
				leftFootImp: 0,
				rightFootImp: 0,
				text: "",
				stopblue: true
			}
		},
		computed: {
			...mapState(["user", "bleValue", "isBluetoothTyle"]),
			userInfo() {
				return this.user
			},
			bleTipsText() {
				return this.bleValue.bleTipsText
			}
		},
		onLoad(options) {
			let that = this
			that.typeInfo = 0
			that.height = that.userInfo.height
			that.deviceId = options.deviceId
		},
		onUnload: function() {
			let that = this
			that.$ble.closeBLEConnection()
			that.$ble.closeBluetoothAdapter()
			console.log("onUnload")
		},
		watch: {
			isBluetoothTyle() {
				let that = this
				if (!that.isBluetoothTyle) {
					that.$tools.showModal(that.$t("linkBluetoothFail2"))
				}
			},
			bleValue: {
				handler(newVal, oldVal) {
					let that = this
					if (newVal.serviceId) {
						that.deviceId = newVal.deviceId
						that.serviceId = newVal.serviceId
						that.getBLEDeviceCharacteristics(newVal.serviceId)
					}
				},
				deep: true,
				immediate: true
			},
			stopblue: function() {
				let that = this
				if (!that.stopblue) {
					if (that.imp == 0 || that.leftHandImp == 0 || that.rightHandImp ==
						0 || that.leftFootImp == 0 || that.rightFootImp == 0) {
						uni.showModal({
							title: that.$t("msgTitle"),
							content: that.$t("FatFailure"),
							cancelText: that.$t("waive"),
							confirmText: that.$t("Save"),
							success(res) {
								if (res.confirm) {
									that.imp = 0
									that.handleGetMeasure()
								} else {
									uni.switchTab({
										url: "/pages/index/index"
									})
								}
							}
						})
					} else {
						that.handleGetMeasure()
					}
				}
			}
		},
		methods: {
			/**
			 * 获取指定服务的特征值
			 */
			getBLEDeviceCharacteristics(serviceId) {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: serviceId,
					success: res => {
						for (let i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i];
							if (item.uuid.indexOf('0000FFE2') != -1) {
								that.notify = item.uuid
							} else if (item.uuid.indexOf('0000FFE3') != -1) {
								that.write = item.uuid
								that.writeBLECharacteristicValue("a603420100466a")
							}
						}
						that.$store.commit("changeBluetoothValue", {
							type: 1,
							isConnectStatus: 2,
							bleTipsText: that.$t("linkBluetoothSuccess"),
						})
						uni.notifyBLECharacteristicValueChange({
							deviceId: that.deviceId,
							serviceId: serviceId,
							characteristicId: that.notify,
							state: true,
						})
						uni.notifyBLECharacteristicValueChange({
							deviceId: that.deviceId,
							serviceId: serviceId,
							characteristicId: that.write,
							state: true,
						})

						uni.onBLECharacteristicValueChange((characteristic) => {
							let payload = that.$tools.ab2hex(characteristic.value, '')
							let type = payload.substring(8, 10) //称重类型
							let weight = parseInt(payload.substring(12, 18), 16) //体重
							let digit = payload.substring(18, 19) //小数
							let unit = payload.substring(19, 20) //单位
							let typeInfo = payload.substring(10, 12) //试试体重
							console.log("开始测量", payload)
							if (type == "01") { //体脂模式

								if (digit == "1") {
									weight = weight / 10
								}
								if (digit == "2") {
									weight = weight / 100
								}
								if (digit == "3") {
									weight = weight / 1000
								}
								if (unit == "0") {
									that.unit = "kg"
								}
								if (unit == "1") {
									that.unit = "斤"
								}
								if (unit == "6") {
									that.unit = "lb"
								}
								if (unit == "4") {
									let y = weight - Math.trunc(weight / 14) * 14
									let y0 = y >= 10 ? Math.trunc(y) : y.toFixed(1)
									let data0 = Math.trunc(weight / 14) + ':' + y0
									that.weightPage = data0 + "st:lb"
									that.weight = weight + "lb"
									that.unit = "lb"
								} else {
									that.weightPage = weight + that.unit
									that.weight = weight + that.unit
								}
								that.typeInfo = typeInfo
							}

							if (type == "02") { //阻抗模式
								if (typeInfo == "02") {
									that.imp = 0
									that.leftHandImp = 0
									that.rightHandImp = 0
									that.leftFootImp = 0
									that.rightFootImp = 0
								}
								if (typeInfo == "03") {
									let mcu = payload.substring(12, 14)
									let Imp = parseInt(payload.substring(14, 22), 16)
									console.log("阻抗类型：", mcu)
									if (mcu == "02") {
										that.leftHandImp = Imp
										console.log("左手阻抗", that.leftHandImp)
									}
									if (mcu == "03") {
										that.rightHandImp = Imp
										console.log("右手阻抗", that.rightHandImp)
									}
									if (mcu == "04") {
										that.leftFootImp = Imp
										console.log("左脚阻抗", that.leftFootImp)
									}
									if (mcu == "05") {
										that.rightFootImp = Imp
										console.log("右脚阻抗", that.rightFootImp)
									}

									if (mcu == "07") {
										that.imp = Imp
										console.log("躯干阻抗", that.imp, that.weight)
									}
								}
							}

							if (type == "0f" || type == "ff") { //测量完成
								that.stopblue = false
							}

						})
					},
					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, 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(that.$t("verifyHeight"))
					return
				}
				that.$model.getmeasurefunit({
					weight: that.weight,
					height: that.height,
					adc: that.imp,
					aud_id: that.userInfo.aud_id,
					lefthand: that.leftHandImp,
					righthand: that.rightHandImp,
					leftfoot: that.leftFootImp,
					rightfoot: that.rightFootImp,
				}).then(res => {
					that.isHeight = false
					that.isSave = false
					if (res.code == 0) {
						that.$store.dispatch('getUserInfo', {
							aud_id: that.user.aud_id
						})
						that.$store.dispatch("getResult", {
							aud_id: that.user.aud_id
						})
						that.$tools.msg(that.$t("msgSuccess"))
					} else {
						that.$tools.msg(that.$t("msgFail"))
					}
					setTimeout(function() {
						uni.switchTab({
							url: "/pages/index/index"
						})
					}, 500)
				})
			},
		},
	}
</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;
	}

	.quan2 {
		width: 480rpx;
		height: 480rpx;
		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: 42px;
			color: #000;
			margin-right: 10px;
			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: calc(100% - 30px);
		font-size: 16px;
		height: 35px;
		line-height: 35px;
		text-align: center;
		border-radius: 15px;
		margin: 15px;
		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>