<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">{{$t("lung.lungTitle")}}</text>
					<text class="text">{{$t("lung.lungExplain0")}}</text>
				</view>
			</view>
			<view class="list">
				<view class="item" v-if="number1">
					<text class="ml-10 mr-10">1</text>
					<text>{{$t("lung.lungsuction")}}</text>
					<text class="cgreen">{{number1}}ml</text>
					<text>{{$t("lung.lungsuctionspeed")}}</text>
					<text class="cgreen level">{{level1}}</text>
				</view>
				<view class="item" v-if="number2">
					<text class="ml-10 mr-10">2</text>
					<text>{{$t("lung.lungsuction")}}</text>
					<text class="cgreen">{{number2}}ml</text>
					<text>{{$t("lung.lungsuctionspeed")}}</text>
					<text class="cgreen level">{{level2}}</text>
				</view>
				<view class="item" v-if="number3">
					<text class="ml-10 mr-10">3</text>
					<text>{{$t("lung.lungsuction")}}</text>
					<text class="cgreen">{{number3}}ml</text>
					<text>{{$t("lung.lungsuctionspeed")}}</text>
					<text class="cgreen level">{{level3}}</text>
				</view>
			</view>
			<view class="title" v-if="number3==''">
				<view :class="[second==5?'cgreen':'']">
					{{number1!=0?$t("lung.lungsecond"):number2!=''?$t("lung.lungthird"):$t("lung.lungfirst")}}
				</view>
				<view :class="[second==3?'cgreen':'']">{{$t("lung.lungExplain1")}}</view>
				<view :class="[second==1?'cgreen':'']">{{$t("lung.lungExplain2")}}</view>
			</view>
			<view class="data" v-if="number3">
				<view class="val">
					<text>{{average.toFixed(2)}}ml</text>
					{{$t("lung.averagelungsuction")}}
				</view>
				<view class="text">
					{{$t("lung.lungExplain3")}}{{standard}}ml。{{$t("lung.nowlungsuctionspeed")}}{{averageS}}L/min,{{$t("lung.lungresult")}}{{average.toFixed(2)}}ml。{{$t("lung.lungExplain4")}}
				</view>
			</view>
			<view class="btn" v-if="number3" @click="handleGetMeasure">{{$t("lung.lunglookreport")}}</view>
			<view class="btn close" v-if="number3" @click="isstart=true">{{$t("lung.remeasure")}}</view>
			<view class="btn" v-if="number1==0||number2==0||number3==0">
				{{second}}{{$t("lunganewstart")}}<text>{{number1!=0?$t("lung.lungsecond"):number2!=0?$t("lung.lungthird"):$t("lung.lungfirst")}}</text>
			</view>
		</view>
		<!-- 开始测量 -->
		<view class="weight" v-else>
			<view class="title cgreen">{{$t("lung.lungExplain2")}}</view>
			<view class="box1">
				<view class="time">{{$t("lung.lungsuctionspeed")}}<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>{{$t("lung.averagelungsuction")}}
				</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: "", //流速
				macAddr: "",
				serviceId: "",
				deviceId: "",
				Unload: false,
				notify: "",
				write: "",
				second: 5, //倒计时
				standard: "", //标准
				offset: 0, //
				listS: [],
			}
		},
		computed: {
			...mapState(["user", "isConnected", "isBluetoothTyle", "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
			if (!that.Unload) {
				clearTimeout(myTime)
				that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
				console.log("页面返回onUnload")
			}
		},
		onLoad(options) {
			let that = this
			if (options && options.deviceId) {
				that.deviceId = options.deviceId
				that.openBluetoothAdapter()
			}
			that.openBluetoothAdapter()
			that.onBLEConnectionStateChange()
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
		},
		watch: {
			isConnected: function() {
				let that = this
				if (!that.isConnected) {
					that.handleBack()
				}
			},
			isBluetoothTyle: function() {
				let that = this
				if (!that.isBluetoothTyle) {
					that.handleBack()
				}
			},
			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
				console.log("结束测量", that.isEnd)
				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: {
			// 重新连接
			openBluetoothAdapter() {
				let that = this
				cnt = 0
				count = 0;
				lastValue = null;
				that.isEnd = false
				that.text = 0
				that.number1 = 0
				that.number2 = 0
				that.number3 = 0
				that.level1 = ""
				that.level2 = ""
				that.level3 = ""
				that.average = "" //平均
				that.LiuS = "" //流速
				that.second = 5 //倒计时
				that.standard = "" //标准
				that.offset = 0 //
				uni.openBluetoothAdapter({
					success: e => {
						console.log("初始化设备")
						that.startBluetoothDeviceDiscovery()
					},
					fail: e => {
						that.$tools.msg(that.$t("linkBluetooth.onDeviceBluetoothTips"))
					}
				});
			},
			// 开始搜寻附近的蓝牙外围设备
			startBluetoothDeviceDiscovery() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: res => {
						console.log("开始搜索")
						that.onBluetoothDeviceFound();
					},
					fail: res => {
						that.$tools.msg(that.$t("linkBluetooth.onDeviceBluetoothTips"))
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				var that = this;
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						if (device.name.indexOf('Yihejia_Lung') != -1) {
							clearTimeout(myTime);
							device.macAddr = device.deviceId
							if (device.deviceId.indexOf(that.deviceId) != -1) {
								that.stopBluetoothDevicesDiscovery()
								that.createBLEConnection()
								console.log("that.deviceId", that.deviceId, device.deviceId)
								return;
							}
						}
					})
				});
				that.handleMyTime()
			},
			// 连接蓝牙
			createBLEConnection() {
				let that = this;
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						that.countdown()
						setTimeout(function() {
							that.getBLEDeviceServices()
						}, 1500)
					},
					fail: res => {
						console.log("设备连接失败，请重新连接", res);
					}
				});
			},
			/**
			 * 获取设备的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();
								console.log("设备的FFE0的serviceId： " + that.serviceId);
								break;
							}
						}
					},
					fail: res => {
						console.log('获取设备的UUID失败:', res)
					}
				});
			},
			/**
			 * 获取指定服务的特征值
			 */
			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);
					},
				})
			},
			handleMyTime() {
				var that = this;
				myTime = setTimeout(function() {
					if (!that.macAddr) {
						clearTimeout(myTime);
						that.Unload = true
						that.startBluetoothDeviceDiscovery()
						that.closeBluetoothAdapter()
					}
				}, 30000);
			},
			// 等级
			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)
			},

			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log("停止搜索蓝牙设备", e)
					},
				});
			},
			// 监听蓝牙连接状态
			onBLEConnectionStateChange() {
				let that = this
				uni.onBLEConnectionStateChange(function(res) {
					console.log("监听蓝牙连接状态", res.connected)
					if (!res.connected) {
						clearTimeout(myTime);
						that.Unload = true
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
					}
					that.$store.commit("changeConnected", res.connected);
				})
			},
			// 保存测量结果
			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')
						})
					}
					that.Unload = true
					setTimeout(function() {
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
						uni.switchTab({
							url: "/pages/home/home"
						})
					}, 200)
				})
			},
			//
			handleBack(ind) {
				let that = this
				that.text = ""
				that.Unload = true
				that.stopBluetoothDevicesDiscovery()
				that.closeBluetoothAdapter()
				that.closeBLEConnection()
				if (ind == 1) {
					uni.switchTab({
						url: "/pages/home/home"
					})
				}
			},
			// 5秒倒计时
			countdown() {
				let that = this
				count = 0
				lastValue = null
				var timer = setInterval(function() {
					that.second--;
				}, 1000);
				setTimeout(() => {
					clearInterval(timer)
					that.second = 0
				}, 5000)
			},
			/**
			 * 断开蓝牙模块
			 */
			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">
	@import "./scss/PCV02.scss";

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