<template>
	<view class="app">
		<view class="uptext">
			<input placeholder="请输入血糖值" border="bottom" v-model="number" fontSize='50rpx' inputAlign='center'>
			</input>
			<view class="text">
				mmol/L
			</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="scene">
			<view class="title">
				测量场景
			</view>
			<view class="choices">
				<view @tap='bucketchoice=1' :class="bucketchoice==1?'choice':'choice2'">凌晨</view>
				<view @tap='bucketchoice=2' :class="bucketchoice==2?'choice':'choice2'">早餐前</view>
				<view @tap='bucketchoice=3' :class="bucketchoice==3?'choice':'choice2'">早晨后</view>
				<view @tap='bucketchoice=4' :class="bucketchoice==4?'choice':'choice2'">午餐前</view>
				<view @tap='bucketchoice=5' :class="bucketchoice==5?'choice':'choice2'">午餐后</view>
				<view @tap='bucketchoice=6' :class="bucketchoice==6?'choice':'choice2'">晚餐前</view>
				<view @tap='bucketchoice=7' :class="bucketchoice==7?'choice':'choice2'">晚餐后</view>
				<view @tap='bucketchoice=8' :class="bucketchoice==8?'choice':'choice2'">睡前2小时</view>
			</view>
		</view>
		<!-- <view class="btn">
			<view class="submit" @tap="submit">
				添加
			</view>
		</view> -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		bound,
		savebg,
		recordlastV2
	} from '@/api/examinationapi/add.js'
	import {
		dzsocketurl,
		dysocketurl
	} from '@/api/socketurl.js'
	export default {
		data() {
			return {
				uploadType: undefined,
				number: '',
				timetext: this.formatDate(Date.now()),
				measureTime: this.formatDate(Date.now()),
				bucketchoice: 1,
				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) == 2) {
			// 				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 == '1') {
								this.bucketchoice = Number(e.bucket)
								this.measureTime = e.date
								this.number = e.val
							}
						})
					}
				})
			},
			timeconfirm(time) {
				this.timetext = time
			},
			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);
			},
			submit() {
				if (!this.number || this.timetext == "请选择时间") {
					this.$refs.uToast.show({
						title: '请填写完整后提交',
						type: 'error',
					})
					return
				}
				let data = {
					bg: this.number,
					bucket: this.bucketchoice,
					measureTime: this.measureTime,
					uploadType: this.uploadType ? this.uploadType : 1,
					identity: uni.getStorageSync('userinfo').cardNo
				}
				savebg(data).then(res => {
					if (res.code == 200) {
						this.$refs.uToast.show({
							title: '保存成功',
							type: 'success',
						})
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							})
						}, 1000)
					}
				})
			},
			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 => {
						this.uploadType = 2
						let resdata = JSON.parse(res.data)
						let message = JSON.parse(resdata.message)
						console.log("webScoket监听收到的信息", resdata, message);
						this.number = message.fbg
						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)
			},
		},
		onUnload() {
			if (this.socketOpen) {
				uni.closeSocket();
			}
		},
	}
</script>

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

	.app {

		.btn {
			position: absolute;
			bottom: 0;
			width: 100%;

			.submit {
				width: 90%;
				height: 80rpx;
				margin: 60rpx auto;
				background-color: #4AC4AB;
				border-radius: 10rpx;
				color: #ffffff;
				text-align: center;
				line-height: 80rpx;
			}
		}

		.scene {
			margin-top: 50rpx;
			width: 100%;

			.choices {
				text-align: center;
				line-height: 60rpx;
				font-size: 28rpx;
				margin-top: 50rpx;
				display: flex;
				flex-wrap: wrap;
				justify-content: space-evenly;

				.choice2 {
					margin: 0 10rpx 30rpx;
					color: #a3a3a3;
					width: 20%;
					height: 60rpx;
					background-color: #ffffff;
					border-radius: 10rpx;
					border: solid 1rpx #ccc;
				}

				.choice {
					margin: 0 10rpx 30rpx;
					width: 20%;
					height: 60rpx;
					background-color: #ffffff;
					border-radius: 10rpx;
					border: solid 1rpx #4AC4AB;
					color: #4AC4AB;
				}
			}


			.title {
				font-size: 34rpx;
				margin-left: 50rpx;
				line-height: 34rpx;
				color: #333333;
			}
		}

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

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

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

		}

		.uptext {
			width: 100%;
			height: 500rpx;
			position: relative;

			.text {
				position: absolute;
				top: 85%;
				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>