<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="">您好！第<text>{{number1!=""?'二':number2!=''?'三':'一'}}</text>次测试开始</view>
				<view>放下呼吸训练器，缓慢呼气，尽可能排空肺部气体</view>
				<view class="cgreen">使用呼吸训练器，缓慢吸气，直至到达极限</view>
			</view>
			<view class="data" v-if="number3">
				<view class="val">
					<text>1441ml</text>
					平均吸气肺活量
				</view>
				<view class="text">
					根据您的个人信息，您的达标吸气肺活量为2900ml。您本次测试吸气速度23.2L/min，肺活量测试结果1441ml。结合您的身体状态和改善目标，我们将为您生成详细的健康报告。
				</view>
			</view>
			<view class="btn" v-if="number3">查看本次报告</view>
			<view class="btn close" v-if="number3">我想重新测试</view>
			<view class="btn" v-if="number1!=''&&number3==''">
				2S后开始第<text>{{number1!=""?'二':number2!=''?'三':'一'}}</text>次测试</view>
		</view>
		<!--  -->
		<view class="weight" v-else>
			<view class="title cgreen">使用呼吸训练器，缓慢吸气，直至到达极限</view>
			<view class="box1">
				<view class="time">吸气速度 <text class="cgreen ml-5">38.3L/min</text></view>
				<view class="item">
					<view class="image">
						<image src="../../static/bae.png" mode="widthFix"></image>
					</view>
					<view class="center  mt-15">
						<view class="level"></view>
						<view class="level level-bg"></view>
						<view class="level-item" v-if="info">
							<view class="ite" v-for="(ite,ind) in list">{{ite}}</view>
						</view>
					</view>
				</view>
				<view class="val">
					<text>{{average}}ml</text>吸气肺活量
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	let myTime;
	export default {
		data() {
			return {
				isstart: true, //是否开始测量
				number1: "11",
				number2: "22",
				number3: "33",
				level1: "适中",
				level2: "适中",
				level3: "适中",
				average: "11",
				list: [],
				macAddr: "",
				serviceId: "",
				deviceId: "",
				Unload: false,
			}
		},
		computed: {
			...mapState(["user", "isConnected", "isBluetoothTyle"]),
			info() {
				return this.user
			}
		},
		onUnload: function() {
			let that = this
			if (!that.Unload) {
				clearTimeout(myTime)
				that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
				that.closeBluetoothAdapter()
				console.log("页面返回onUnload")
			}
		},
		onLoad(options) {
			let that = this
			if (options && options.deviceId) {
				that.deviceId = options.deviceId
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
				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()
				}
			},
		},
		methods: {
			// 重新连接
			openBluetoothAdapter() {
				let that = this
				that.text = ""
				uni.openBluetoothAdapter({
					success: e => {
						that.startBluetoothDeviceDiscovery()
					},
					fail: e => {
						that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
					}
				});
			},
			// 开始搜寻附近的蓝牙外围设备
			startBluetoothDeviceDiscovery() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: res => {
						that.onBluetoothDeviceFound();
					},
					fail: res => {
						that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				var that = this;
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						if (device.name.indexOf('PC') != -1) {
							console.log("搜索设备", device)
							clearTimeout(myTime);
							let buff = device.advertisData.slice(-6)
							device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
							let tempMac = Array.from(device.mac)
							tempMac.reverse()
							device.macAddr = that.$tools.ab2hex(tempMac, ':').toUpperCase()
							if (device.deviceId.indexOf(that.deviceId) != -1 || device.macAddr.indexOf(that
									.deviceId) != -1) {
								that.stopBluetoothDevicesDiscovery()
								that.macAddr = device.macAddr
								that.deviceId = device.deviceId
								that.createBLEConnection()
								return;
							}
						}
					})
				});
				that.handleMyTime()
			},
			// 连接蓝牙
			createBLEConnection() {
				let that = this;
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						that.getBLEDeviceServices();
					},
					fail: res => {
						console.log("设备连接失败，请重新连接", res);
					}
				});
			},
			/**
			 * 获取设备的UUID
			 */
			getBLEDeviceServices() {
				let serviceList = [];
				let that = this;
				uni.getBLEDeviceServices({
					deviceId: "12:F7:00:08:83:FC",
					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)
						for (let i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i];
							if (item.uuid.indexOf('0000FFE9') != -1) {
								console.log("0000FFE9")
							} else if (item.uuid.indexOf('0000FFE4') != -1) {
								console.log("0000FFE4")
								that.notifyBLECharacteristicValue(item.uuid)
							} else if (item.uuid.indexOf('0000FFE0') != -1) {
								console.log("0000FFE0")
							}
						}
					},
					fail: res => {
						console.log('获取特征值失败:', JSON.stringify(res))
					}
				})
			},
			/**
			 * 开启订阅特征值
			 * read: true, //读,write: true, //写,notify: true, //广播
			 */
			notifyBLECharacteristicValue(uuid) {
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: uuid,
					success(res) {
						uni.onBLECharacteristicValueChange(function(res) {
							let value = that.$tools.ab2hex(res.value, "");
							let num = value.substring(18, 19)
							let dw = value.substring(19, 20)
							let type = value.substring(8, 10)
							let typeInfo = value.substring(10, 12)
							console.log("value", value)
							if (type == "10") {

							}
							if (type == "11") {
								that.type = 2
								if (typeInfo == "03" || typeInfo == "04") {
									that.imp = parseInt(value.substring(17, 22), 16)
								}
								console.log("体脂:", that.imp)
							}
						});
					},
					fail(res) {
						console.log("测量失败", res.value);
					}
				});
			},
			handleMyTime() {
				var that = this;
				myTime = setTimeout(function() {
					if (!that.macAddr) {
						clearTimeout(myTime);
						that.Unload = true
						that.startBluetoothDeviceDiscovery()
						that.closeBluetoothAdapter()
					}
				}, 30000);
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			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.getmeasurefunit({
					imp: that.imp,
					weight: that.weight,
					ecode: that.macAddr,
					height: that.height,
					familyid: that.info.id
				}).then(res => {
					that.isHeight = false
					if (res.code == 0) {
						that.$store.dispatch("getUserInfo", {
							familyid: that.info.id
						});
						that.$tools.msg("测量成功")
					} else {
						that.$tools.msg("测量失败")
					}
					that.Unload = true
					setTimeout(function() {
						that.closeBluetoothAdapter()
						uni.switchTab({
							url: "/pages/index/index"
						})
					}, 200)
				})
			},
			//
			handleBack(ind) {
				let that = this
				that.text = ""
				that.Unload = true
				that.stopBluetoothDevicesDiscovery()
				that.closeBluetoothAdapter()
				if (ind == 1) {
					uni.switchTab({
						url: "/pages/index/index"
					})
				}
			},
			/**
			 * 断开蓝牙模块
			 */
			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">
	.content {
		width: calc(100% - 30px);
		padding: 0 15px;
		min-height: 100vh;
		color: #5d5651;
		background-color: #000;
	}

	.cgreen {
		color: #39D9C9;
	}

	.tips {
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.top {
			width: 100%;
			display: flex;
			margin-top: 20px;
			align-items: flex-start;

			.left {
				font-size: 32px;
				margin-right: 10px;
			}

			.right {
				.text {
					font-size: 12px !important;
				}

				text {
					font-size: 14px;
					display: block;
					width: 100%;
					margin-bottom: 5px;
				}
			}
		}

		.item {
			background-color: #272a2a;
			border-radius: 10px;
			margin-top: 8px;
			color: #fff;
			height: 35px;
			line-height: 35px;
			display: flex;

			text {
				flex-grow: 0;
				display: inline-block;
			}

			.cgreen {
				flex-grow: 2;
				font-size: 16px;
				text-align: center;
			}

			.level {
				color: #516752;
			}
		}

		.title {
			font-size: 18px;
			margin: 20px;


			view {
				width: 100%;
				margin-top: 40px;
				text-align: center;
			}
		}

		.data {
			margin-top: 20px;

			.text {
				font-size: 12px;
				color: #fff;
				line-height: 20px;
			}
		}

		.btn {
			width: 70%;
			color: #fff;
			padding: 5px 15px;
			border-radius: 15px;
			text-align: center;
			background: $maincolor;
			margin: 15px auto;
			position: absolute;
			bottom: 80px;
			left: calc(15% - 15px);
		}

		.close {
			background: #999;
			bottom: 20px;
		}
	}

	.weight {
		padding-top: 30px;

		.title {
			width: 80%;
			margin: auto;
			font-size: 18px;
			text-align: center;
		}
	}

	.box1 {
		color: #fff;
		margin: 50px 15px 15px;
		width: calc(100%- 30px);

		.time {
			width: 60%;
			margin: auto;
			position: relative;
			text-align: center;
			border-radius: 10px;
			background-color: #272a2a;
			height: 30px;
			line-height: 30px;
		}

		.time:after {
			content: "";
			position: absolute;
			left: 45%;
			bottom: -7px;
			width: 0px;
			height: 0px;
			border-left: 5px solid transparent;
			border-right: 5px solid transparent;
			border-top: 8px solid #272a2a;
		}

		.item {
			width: 100%;
			font-size: 14px;
			padding: 10px 0;
			border-radius: 15px;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 15px;
			position: relative;
			margin-top: 10px;

			.image {
				width: 80%;

				image {
					width: 100%;
				}
			}

			.center {
				top: -10px;
				bottom: 20px;
				position: absolute;
				width: 55px;
				margin: auto;
				text-align: center;
				background-color: #333;
				border-radius: 10px;
				z-index: 9;
			}

			.level-bg {
				position: absolute;
				width: 55px;
				margin: auto;
				text-align: center;
				background-color: #4d6c7b;
				border-radius: 0 0 10px 10px;
				bottom: 0px;
				z-index: 19;
			}

			.level-item {
				width: 55px;
				height: 100%;
				position: absolute;
				z-index: 99;

				:last-child {
					border-bottom: none;
				}

			}

			.ite {
				margin: 0 5px;
				width: calc(100% - 10px);
				height: 40px;
				line-height: 40px;
				font-size: 12px;
				color: #fff;
				z-index: 99;
				border-bottom: 1px solid #999;
			}
		}
	}

	.val {
		width: 100%;
		text-align: center;
		margin: 20px 0;
		color: #fff;
		font-size: 14px;

		text {
			display: block;
			color: #39D9C9 !important;
			font-size: 32px;
			margin-bottom: 10px;
		}
	}
</style>