<template>
	<view class="content skipping">
		<!--  -->
		<view class="skiptop">
			<view class="status" @click="handleisSdevice()">
				<text>{{islink==0?"正在连接":islink==1?'连接成功':'重新连接'}}</text>
				<image v-if="islink!=1" :class="[islink==-1?'':'icon_link']" src="../../static/zhuan.png"></image>
				<image v-if="islink==1" 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==1?'start':'start Nstart']" @click="handleStart(1)">开始</view>
			<!-- <view class="item">
				<text class="item-ite">本次时长</text>
				<text class="bold">{{info?info.last_jump_time:'0'}}</text>
			</view>
			<view class="item">
				<text class="item-ite">消耗卡路里</text>
				<text class="bold">{{info?info.last_jump_kcal:'0'}}</text>
			</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 class="item">
				<text class="item-ite">本次个数</text>
				<text></text>
			</view>
			<view class="item">
				<text class="item-ite">消耗卡路里</text>
				<text></text>
			</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 class="item">
				<text class="item-ite">本次时长</text>
				<text>0</text>
			</view>
			<view class="item">
				<text class="item-ite">消耗卡路里</text>
				<text>0</text>
			</view> -->
		</view>
		<!--  -->
		<view class="gridList">
			<view class="data">
				<view class="item" @click="navTo('/pages/skiping/charts')">
					<view class="image">
						<image src="@/static/charts.png"></image>
					</view>
					<view class="name">运动曲线</view>
				</view>
				<view class="item" @click="navTo('/pageTwo/history/history?acd_id='+acd_id)">
					<view class="image">
						<image src="@/static/add.png"></image>
					</view>
					<view class="name">历史记录</view>
				</view>
				<view class="item" @click="navTo('/pageTwo/compk/contrast?acd_id='+acd_id)">
					<view class="image">
						<image src="@/static/pk.png"></image>
					</view>
					<view class="name">数据对比</view>
				</view>
				<view class="item" @click="$store.commit('changeRecord',true)">
					<view class="image">
						<image src="@/static/history.png"></image>
					</view>
					<view class="name">添加记录</view>
				</view>
			</view>
		</view>
		<!-- 手动记录 -->
		<record :rtype="acd_id"></record>
	</view>
</template>

<script>
	let myTime;
	import {
		mapState
	} from "vuex";
	import record from '@/element/manuallyAdd/record.vue';
	export default {
		data() {
			return {
				active: 1,
				acd_id: 6,
				weight: 50,
				disabled: false,
				isDevice: 0,
				isConnection: false,
				time_m: "",
				time_s: "",
				timeList: [],
				timesTndex: [1, 0],
				deviceId: "",
				serviceId: "",
				write: "",
				notify: "",
				islink: 0 //0连接中，1成功，-1失败
			}
		},
		components: {
			record
		},
		computed: {
			...mapState(['user', "MeasureSkip", "isConnected", "isBluetoothTyle", "devicesList"]),
			info() {
				return this.MeasureSkip
			},
		},
		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
			console.log('options', options)
			// 首页进入
			if (options && options.acd_id) {
				that.acd_id = options.acd_id
				that.isDevice = options.device
				setTimeout(function() {
					that.handleisSdevice()
				}, 1000)
			}
			that.$store.dispatch("getSkipResult", {
				aud_id: uni.getStorageSync('userid')
			})
			that.isConnection = that.isConnected
			that.$Bluetooth.onBLEConnectionStateChange()
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
		},
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000);
		},
		onShow() {
			let that = this
			// 跳绳页返回
			uni.$on('updateData', function(info) {
				let data = JSON.parse(info)
				that.acd_id = data.acd_id
				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.islink = !that.isConnected ? -1 : 1
				that.isConnection = that.isConnected
				that.notifyBLECharacteristicValue()
				if (data.isSuccessful) {
					that.$store.dispatch("getSkipResult", {
						aud_id: uni.getStorageSync('userid')
					})
				}
				that.$Bluetooth.onBLEConnectionStateChange()
				uni.onBluetoothAdapterStateChange(function(res) {
					that.$store.commit("changeBluetooth", res.available);
				})
				console.log('监听到事件来自 updateData', data);
			})
		},
		onUnload: function() {
			let that = this
			clearTimeout(myTime);
			that.islink = -1
			that.isConnection = false
			that.$Bluetooth.closeBluetoothAdapter()
			that.$Bluetooth.closeBLEConnection(that.deviceId)
			that.$Bluetooth.stopBluetoothDevicesDiscovery()
			that.$store.commit("changeBluetooth", false);
			that.$store.commit("changeConnected", false);
			uni.$off("updateData")
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/home/home'
				})
			}, 300)
			console.log("返回首页onUnload")
		},
		watch: {
			devicesList() {
				let that = this
				if (that.devicesList.length) {
					clearTimeout(myTime);
					that.$Bluetooth.stopBluetoothDevicesDiscovery()
					that.deviceId = that.devicesList[0].deviceId
					that.createBLEConnection()
				}
				console.log("devicesList", that.devicesList)
			},
			isConnected() {
				let that = this
				if (!that.isConnected) {
					that.islink = -1
				}
				that.isConnection = that.isConnected
				console.log("蓝牙是否连接", that.isConnected)
			},
			isBluetoothTyle() {
				let that = this
				if (!that.isBluetoothTyle) {
					that.isConnection = false
					that.islink = -1
				}
				console.log("蓝牙是否打开", that.isBluetoothTyle)
			}
		},
		methods: {
			handleisSdevice() {
				let that = this
				if (that.isConnected) return
				// if (Number(that.isDevice) != 0) {
				that.$Bluetooth.stopBluetoothDevicesDiscovery()
				uni.openBluetoothAdapter({
					success: e => {
						that.islink = 0
						that.handleMyTime()
						that.$store.commit("changedevicesList", []);
						that.$store.commit("changeBluetooth", true)
						that.$Bluetooth.startBluetoothDeviceDiscovery()
						console.log('初始化蓝牙成功:' + e.errMsg);
					},
					fail: e => {
						that.islink = -1
						that.$Bluetooth.getBluetoothAdapter(e)
					}
				});
				// } else {
				// 	that.islink = -1
				// 	that.$tools.msg("请先添加设备！")
				// 	that.$Bluetooth.stopBluetoothDevicesDiscovery()
				// 	setTimeout(function() {
				// 		uni.switchTab({
				// 			url: "/pageTwo/business/business"
				// 		})
				// 	}, 500)
				// }
			},
			// 设备排查
			handleDevType(device) {
				let that = this
				console.log("device123", device)
				that.$model.getdevdetail({
					mac: device.macAddr,
					acd_id: that.acd_id
				}).then(res => {
					console.log("排查返回", res)
					if (res.code == 0) {
						that.deviceId = device.deviceId
						that.createBLEConnection()
					}
				})
			},
			// 连接蓝牙
			createBLEConnection() {
				let that = this;
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						setTimeout(function() {
							uni.hideLoading()
							that.islink = 1
							that.isConnection = true
							that.getBLEDeviceServices()
						}, 1000)
					},
					fail: res => {
						console.log("设备连接失败，请重新连接", res, that.deviceId);
					}
				});
			},
			/**
			 * 获取设备的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)
						that.islink = -1
						clearTimeout(myTime);
						that.isConnection = false
					}
				});
			},

			/**
			 * 获取指定服务的特征值
			 */
			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) {
						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,
									acd_id: that.acd_id,
									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.isConnected) {
					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.$Bluetooth.stopBluetoothDevicesDiscovery()
			},
			// 历史数据删除时重新加载接口
			reload() {
				let that = this
				this.$nextTick(() => {
					that.$store.dispatch("getSkipResult", {
						aud_id: uni.getStorageSync('userid')
					})
				})
			},
			// 定时训练
			//
			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
				}
			},
			// 蓝牙搜索记时
			handleMyTime() {
				let that = this
				myTime = setTimeout(function() {
					if (!that.devicesList.length) {
						that.islink = -1
						that.$tools.showModal("没有查找到设备")
					}
					clearTimeout(myTime)
					that.$Bluetooth.stopBluetoothDevicesDiscovery()
				}, 20000);
			},
			navTo(url) {
				let that = this
				if (!that.isConnected) {
					that.islink = -1
					clearTimeout(myTime)
					that.$Bluetooth.closeBluetoothAdapter()
					that.$Bluetooth.closeBLEConnection(that.deviceId)
					that.$Bluetooth.stopBluetoothDevicesDiscovery()
					console.log("蓝牙没有连接")
				}
				uni.navigateTo({
					url: url
				})
			},

		}
	}
</script>

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

	.skiptop {
		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%- 30px);

		.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>