<template>
	<view class="app">
		<view class="uptext">
			<view class="pressured">
				收缩压
			</view>
			<input placeholder="请输入数值" border="bottom" v-model="sbp" fontSize='50rpx' inputAlign='center'></input>
			<view class="text">
				mmHg
			</view>
		</view>
		<view class="uptext">
			<view class="pressureg">
				舒张压
			</view>
			<input placeholder="请输入数值" border="bottom" v-model="dbp" fontSize='50rpx' inputAlign='center'></input>
			<view class="text">
				mmHg
			</view>
		</view>
		<view class="uptext">
			<view class="heart">
				心率
			</view>
			<input placeholder="请输入数值" border="bottom" v-model="hr" fontSize='50rpx' inputAlign='center'></input>
			<view class="text">
				次/分钟
			</view>
		</view>
		<view class="time">
			<view style="display: flex;align-items: center;">
				<text style="margin-left: 50rpx">记录时间：</text>
				<view style="display: flex;margin: 0 auto; color: #999;">
					<uni-datetime-picker v-model="measureTime" @change="timeconfirm">{{measureTime}}
						<image style="margin-right: 40rpx;" src="../../static/huijiantou.png" mode="widthFix" />
					</uni-datetime-picker>
				</view>
			</view>
		</view>
		<!-- <view class="submit" @tap="submit">
			保存
		</view> -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		savebp,
		recordlastV2,
		bound,
	} from '@/api/examinationapi/add.js'
	import {
		dzsocketurl,
		dysocketurl
	} from '@/api/socketurl.js'
	export default {
		data() {
			return {
				dbp: '',
				sbp: '',
				hr: '',
				timetext: this.formatDate(Date.now()),
				measureTime: this.formatDate(Date.now()),
				uploadType: undefined,
				timeoutObj: null,
				socketOpen: false,
				SOCKETURL: '',
			};
		},
		onLoad(options) {
			this.info();
			// bound(uni.getStorageSync('userinfo').cardNo).then(res => {
			// 	if (res.code == 200) {
			// 		res.data.forEach(e => {
			// 			if (Number(e.deviceType) == 1) {
			// 				if (uni.getStorageSync('region') == 1) {
			// 					this.SOCKETURL = dzsocketurl + `${e.sn}`
			// 				} else if (uni.getStorageSync('region') == 2) {
			// 					this.SOCKETURL = dysocketurl + `${e.sn}`
			// 				}
			// 				this.scoket();
			// 			}
			// 		})
			// 	}
			// })
		},
		methods: {
			info() {
				recordlastV2(uni.getStorageSync('userinfo').cardNo).then(res => {
					if (res.data && res.data.length > 0) {
						res.data.forEach(e => {
							if (e.type == '2') {
								this.measureTime = e.date
								this.sbp = e.val.split('/')[1]
								this.dbp = e.val.split('/')[0]
							}
							if (e.type == '6') {
								this.hr = e.val
							}
						})
					}
				})
			},
			formatDate(timestamp) {
				const now = new Date(parseInt(timestamp))
				const year = now.getFullYear();
				const month = now.getMonth() + 1;
				const date = now.getDate();
				const hour = now.getHours();
				const minute = now.getMinutes();
				const second = now.getSeconds();
				return year + "-" + ((month < 10) ? '0' + month : month) + "-" + ((date < 10) ? '0' + date : date) + " " +
					((hour < 10) ? '0' + hour : hour) + ":" + ((minute < 10) ? '0' + minute : minute) + ":" + ((second <
						10) ? '0' + second : second);
			},
			timeconfirm(time) {
				this.timetext = time
			},
			scoket() {
				const that = this
				this.socketOpen = false
				try {
					uni.connectSocket({
						url: that.SOCKETURL
					})
					uni.onSocketOpen(res => {
						console.log('webScoket连接已打开', res);
						that.socketOpen = true
						that.reset()
					})

					uni.onSocketError(err => {
						console.log('webScoket连接打开失败', err);
						if (err && err.code != 1000) {
							setTimeout(() => {
								that.socketOpen = true
								uni.connectSocket({
									url: that.SOCKETURL
								})
							}, 3 * 1000)
						}
					})

					uni.onSocketClose(err => {
						console.log('webScoket连接关闭', err);
						if (err && err.code !== 1000) {
							setTimeout(() => {
								that.socketOpen = true
								uni.connectSocket({
									url: that.SOCKETURL
								})
							}, 3 * 1000)
						}
					})
					uni.onSocketMessage(res => {
						let resdata = JSON.parse(res.data)
						let message = JSON.parse(resdata.message)
						console.log("webScoket监听收到的信息", resdata, message);
						this.uploadType = 2
						this.dbp = message.dbp
						this.sbp = message.sbp
						this.hr = message.pulse
						this.$forceUpdate()
					})
				} catch (e) {
					console.log(e);
				}
			},
			// 心跳响应
			reset() {
				let that = this
				clearInterval(that.timeoutObj);
				that.timeoutObj = setInterval(() => {
					uni.sendSocketMessage({
						data: 'ping',
						success(res) {
							console.log('正在发送心跳');
						},
						fail(err) {
							console.log('心跳发送失败，重新连接...');
							console.log(this.SOCKETURL)
							that.socketOpen = true
							uni.connectSocket({
								url: this.SOCKETURL
							})
						}
					})
				}, 3000)
			},
			submit() {
				if (this.ruls(this.dbp) && this.ruls(this.sbp) && this.ruls(this.hr)) {
					let data = {
						dbp: this.dbp,
						sbp: this.sbp,
						hr: this.hr,
						identity: uni.getStorageSync('userinfo').cardNo,
						measureTime: this.timetext,
						uploadType: this.uploadType ? this.uploadType : 1,
					}
					savebp(data).then(res => {
						if (res.code == 200) {
							this.$refs.uToast.show({
								title: '保存成功',
								type: 'success',
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 1000)
						}
					})
				} else {
					this.$refs.uToast.show({
						title: '各项格式为正整数，请重新输入',
						type: 'error',
					})
				}
			},
			ruls(num) {
				let reg = /^((?!0)\d{1,9})$/;
				if (!num.match(reg)) {
					return false
				} else {
					return true
				}
			},
		},
		onUnload() {
			if (this.socketOpen) {
				uni.closeSocket();
			}
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.app {
		.submit {
			width: 60%;
			height: 98rpx;
			margin: 60rpx auto;
			background-color: #4AC4AB;
			border-radius: 10rpx;
			border: solid 0rpx #0c0c0c;
			color: #ffffff;
			text-align: center;
			line-height: 98rpx;
		}

		.time {
			margin-top: 100rpx;
			position: relative;
			border-bottom: 1rpx solid #f0f1f6;
			height: 80rpx;
			line-height: 65rpx;

			image {
				width: 20rpx;
				height: 20rpx;
				position: absolute;
				right: 10rpx;
				top: 20%;
			}

			// text:nth-child(1) {
			// 	margin-left: 50rpx;
			// }

			text:nth-child(2) {
				float: right;
				margin-right: 100rpx;
				color: #999999;
				font-size: 28rpx;
			}
		}

		.uptext:nth-child(3) {
			margin-top: 80rpx;
		}

		.uptext:nth-child(2) {
			margin-top: 80rpx;
		}

		.uptext:nth-child(1) {
			margin-top: 40rpx;
		}

		.uptext {
			width: 100%;
			height: 300rpx;
			position: relative;
			border-bottom: 1rpx solid #f0f1f6;

			.pressured {
				margin-left: 20rpx;
				font-size: 32rpx;
				line-height: 34rpx;
				letter-spacing: 2rpx;
				color: #d34141;
			}

			.pressureg {
				margin-left: 20rpx;
				font-size: 32rpx;
				line-height: 34rpx;
				letter-spacing: 2rpx;
				color: #41d36d;
			}

			.heart {
				margin-left: 20rpx;
				font-size: 32rpx;
				line-height: 34rpx;
				letter-spacing: 2rpx;
				color: #00aaff;
			}

			.text {
				position: absolute;
				top: 75%;
				width: 20%;
				text-align: center;
				left: 40%;
				font-size: 30rpx;
				line-height: 34rpx;
				letter-spacing: 1rpx;
				color: #999999;
			}

			/deep/ input {
				text-align: center;
				font-size: 40rpx;
				border-bottom: 2rpx solid #f0f1f6;
				position: absolute;
				width: 40%;
				height: 10%;
				top: 50%;
				left: 30%;
			}
		}
	}
</style>