<template>
	<view class="content skipping">
		<!--  -->
		<view class="skiptop">
			<view class="status" @click="handleisSdevice()">
				<text>{{bleTipsText}}</text>
				<image v-if="islink!=2" :class="[islink==1?'':'icon_link']" src="../../static/zhuan.png"></image>
				<image v-if="islink==2" src="../../static/dui.png"></image>
			</view>
			<view class="item">
				<view class="item-ite">今日个数<text>{{info?info.today_jump_num:'--'}}</text></view>
				<view class="item-ite">今日时长<text>{{info?info.today_jump_time:'--'}}</text></view>
				<view class="item-ite">卡路里/kcal<text>{{info?info.today_jump_kcal:'--'}}</text></view>
			</view>
		</view>
		<!--  -->
		<view class="tabbar">
			<view @click="active=1" :class="[active==1?'active':'']">自由跳</view>
			<view @click="active=3" :class="[active==3?'active':'']">倒计数</view>
			<view @click="active=2" :class="[active==2?'active':'']">倒计时</view>
		</view>
		<!--自由训练  -->
		<view class="box1 box" v-if="active==1">
			<view class="item">
				<text class="item-set item-set0">自由</text>
				<text class="tips">无限制</text>
			</view>
			<view :class="[islink==2?'start':'start Nstart']" @click="handleStart(1)">开始</view>
		</view>
		<!--定时训练  -->
		<view class="box1 box" v-if="active==2">
			<view class="item">
				<view class="item-set">
					<text @click="handleTimeEdit('减')">－</text>
					<text>{{time_m}}:{{time_s}}</text>
					<text @click="handleTimeEdit('加')">＋</text>
				</view>
				<view class="tips">
					<picker mode="multiSelector" :range="timeList" :value="timesTndex" @change="bindTimeChange">
						<view>调整目标</view>
					</picker>
				</view>
			</view>
			<view :class="[isConnection?'start':'start Nstart']" @click="handleStart(2)">开始</view>
		</view>
		<!--定数训练  -->
		<view class="box1 box" v-if="active==3">
			<view class="item">
				<view class="item-set">
					<text @click="handleWeightEdit('减')">－</text>
					<text v-if="!disabled">{{weight>50?weight:50}}</text>
					<input type="number" v-model="weight" focus="true" v-else @blur="disabled=false">
					<text @click="handleWeightEdit('加')">＋</text>
				</view>
				<text class="tips" @click="disabled=true">调整目标</text>
			</view>
			<view :class="[isConnection?'start':'start Nstart']" @click="handleStart(3)">开始</view>
		</view>
		<!--  -->
	</view>
</template>

<script>
	let myTime;
	import {
		mapState
	} from "vuex";
	export default {
		data() {
			return {
				active: 1,
				weight: 50,
				disabled: false,
				isDevice: 0,
				time_m: "",
				time_s: "",
				timeList: [],
				timesTndex: [1, 0],
				deviceId: "",
				serviceId: "",
				write: "",
				notify: "",
			}
		},
		computed: {
			...mapState(['user', "MeasureSkip", "bleValue"]),
			info() {
				return this.MeasureSkip
			},
			bleTipsText() {
				return this.bleValue.bleTipsText
			},
			isConnection() {
				return this.bleValue.isBluetoothTyle
			},
			islink() {
				return this.bleValue.isConnectStatus
			}
		},
		mounted() {
			let that = this
			that.timeList = that.$tools.gethms()
			that.time_m = that.timeList[0][1].substring(0, 2)
			that.time_s = that.timeList[1][0].substring(0, 2)
		},
		onLoad(options) {
			let that = this
			that.deviceId = options.deviceId
			that.$store.dispatch("getSkipResult", {
				aud_id: that.user.aud_id
			})
			that.$ble.onBLEConnectionStateChange()
		},
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000);
		},
		onShow() {
			let that = this
			// 跳绳页返回
			uni.$on('updateData', function(info) {
				let data = JSON.parse(info)
				that.isDevice = data.device
				that.active = data.active
				that.deviceId = data.deviceId
				that.serviceId = data.serviceId
				that.write = data.write
				that.notify = data.notify
				that.notifyBLECharacteristicValue()
				if (data.isSuccessful) {
					that.$store.dispatch("getSkipResult", {
						aud_id: that.user.aud_id
					})
				}
				that.$ble.onBLEConnectionStateChange()
				console.log('监听到事件来自 updateData', data);
			})
		},
		onUnload: function() {
			let that = this
			clearTimeout(myTime);
			that.$ble.closeBLEConnection()
			that.$ble.closeBluetoothAdapter()
			uni.$off("updateData")
			console.log("返回首页onUnload")
		},
		watch: {
			bleValue: {
				handler(newVal, oldVal) {
					let that = this
					if (newVal.serviceId) {
						that.deviceId = newVal.deviceId
						that.serviceId = newVal.serviceId
						that.getBLEDeviceCharacteristics()
					}
					if (!newVal.isBluetoothTyle) {
						that.$store.commit("changeBluetoothValue", {
							bleTipsText: "连接失败，点击重新连接",
							isConnectStatus: 1,
						})
					}
				},
				deep: true,
				immediate: true
			},
		},
		methods: {
			// 初始化蓝牙
			handleisSdevice() {
				let that = this
				if (that.islink == 2) return
				that.$store.commit('changeBluetoothValue', {
					bleTipsText: "蓝牙搜索中",
					isConnectStatus: 0,
					isBleLink: false,
					deviceId: "",
					serviceId: "",
				})
				that.$ble.openBluetoothAdapter()
			},


			/**
			 * 获取指定服务的特征值
			 */
			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('0000FF12') != -1) {
								that.write = item.uuid

							} else if (item.uuid.indexOf('0000FFE4') != -1) {
								that.notify = item.uuid
							}
						}
						setTimeout(function() {
							let j = Number(165 + 10 + 1 + 8 + 8 + 8 + 8 + 8 + 8).toString(16)
							let str = "A50A01080808080808" + j.substr(j.length - 2, 2)
							that.SendData(str)
						}, 300)
						// 体重
						setTimeout(function() {
							that.handleStart(4)
						}, 600)
						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,
						})
						that.notifyBLECharacteristicValue()
					},
					fail: res => {
						console.log('获取特征值失败:', JSON.stringify(res))
					}
				})
			},
			notifyBLECharacteristicValue() {
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.notify,
					success(res) {
						that.$store.commit('changeBluetoothValue', {
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							foodNotify: that.notify,
							foodWrite: that.write,
							bleTipsText: "连接成功",
							isConnectStatus: 2
						})
						uni.onBLECharacteristicValueChange(function(res) {
							let value = that.$tools.ab2hex(res.value, "");
							if (value == '5a05090169') { //模式设置成功
								let info = {
									active: that.active,
									deviceId: that.deviceId,
									serviceId: that.serviceId,
									notify: that.notify,
									write: that.write,
									isDevice: that.isDevice,
									isSuccessful: false
								}
								setTimeout(function() {
									uni.$off("updateData")
									uni.navigateTo({
										url: "/pageTwo/devices/PCT01?info=" + JSON.stringify(info)
									})
								}, 200)
							}
							console.log("value", value, that.active)
						})
					}
				})
			},
			// 开启蓝牙主动上报模式
			SendData(str) {
				let that = this
				let buf = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				}))
				console.log("xiafa", str)
				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);
					},
				})
			},
			// 模式切换
			handleStart(ind) {
				let that = this
				let m = null
				let send = null
				if (!that.bleValue.isBluetoothTyle) {
					that.$tools.msg("请先连接设备！")
					return
				}
				if (ind == 1) { // 1自由
					m = Number(165 + 8 + 9).toString(16)
					send = "A5080900000000" + m.substr(m.length - 2, 2)
				}
				if (ind == 2) { //2定时
					let time = Number(that.time_m) * 60 + Number(that.time_s)
					m = Number(165 + 8 + 9 + time).toString(16)
					send = "A508090000" + that.$tools.toHex(time, 4) + m.substr(m.length - 2, 2)
				}
				if (ind == 3) { //3定数
					let weight = that.$tools.toHex(that.weight, 4)
					m = Number(165 + 8 + 9 + that.weight).toString(16)
					send = "A50809" + weight + "0000" + m.substr(m.length - 2, 2)
				}
				if (ind == 4) { //体重

					let weight = Number(that.user.weight) * 2
					let num = parseInt(weight).toString();
					m = Number(165 + 5 + 8 + Number(num)).toString(16)
					send = "A50508" + Number(num).toString(16) + m.substr(m.length - 2, 2)
				}
				that.SendData(send)
				that.$ble.stopBluetoothDevicesDiscovery()
			},
			// 定时训练
			//
			bindTimeChange(e) {
				let that = this
				let m = e.target.value[0]
				let s = e.target.value[1]
				that.timesTndex = e.target.value
				let time_m = Number(that.timeList[0][m].substring(0, 2)) * 60
				let time_s = Number(that.timeList[1][s].substring(0, 2))
				if (Number(time_m + time_s) < 30) {
					that.time_m = '00'
					that.time_s = '30'
				} else {
					that.time_m = that.timeList[0][m].substring(0, 2)
					that.time_s = that.timeList[1][s].substring(0, 2)
				}
			},
			handleTimeEdit(text) {
				let that = this
				let time_m = Number(that.time_m) * 60
				let time_s = Number(that.time_s)
				let minutes = null
				let seconds = null

				if (Number(time_m + time_s) >= 3570 && text == '加') {
					that.time_m = '59'
					that.time_s = '59'
					return
				}
				if (Number(time_m + time_s) <= 30 && text == '减') {
					that.time_m = '00'
					that.time_s = '30'
					return
				}
				if (text == '减') {
					minutes = Math.floor((Number(time_m + time_s - 30) % 3600) / 60)
					seconds = Number(time_m + time_s - 30) % 60
				}
				if (text == '加') {
					minutes = Math.floor((Number(time_m + time_s + 30) % 3600) / 60)
					seconds = Number(time_m + time_s + 30) % 60
				}
				that.time_m = minutes > 9 ? minutes : '0' + minutes;
				that.time_s = seconds > 9 ? seconds : '0' + seconds;
				that.timesTndex = [Number(that.time_m), Number(that.time_s)]
			},
			handleWeightEdit(text) {
				let that = this
				if (text == '减') {
					that.weight = Number(that.weight) - 50 > 50 ? Number(that.weight) - 50 : 50
				}
				if (text == '加') {
					that.weight = Number(that.weight) + 50
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		min-height: 100vh;
		background-color: #F5F6FA;
	}

	.skiptop {
		width: calc(100% - 40px);
		margin-top: 15px;

	}

	.tabbar {
		width: 100%;
		margin-top: 20px;
		margin-bottom: 20px;
		display: flex;
		align-items: center;
		justify-content: space-around;

		view {
			position: relative;
		}

		.active:after {
			content: "";
			height: 3px;
			width: 100%;
			position: absolute;
			bottom: -8px;
			left: 0;
			border-radius: 5px;
			background: $maincolor;
		}
	}

	.box1 {
		background-color: #fff;
		padding: 10px !important;
		color: #999;
		margin: 15px;
		border-radius: 10px;
		width: calc(100% - 40px);

		.time {
			width: 100%;
			font-size: 32rpx;
			margin-bottom: 20px;
		}

		.item {
			width: 100%;
			color: #333;
			font-size: 44rpx;
			text-align: center;
			margin-bottom: 15px;

			text {
				display: block;
			}

			.item-ite {
				font-size: 36rpx;
				margin-bottom: 15px;
				width: 100%;

			}

			.item-set {
				width: calc(100% - 30px);
				display: flex;
				align-items: center;
				height: 55px;
				line-height: 55px;
				font-size: 60rpx;
				margin-bottom: 5px;
				background-color: #f7f7f7;
				padding: 0 15px;
				justify-content: space-between;
				margin: auto;
				position: relative;

				/deep/input {
					font-size: 60rpx;
					height: 55px;
					line-height: 55px;
				}
			}

			.item-set0 {
				background-color: #fff;
				justify-content: center
			}

			.tips {
				font-size: 32rpx;
				color: #999;
				margin-top: 10px;
			}
		}

		.start {
			color: #fff;
			width: 100px;
			height: 100px;
			font-size: 36rpx;
			font-weight: bold;
			line-height: 100px;
			text-align: center;
			border-radius: 50%;
			background: $textcolor;
			margin: 15px auto;
		}

		.Nstart {
			opacity: 0.5 !important;
		}
	}

	.status {
		background-color: #fff;

		image {
			width: 18px;
			height: 18px;
		}

		.icon_link {
			animation: rotation 0.6s infinite linear;
		}

		@keyframes rotation {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}
	}
</style>