<template>
	<view>
		<uni-nav-bar id="nav-bar" status-bar="true" @clickLeft="onBack()" title="校准设备方向" color="#000000" fixed="true"
			:border="false" @clickRight="onResetCalibration()">
			<view slot="left">
				<view class=" flex align-center margin-left">
					<image class="p-left-arrow" src="../../../static/p-left-arrow.png"></image>
				</view>
			</view>
			<view slot="right">
				<button class="cu-btn make-bg-bPurple text-white margin-top margin-bottom text-11px">重置</button>
			</view>

		</uni-nav-bar>
		<view class="flex justify-center align-center" style="height: 200rpx;">
			<view v-if="currentBLEData">
				<view>加速计 acc: x:{{currentBLEData.acc.ax.toFixed(4)}} y:{{currentBLEData.acc.ay.toFixed(4)}}
					z:{{currentBLEData.acc.az.toFixed(4)}}
				</view>
				<view v-if="outBLEData">校准后 acc: x:{{outBLEData.acc.ax.toFixed(4)}} y:{{outBLEData.acc.ay.toFixed(4)}}
					z:{{outBLEData.acc.az.toFixed(4)}}
				</view>

				<view>陀螺仪 gyro: x:{{currentBLEData.gyro.gx.toFixed(4)}} y:{{currentBLEData.gyro.gy.toFixed(4)}}
					z:{{currentBLEData.gyro.gz.toFixed(4)}}
				</view>
				<view v-if="outBLEData">校准后 gyro: y:{{outBLEData.gyro.gy.toFixed(4)}}
				</view>

			</view>
		</view>
		<!-- 任务栏 -->
		<scroll-view scroll-y="true" style="height: 500px; max-height: 600px;min-height: 230rpx;margin-top: 10rpx;"
			:scroll-into-view="taskIntoView" :scroll-top="taskScrollTop">
			<view class="my-column-cu-steps">
				<view class="cu-item" :class="!item.isUnlock?'':'make-text-bPurple'"
					v-for="(item,index) in currentTaskList" :key="index" :id='"task_"+index'>
					<image v-if="item.isUnlock" class="my-column-cu-image"
						src="../../../static/common/modal/unLock.png"></image>
					<image v-else-if="index>=1&&currentTaskList[index-1].isUnlock&&currentTaskList[index-1].isPassed"
						class="my-column-cu-image" src="../../../static/common/modal/canUnlock.png">
					</image>
					<image v-else class="my-column-cu-image" src="../../../static/common/modal/lock.png">
					</image>
					<view class="content" style="height: 130px;">
						<view class="text-15px text-bold text-cut text-left "
							style="margin-left: 48rpx; width: 360rpx;">
							{{index+1}}. {{item.name}}
						</view>

						<view class="text-13px text-grey text-left" style="margin: 20rpx 20rpx 0 86rpx;">
							{{item.explain}}
						</view>

						<button v-if="item.isAcc" :disabled="!(currentJumpTask!=null&&index==currentJumpTask.index)"
							class="cu-btn make-bg-bPurple text-white margin-top margin-bottom"
							@click="onCalibration(index,item)">确认</button>
						<button v-else :disabled="!(currentJumpTask!=null&&index==currentJumpTask.index)"
							class="cu-btn make-bg-bPurple text-white margin-top margin-bottom"
							@click="onCalibrationGyro(index,item)">开始</button>
					</view>

					<image class="my-column-cu-image" style="left: 130rpx;top: 40rpx; width: 50rpx;height: 50rpx;"
						:src="(currentJumpTask!=null&&index==currentJumpTask.index)?'/static/devicesOther/radio-b.png':'/static/devicesOther/radio-g.png'"
						mode="aspectFit"></image>

				</view>
			</view>
		</scroll-view>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				taskIntoView: '',
				taskScrollTop: 0,
				currentJumpTask: {
					index: 0
				},
				currentTaskList: [{
						name: 'y轴-设备垂直方向',
						isUnlock: false,
						isPassed: false,
						explain: '设备垂直桌面静止后，点击确认按钮',
						isAcc: true
					},
					{
						name: 'z轴-设备方向键方向',
						isUnlock: false,
						isPassed: false,
						explain: '设备方向键向上静止于桌面后，点击确认按钮',
						isAcc: true
					},
					{
						name: 'x轴-侧边按钮方向',
						isUnlock: false,
						isPassed: false,
						explain: '侧边按钮垂直向上静止后，点击确认按钮',
						isAcc: true
					},
					{
						name: 'y轴-左旋转',
						isUnlock: false,
						isPassed: false,
						explain: '垂直桌面方向进行绕Y轴左旋转，点击确认按钮',
						isAcc: false
					}
				],
				currentBLEData: null,
				outBLEData: null,

				currentGyroXArray: [],
				currentGyroYArray: [],
				currentGyroZArray: [],
				bMatchGyro: false,

				currentInterval: null
			}
		},
		onLoad() {
			//测试socket
			console.log('test*******************************');
			// this.$testWS.connectSocket(() => {
			// 	this.$testWS.sendSocketMessage('unity');
			// });

			//监听蓝牙回调
			uni.$on('callbackCloseBLE', this.callbackCloseBLE);
			uni.$on('updateBLEDeviceData', this.callbackUpdateBLEData);

			// #ifndef APP-PLUS
			this.currentInterval = setInterval(() => {
				this.callbackUpdateBLEData({
					acc: {
						ax: Math.random() * 2,
						ay: Math.random() * 2,
						az: Math.random() * 2
					},
					gyro: {
						gx: Math.random(),
						gy: Math.random(),
						gz: Math.random()
					}
				})
			}, 100);
			// #endif
			// #ifdef APP-PLUS
			//打开加速计
			this.onWriteBLEConnectionValue({
				value: "3"
			});
			// #endif




		},
		onUnload() {
			//*****注释蓝牙操作******
			uni.$off('callbackCloseBLE', this.callbackCloseBLE);
			uni.$off('updateBLEDeviceData', this.callbackUpdateBLEData);
			// #ifdef APP-PLUS
			//打开加速计
			this.onWriteBLEConnectionValue({
				value: "4"
			});
			// #endif

		},
		computed: mapState(['convertAcc', 'convertGyro']),
		methods: {
			...mapMutations(['onWriteBLEConnectionValue', 'onAccAndGyroConvertDataReset', 'onConvertDeviceData','onAccAndGyroConvertDataSave']),
			onBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			/**
			 * 蓝牙断开连接时候
			 */
			callbackCloseBLE() {
				console.log('callbackCloseBLE');
			},
			//设备回调事件
			callbackUpdateBLEData(data) {
				//如果在监听状态时候隐藏页面，返回
				this.currentBLEData = data;

				//如果开始校准旋转方向
				if (this.bMatchGyro) {
					this.onUpdateGyroData();
				}

				//模拟数据转化
				this.onConvertDeviceData({
					data: this.currentBLEData,
					callback: (outData) => {
						this.outBLEData = {
							acc: outData.convertAcc,
							gyro: outData.convertGyro
						}
					}
				});

			},
			updateTaskScroll() {
				if (this.currentJumpTask != null) {
					let _index = this.currentJumpTask.index - 1 < 0 ? 0 : this.currentJumpTask.index - 1;
					this.$nextTick(() => {
						this.taskIntoView = "task_" + _index;
					});
					this.taskIntoView = '' //不清空再次跳到锚点位置会不起作用
				}

			},
			onResetCalibration() {
				this.currentJumpTask.index = 0;
				for (let i = 0; i < this.currentTaskList.length; i++) {
					this.currentTaskList[i].isUnlock = false;
				}

				this.onAccAndGyroConvertDataReset();

				if (this.currentInterval) {
					clearInterval(this.currentInterval)
					this.currentInterval = null;
				}

			},
			onCalibration(index, item) {
				console.log(index, JSON.stringify(item));
				item.isUnlock = true;
				this.currentJumpTask.index = index + 1;
				//这里处理校准设备方向处理,convertAcc 是一个 x，y，z 数组
				if (0 === index) {
					//校准y轴方向
					//获取匹配当前接近1的数据，三个轴同时匹配
					let {
						name,
						value
					} = this.onMatchAccData();
					this.$store.state.convertAcc[1].match = name;
					this.$store.state.convertAcc[1].direction = value > 0 ? 1 : -1;
				} else if (1 === index) {
					//校准z轴方向
					let {
						name,
						value
					} = this.onMatchAccData();
					this.$store.state.convertAcc[2].match = name;
					this.$store.state.convertAcc[2].direction = value > 0 ? 1 : -1;
				} else if (2 === index) {
					//校准x轴方向
					let {
						name,
						value
					} = this.onMatchAccData();
					this.$store.state.convertAcc[0].match = name;
					this.$store.state.convertAcc[0].direction = value > 0 ? 1 : -1;
				}
				this.updateTaskScroll();
			},
			onCalibrationGyro(index, item) {
				item.isUnlock = true;
				this.currentJumpTask.index = index + 1;
				if (3 === index) {
					//校准y轴旋转方向-左旋转
					this.onStartMatchGyro();
					uni.showToast({
						title: '校准中',
						icon: 'loading',
						mask: true,
						duration: 2000
					})
				}
				this.updateTaskScroll();
			},
			onStartMatchGyro() {
				this.currentGyroValue = 0;
				this.bMatchGyro = true;
				this.currentGyroXArray = [];
				this.currentGyroYArray = [];
				this.currentGyroZArray = [];
			},
			onMatchAccData() {
				let _data = {
					name: 'none',
					value: 0
				}
				// console.log(JSON.stringify(this.currentBLEData));
				//返回一个大于0.9的数据的轴
				if (Math.abs(this.currentBLEData.acc.ax) > 0.6) {
					_data.name = 'ax'
					_data.value = this.currentBLEData.acc.ax;
					return _data;
				}
				if (Math.abs(this.currentBLEData.acc.ay) > 0.6) {
					_data.name = 'ay'
					_data.value = this.currentBLEData.acc.ay;
					return _data;
				}
				if (Math.abs(this.currentBLEData.acc.az) > 0.6) {
					_data.name = 'az'
					_data.value = this.currentBLEData.acc.az;
					return _data;
				}
				// console.log(_data);
				return _data;
			},
			onUpdateGyroData() {
				let _temp = 50;
				if (Math.abs(this.currentBLEData.gyro.gx) < _temp &&
					Math.abs(this.currentBLEData.gyro.gy) < _temp &&
					Math.abs(this.currentBLEData.gyro.gz) < _temp)
					return;

				//这里不确定是哪个轴，
				this.currentGyroXArray.push(this.currentBLEData.gyro.gx);
				this.currentGyroYArray.push(this.currentBLEData.gyro.gy);
				this.currentGyroZArray.push(this.currentBLEData.gyro.gz);

				//取到10个数，停止。
				if (this.currentGyroXArray.length > 20) {
					this.bMatchGyro = false;
					//判断左旋时候，确定当前轴的值
					let _data = {
						name: 'none',
						value: 0
					}
					let currentGyroXValue = 0,
						currentGyroYValue = 0,
						currentGyroZValue = 0,
						currentMaxGyro = 0;
					for (let i = 0; i < this.currentGyroXArray.length; i++) {
						currentGyroXValue += this.currentGyroXArray[i];
						currentGyroYValue += this.currentGyroYArray[i];
						currentGyroZValue += this.currentGyroZArray[i];
					}


					if (Math.abs(currentGyroXValue) > Math.abs(currentGyroYValue)) {
						_data.name = 'gx';
						_data.value = currentGyroXValue;
						currentMaxGyro = currentGyroXValue;
					} else {
						_data.name = 'gy';
						_data.value = currentGyroYValue;
						currentMaxGyro = currentGyroYValue;
					}

					if (Math.abs(currentGyroZValue) > Math.abs(currentMaxGyro)) {
						_data.name = 'gz';
						_data.value = currentGyroZValue;
						currentMaxGyro = currentGyroZValue;
					}
					//定y为旋转轴，即 convertGyro 下标 1
					this.$store.state.convertGyro[1].match = _data.name;
					//以左旋转为校准轴,如果当前左旋值大于0.即设置direction -1;
					this.$store.state.convertGyro[1].direction = _data.value > 0 ? -1 : 1;
					
					console.log('convertGyro=',JSON.stringify(_data))
					uni.showToast({
						title: '校准完成'
					})
					
					this.onAccAndGyroConvertDataSave();
				}
			}
		}
	}
</script>

<style>

</style>
