<template>
	<view class="content">
		<view class="tips" v-if="!isstart">
			<view class="top">
				<view class="left cgreen f-l">T</view>
				<view class="right">
					<text class="cgreen">肺活量测试</text>
					<text class="text">肺活量测试能让我们更好的了解您，为您生成详细的健康报告。</text>
				</view>
			</view>
			<view class="list">
				<view class="item" v-if="number1">
					<text class="ml-10 mr-10">1</text>
					<text>吸气肺活量</text>
					<text class="cgreen">{{number1}}ml</text>
					<text>吸气速度</text>
					<text class="cgreen level">{{level1}}</text>
				</view>
				<view class="item" v-if="number2">
					<text class="ml-10 mr-10">2</text>
					<text>吸气肺活量</text>
					<text class="cgreen">{{number2}}ml</text>
					<text>吸气速度</text>
					<text class="cgreen level">{{level2}}</text>
				</view>
				<view class="item" v-if="number3">
					<text class="ml-10 mr-10">3</text>
					<text>吸气肺活量</text>
					<text class="cgreen">{{number3}}ml</text>
					<text>吸气速度</text>
					<text class="cgreen level">{{level3}}</text>
				</view>
			</view>
			<view class="title" v-if="number3==''">
				<view :class="[second==5?'cgreen':'']">您好！第<text>{{number1!=0?'二':number2!=''?'三':'一'}}</text>次测试开始
				</view>
				<view :class="[second==3?'cgreen':'']">放下呼吸训练器，缓慢呼气，尽可能排空肺部气体</view>
				<view :class="[second==1?'cgreen':'']">使用呼吸训练器，缓慢吸气，直至到达极限</view>
			</view>
			<view class="data" v-if="number3">
				<view class="val">
					<text>{{average.toFixed(2)}}ml</text>
					平均吸气肺活量
				</view>
				<view class="text">
					根据您的个人信息，您的达标吸气肺活量为{{standard}}ml。您本次测试吸气速度{{averageS}}L/min,肺活量测试结果{{average.toFixed(2)}}ml。结合您的身体状态和改善目标，我们将为您生成详细的健康报告。
				</view>
			</view>
			<view class="btn" v-if="number3" @click="handleGetMeasure">查看本次报告</view>
			<view class="btn close" v-if="number3" @click="isstart=true">我想重新测试</view>
			<view class="btn" v-if="number1==0||number2==0||number3==0">
				{{second}}S后开始第<text>{{number1!=0?'二':number2!=0?'三':'一'}}</text>次测试
			</view>
		</view>
		<!-- 开始测量 -->
		<view class="weight" v-else>
			<view class="title cgreen">使用呼吸训练器，缓慢吸气，直至到达极限</view>
			<view class="box1">
				<view class="time">吸气速度 <text class="cgreen ml-5">{{LiuS}}L/min</text></view>
				<view class="item">
					<view class="image">
						<!--  -->
						<!-- <image src="../../static/01.gif" mode="widthFix"> -->
						<!-- </image> -->
					</view>
					<view class="center  mt-15">
						<view class="level"></view>
						<view class="level level-bg" :style="{'top':Number(100 - offset)+'%'}"></view>
						<view class="level-item">
							<view class="ite" v-for="(ite,ind) in list">{{ite.text}}</view>
						</view>
					</view>
				</view>
				<view class="val">
					<text>{{text}}ml</text>吸气肺活量
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	let myTime;
	let cnt = 0;
	let count = 0;
	let lastValue = null;
	export default {
		data() {
			return {
				isEnd: false,
				isstart: false, //是否开始测量
				number1: 0,
				number2: 0,
				number3: 0,
				level1: "",
				level2: "",
				level3: "",
				average: "", //平均
				averageS: "", //平均流速
				text: 0, //实时
				LiuS: "", //流速
				serviceId: "",
				deviceId: "",
				notify: "",
				write: "",
				second: 5, //倒计时
				standard: "", //标准
				offset: 0, //
				listS: [],
			}
		},
		computed: {
			...mapState(["user", "UseBlueConfig", "lungLevel"]),
			info() {
				return this.user
			},
			list() {
				let that = this
				let standard = ""
				that.lungLevel.forEach(ite => {
					if (ite.text == "及格") {
						standard = ite.min_val
					}
				})
				that.standard = standard
				return this.lungLevel
			}
		},
		onUnload: function() {
			let that = this
			that.useBluetooth.clearBluetoothStatus()
		},
		onLoad(options) {
			let that = this
			if (options && options.deviceId) {
				that.deviceId = options.deviceId
			}
			that.useBluetooth.createBLEConnection("FFE0")
			that.useBluetooth.onBLEConnectionStateChange()
			that.useBluetooth.onBluetoothAdapterStateChange()
		},
		watch: {
			'UseBlueConfig.isUseConnect'() {
				let that = this
				if (!that.UseBlueConfig.isUseConnect) {
					that.$tools.showModal('蓝牙连接已断开，请重新连接后测量')
				}
			},
			'UseBlueConfig.serviceId'() {
				let that = this
				if (that.UseBlueConfig.serviceId) {
					that.serviceId = that.UseBlueConfig.serviceId
					that.getBLEDeviceCharacteristics()
				}
			},
			second: function() {
				let that = this
				if (that.second <= 0) {
					cnt++
					that.isstart = true
					that.sendData("FA02A29E") //蓝牙主动上报
					that.offset = 0
					that.text = 0
				}
			},
			// 是否结束测量
			isEnd: function() {
				let that = this
				if (that.isEnd) {
					console.log("结束测量2", that.isEnd)
					that.isstart = false
					that.sendData("FA02A39F")
					that.level3 = that.handlelenver(that.number2)
					that.average = (Number(that.number3) + Number(that.number2) + Number(that.number1)) / 3
					var sum = 0
					for (var i = 0; i < that.listS.length; i++) {
						sum += Number(that.listS[i]);
					}
					that.averageS = (sum / that.listS.length).toFixed(2)
					console.log((sum / that.listS.length))
				}
			}

		},
		methods: {
			/**
			 * 获取指定服务的特征值
			 */
			getBLEDeviceCharacteristics() {
				let characteristicsList = [];
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					success: res => {
						console.log("服务的特征值成功", 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('0000FFE9') != -1) {
								that.write = item.uuid
							} else if (item.uuid.indexOf('0000FFE4') != -1) {
								that.notify = item.uuid
							}
						}
						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,
						})
						uni.onBLECharacteristicValueChange(function(res) {
							let value = that.$tools.ab2hex(res.value, "");
							// 流量
							let LiuL = value.substring(14, 16) + value.substring(10, 14)
							let LiuL2 = parseInt(LiuL, 16) / 1000
							// 流速
							let LiuS = parseInt(value.substring(22, 26), 16) + parseInt(value
								.substring(18, 22), 16)
							let LiuS2 = LiuS / 1000

							if (Number(LiuL2) > 0) {
								that.text = LiuL2.toFixed(0)
								that.LiuS = LiuS2.toFixed(1)
								that.offset = that.handleoffset(that.text)
								// 第一次
								if (cnt == 1) {
									// 流量
									if (that.text == lastValue) {
										count++
										if (count >= 30) {
											that.isstart = false
											that.sendData("FA02A39F") //关闭蓝牙主动上报
											that.number1 = LiuL2.toFixed(0)
											that.level1 = that.handlelenver(that.number1)
											that.second = 5
											that.countdown()
											that.LiuS = 0
											return
										}
									} else {
										count = 0
										lastValue = that.text // 更新lastValue
									}
								}
								if (cnt == 2) {
									if (that.text == lastValue) {
										count++
										if (count >= 30) {
											that.isstart = false
											that.sendData("FA02A39F") //关闭蓝牙主动上报
											that.number2 = LiuL2.toFixed(0)
											that.level2 = that.handlelenver(that.number2)
											that.second = 5
											that.countdown()
											that.LiuS = 0
											return
										}
									} else {
										count = 0
										lastValue = that.text // 更新lastValue
									}
									// console.log('流量2', cnt, LiuL2, count)
								}
								if (cnt == 3) {
									// 流速
									if (that.LiuS != 0 || that.LiuS != 0.0) {
										that.listS.push(that.LiuS)
									}
									// 流量
									if (that.text == lastValue) {
										count++
										if (count >= 15) {
											that.number3 = LiuL2.toFixed(0)
											that.isEnd = true
											return
										}
									} else {
										count = 0
										lastValue = that.text // 更新lastValue
									}
									console.log('流量3', cnt, count)
								}
							}
						})
					},
					fail: res => {
						console.log('获取特征值失败:', JSON.stringify(res))
					}
				})
			},
			// 开启蓝牙主动上报模式
			sendData(str) {
				let that = this
				let buf = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				}))
				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);
					},
				})
			},
			// 等级
			handlelenver(value) {
				let that = this
				let text = ""
				that.list.forEach(ite => {
					if (Number(value) <= Number(ite.max_val) && Number(value) >= Number(ite.min_val)) {
						text = ite.text
					}
				})
				return text
			},
			//标准动态
			handleoffset(value) {
				let that = this
				let number = 0
				let length = that.list.length
				number = value / (that.list[0].max_val - that.list[length - 1].min_val) * 100
				return number.toFixed(0)
			},
			// 保存测量结果
			handleGetMeasure() {
				let that = this
				that.$model.getMeasureLung({
					aud_id: uni.getStorageSync('userid'),
					one: that.number1,
					two: that.number2,
					three: that.number3,
					flow: that.averageS
				}).then(res => {
					if (res.code == 0) {
						that.$store.dispatch('getUserInfo', {
							aud_id: uni.getStorageSync('userid')
						})
						that.$store.dispatch("getLungResult", {
							aud_id: uni.getStorageSync('userid')
						})
					}
					setTimeout(function() {
						uni.switchTab({
							url: "/pages/home/home"
						})
					}, 200)
				})
			},
			// 5秒倒计时
			countdown() {
				let that = this
				count = 0
				lastValue = null
				var timer = setInterval(function() {
					that.second--;
				}, 1000);
				setTimeout(() => {
					clearInterval(timer)
					that.second = 0
				}, 5000)
			},
		}
	}
</script>

<style scoped lang="scss">
	@import "./scss/PCV02.scss";

	.content {
		width: calc(100% - 30px);
		padding: 0 15px;
		min-height: 100vh;
		color: #5d5651;
		background-color: #000;
	}
</style>