<template>
	<view class="web-view">
		<!-- :src="url" src = 'http://192.168.0.112:7456/build/index.html' :src="LocationGameUrl" -->
		<!-- @receivedtitle="onReceivedTitle"   @pagefinish="onPageFinish"-->
		<web-view class="web-view-child" :src="url" ref="webview" @pagestart="onPageStart" @onPostMessage="handlePostMessage"
		 @error="onError"></web-view>
		<view class="web-back" @click="navBack">
			<image style="width: 40rpx;height: 40rpx;" src="/static/gameCloseW.png"></image>
		</view>
	</view>



</template>

<script>
	import reqUtil from "@/util/util-js/requstUtil.js";
	import config from "@/common/config.js";
	import fruit from "@/components/fruitMachine/fruit.js"


	// import AccAndOri from "@/util/util-js/AccAndOri.js"
	import puchConfig from "@/util/util-js/puchConfig.js"

	import EquipmentAction from "@/util/util-js/EquipmentAction.js"


	var currentWebview;
	var orientId = null,
		accId = null;

	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		computed: mapState([
			'avatarUrl', 'gender', 'userName', 'city', 'BLEConnectDevice', 'instructionState', 'currentInstruction',
			'cIndex', 'globalAcc', 'globalOri', 'LocationGameUrl',
			'ConnectBindingDevice',
			'currentModeIndex'
		]),
		data() {
			return {
				url: '',
				pagefinish: '',
				error: '',
				PageStart: false, // 记录网页请求的加载状态，true 加载成功 false 加载失败
				gameQuitListener: false, //游戏是否初始化退出监听

				xA: 0,
				yA: 0,
				zA: 0,
				oldxA: 0,
				oldzA: 0,
				bUpdateOnce: false,
				bDelayOnce: false,
				mass: puchConfig.BOXING_MASS,

				//X轴的变化数组值
				xAccArray: [],
				xMax: 0,
				maxTimeoutId: null,
				bMaxPause: false,
				xMin: 0,
				minTimeoutId: null,
				bMinPause: false,
				bCalculation: false,
				calTimeout: null,

				//角度比 z/x
				angleRatio: 1, //

				//当前选择的item
				decodeItem: null,

				//拳击数据判断对象
				EquipmentActionObj: null,

				BLENum: 0,
				BLEACX: 0,
				BLEACYL: 0,

				//是否是游戏里面开启的监听，如果是的话，退出游戏界面时候需要关闭相应的监听，如加速计和陀螺仪
				bGameOpenListen: false,
				//手机陀螺仪和加速计android模块
				bMyAttitudeListen:false,
			}
		},
		onLoad() {
			let _self = this;

			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			currentWebview = page.$getAppWebview();

			//监听一次调用setOnceGameOption

			console.log("子组件初始化");
			uni.$once("setOnceGameOption", (option) => {
				console.log("setOnceGameOption=", option);
				if (option && option.item) {
					this.decodeItem = JSON.parse(decodeURIComponent(option.item));
					this.url = this.decodeItem.gameWebUrl;
					let temp = {
						fObjectId: this.decodeItem.gameId,
						recentlyType: 0
					}
					// console.log("game temp:", config.URL.RECENTLYPLAYINGADD);
					//添加最近在玩的游戏
					reqUtil.requestData(config.URL.RECENTLYPLAYINGADD, temp).then(res => {
							console.log('RECENTLYPLAYINGADD =====', res);
							if (res.code == 0) {}

						},
						e => {
							console.log(e)
						});

				}
			});
			//子窗体onload 后获取父窗体的onload数据
			uni.$emit("game-load");

			uni.getCurrentSubNVue().addEventListener("hide", function() {
				console.log("subNVue子窗体已隐藏！");
				//通知游戏，页面退出
				_self.sendMessage("onSubHide", {
					msg: '退出页面'
				});
				uni.$off('updateBLEDeviceData', _self.BLECallback);
				//json
				uni.$off('updateBLEDeviceJson', _self.BLEJsonCallback);
				
				//去掉监听
				if(_self.bMyAttitudeListen){
					_self.gStopSimulateBLEUpdate();
				}
				
				// console.log(_self.BLEConnectDevice);
				//如果连接了蓝牙设备是手柄
				if (_self.BLEConnectDevice && _self.BLEConnectDevice.deviceType == "BLEHandle") {
					//开启设备回调 3/4关闭
					_self.onWriteBLEConnectionValue({
						value: "4"
					});
					//关闭json 回调
					_self.onWriteBLEConnectionValue({
						value: "6"
					});
				
					uni.$off('updateBLEDeviceData', _self.gWatchBLEUpdate);
				}//关闭跳绳模式指令
				else if (_self.BLEConnectDevice && _self.BLEConnectDevice.deviceType == "BLERope") {
					console.warn("还没设置关闭跳绳模式")
					_self.B_CloseRopeSkipping();
					uni.$off('updateBLEDeviceData', _self.gWatchBLEUpdate);
				}
				uni.$emit("game-unload", {
					globalAcc: _self.globalAcc,
					globalOri: _self.globalOri,
					bGameOpenListen: _self.bGameOpenListen
				});
				
				
			});
			//*****注释蓝牙操作******
			// 监听事件    
			// uni.$on('callbackCloseBLE', this.callbackCloseBLE);
			// uni.$on('callbackBLEState', this.callbackBLEState);
			// uni.$on('updateBLEDeviceData', this.BLECallback);

			//监听物理返回按钮
			plus.key.addEventListener('backbutton', () => {
				this.navBack();
			}, false);
			
			//设置store状态
			_self.$store.state.bGamePlaying = true;
		},
		onUnload() {
			this.$store.state.bGamePlaying = false;
			console.log("subNVue子窗体 onUnload！");
			//*****注释蓝牙操作******
			// uni.$off('callbackCloseBLE', this.callbackCloseBLE);
			// uni.$off('callbackBLEState', this.callbackBLEState);
			//取消相应的绑定事件
			uni.$off('watchAcceleration', this.gWatchAcceleration);
			uni.$off("watchAcceleration", this.gWatchBoxingAcc);
			uni.$off("watchAcceleration", this.gWatchHitBoxingAcc);
			uni.$off('watchOrientation', this.gWatchOrientation);

			uni.$emit("game-unload");
		},
		methods: {
			...mapMutations(['addlocalCalorie', 'syncRequestEvent', 'onWriteBLEConnectionValue',
				'gCreateFilterObj', 'gUpdateFilter' ,'B_OpenRopeSkipping','B_CloseRopeSkipping',
				'gStopSimulateBLEUpdate','gStartSimulateBLEUpdate','gUpdateSandbagAlgorithm','gCreateSandbagAlgorithm'
			]),
			navBack() {


				this.sendMessage("onQuit", {
					type: "right-button",
					msg: '点击右上角按钮退出游戏'
				});

				uni.showModal({
					title: '提示',
					content: '是否退出游戏？',
					success: (res) => {
						//如果游戏需要监听退出，则需要走完游戏端流程，才能退出，否则直接退出
						if (this.gameQuitListener) {
							this.sendMessage("onQuitModal", {
								data: res,
								msg: '退出提示'
							});
						} else {
							if (res.confirm) {
								uni.getCurrentSubNVue().hide('auto');
							}
						}
					}
				})

			},
			//蓝牙断开连接时候
			callbackCloseBLE() {
				this.sendMessage("onDeviceClose", {
					msg: '设备断开连接。'
				});
			},
			//蓝牙状态回调
			callbackBLEState(res) {
				// console.log("game callbackBLEState==", res);
				// 暂时只返回数据连接错误信息
				// uni.$emit("callbackBLEState", {
				// 	state: -1,
				// 	msg: "设备数据错误"
				// });
				this.sendMessage("onDeviceState", res)
			},
			BLECallback(data) {
				let dataType = 'Box';
				// if (data.hasOwnProperty("ax")) {
				// 	dataType = "Accelerometer"
				// }else if(data.hasOwnProperty("gx")){
				// 	dataType = "Gyroscope"
				// }
				// 设备回调后面用这个接口
				let BLEState = {
					device: this.BLEConnectDevice, //连接的蓝牙设备
					instructionState: this.instructionState, //开启的指令状态
					currentInstruction: this.currentInstruction, //当前发送的指令记录
					dataType: dataType, //回调的数据类型
					data: data //蓝牙回调的数据
				}
				this.sendMessage("onDeviceUpdateData", BLEState);
			},
			BLEJsonCallback(data) {
				let dataType = 'Json';
				// 设备回调后面用这个接口
				let BLEState = {
					device: this.BLEConnectDevice, //连接的蓝牙设备
					instructionState: this.instructionState, //开启的指令状态
					currentInstruction: this.currentInstruction, //当前发送的指令记录
					dataType: dataType, //回调的数据类型
					data: data //蓝牙回调的数据
				}
				this.sendMessage("onDeviceUpdateJson", BLEState);
			},
			/**
			 * 图片转化base64
			 * @param {Object} url
			 * @param {Object} callback
			 */
			urlToBase64(url, callback) {
				let toBase64Url;
				uni.request({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer',
					success: async res => {
						let base64 = uni.arrayBufferToBase64(res.data);
						toBase64Url = 'data:image/jpeg;base64,' + base64;
						if (callback)
							callback(toBase64Url, res.data);
					}
				})
			},
			/**
			 * 初始化发送数据给游戏
			 */
			sendGameInit() {

				this.urlToBase64(this.avatarUrl, (toBase64Url) => {
					let device = null;
					/**
					 * 卡路里消耗参数
					 */
					let calorieParams = null;

					if (this.BLEConnectDevice) {
						// device = {
						// 	cname: this.BLEConnectDevice.cname,
						// 	ename: this.BLEConnectDevice.ename,
						// 	name: this.BLEConnectDevice.name
						// };
						// calorieParams = {
						// 	runUnit: 0.55, // 比跳的稍微大一点
						// 	jumpUnit: 0.5 // 跳的次数 * 0.5
						// };
						device = {
							cname: this.BLEConnectDevice.cname,
							ename: this.BLEConnectDevice.ename,
							name: this.BLEConnectDevice.name
						};

						calorieParams = {
							hitUnit: puchConfig.getBoxingCalorie(1)
						};

					} else if (this.ConnectBindingDevice) {
						device = {
							cname: this.ConnectBindingDevice.cname,
							ename: this.ConnectBindingDevice.ename,
							name: this.ConnectBindingDevice.name
						};

						calorieParams = {
							hitUnit: puchConfig.getBoxingCalorie(1)
						};
					}
					//到时候可能要区分是什么类型
					let item = {
						id: this.decodeItem.gameId,
						name: this.decodeItem.gameName
					};

					// console.log(this.BLEConnectDevice, device);
					let gameData = {
						avatarUrl: this.avatarUrl,
						avatarBase64Url: toBase64Url,
						userName: this.userName,
						gender: this.gender,
						caloriUnit: 10,
						calorieParams: calorieParams,
						//蓝牙连接的设备
						device: device,
						item: item
					}

					this.sendMessage("onGameInit", gameData);
					// console.log("onGameInit =", gameData);
				})


			},
			/**
			 * 统一发送信息
			 * @param {Object} gameData
			 */
			sendMessage(functionName, gameData) {
				let data = {
					"funName": functionName,
					"gameData": gameData
				}
				if (!this.PageStart) {
					console.warn("页面未初始化不能传消息", data);
					return;
				}
				let initStr = JSON.stringify(data);
				this.$refs.webview.evalJs("onWebViewMessage(" + initStr + ")");
			},
			sendMessageToWebview() {
				if (!this.PageStart) {
					uni.showModal({
						title: "暴躁的提示",
						content: "只有网页加载成功了才可以传参过去，不然无效哦。。"
					})
					return false;
				}
				/**
				 * 下面的 jsfunction 代码你要自己在你的网页里面写一个方法 大致如下
				 *  下面就是你基本的html知识了，我就不想说什么了，自己学。
					window.jsfunction = function(data){
						console.log('data', data);
					}
				 */
				this.sendMessage("onDeviceUpdateData", {
					H: 1
				});

			},
			handlePostMessage: function(postData) {
				console.log("handlePostMessage得到参数", postData.detail);
				let temp = postData.detail.data[0];
				let gameData = temp.gameData;
				if (temp.funName == "uploadInfo") {

					//TODO:写入排行榜分数,后面需要在游戏完结里面调用
					//TODO: 后面游戏时间,卡路里的需要写入数据库,目前只是处理了分数
					// let num = Math.round(Math.random() * 10000);
					//1. gameScore 处理上传的分数
					// let _temp = {
					// 	gameId: '1595755153789139696',
					// 	score: 1230,
					// 	cityCode: '110101',
					// };

					//2. calorieBurned 处理卡路里
					// 记录卡路里到本地
					this.addlocalCalorie(gameData.calorieBurned);
					console.log("gameData.calorieBurned", gameData.calorieBurned);
					//然后更新上服务器
					this.syncRequestEvent({
						success: () => {
							// uni.$emit('updateArcbarData', '');

							let _temp = {
								//假如排行id 为空，排行榜就是游戏自己的id
								gameId: this.decodeItem.gameRankingId == null ? this.decodeItem.gameId : this.decodeItem.gameRankingId,
								score: gameData.gameScore,
								cityCode: this.city.cityCode,
								bMaxLimit: true
							}
							console.log('_temp =====', _temp);
							reqUtil.requestData(config.URL.UPLOADRANKING, _temp, "POST").then(res => {
									console.log('UPLOADRANKING =====', res);
									if (res.code == 0) {
										//TODO 后续游戏数据处理
										this.sendMessage("onUploadInfo", {
											code: 0,
											msg: '上传成功'
										});
									} else {
										//TODO 后续游戏数据处理
										this.sendMessage("onUploadInfo", {
											code: 400,
											msg: '上传失败'
										});
									}

								},
								e => {
									console.log(e)
								});
						},
						fail: () => {
							this.sendMessage("onUploadInfo", {
								code: 400,
								msg: '上传失败'
							});
						}
					});

					//3. gameTime 游戏时间 
					//TODO 后面处理游戏时长


				} else if (temp.funName == "gameInit") {
					// 获取游戏信息
					this.sendGameInit();
				} else if (temp.funName == "aiRandomInfo") {
					// 获取aiRandomInfo
					reqUtil.requestData(config.URL.AIRANDOMINFO, {}).then(res => {
							console.log('AIRANDOMINFO =====', res);
							if (res.code == 0) {
								let data = res.data;
								this.urlToBase64(data.aiAvatar, (toBase64Url) => {
									let sendData = {
										aiId: data.aiId,
										aiName: data.aiName,
										aiGender: data.aiGender,
										aiType: data.aiType,
										aiAvatarBase64Url: toBase64Url
									}
									this.sendMessage("onAiRandomInfo", sendData);
								})
							}

						},
						e => {
							console.log(e)
						});
				} else if (temp.funName == "fruitInfo") {
					let fruitIndexArray = [0, 0, 0];
					if (gameData.hasOwnProperty("calorie")) {
						fruitIndexArray = fruit.getFruitIndex(gameData.calorie);
					}

					this.urlToBase64("https://bbeng-bucket.oss-cn-beijing.aliyuncs.com/cocos/fruitMachine.png", (toBase64Url) => {
						this.sendMessage("onFruitInfo", {
							// 水果雪碧图
							fruitBase64Url: toBase64Url,
							// 雪碧图 单张图片宽高
							unitWidth: 100,
							unitHeight: 100,
							unit: "px",
							imageStartPosY: 0,
							imageEndPosY: -1200,
							fruitIndexArray: fruitIndexArray
						});
					})



				} else if (temp.funName == "urlToBase64") {
					if (gameData.url) {
						this.urlToBase64(gameData.url, (toBase64Url) => {
							this.sendMessage("onUrlToBase64", {
								base64: toBase64Url,
							});
						})
					} else {
						this.sendMessage("onUrlToBase64", {
							base64: {},
						});
					}

				} else if (temp.funName == "openAccelerometer") {
					//打开加速计s
					// if (this.globalGameAcc) {
					// 	uni.$on('watchAcceleration', this.gWatchAcceleration);
					// } else {
					// 	AccAndOri.bindAcc((accId) => {
					// 		this.$store.state.globalGameAcc = accId;
					// 		console.log("开启的：globalGameAcc=",this.globalGameAcc);
					// 		uni.$on('watchAcceleration', this.gWatchAcceleration);
					// 	});
					// }
					if (this.globalAcc) {
						uni.$on('watchAcceleration', this.gWatchAcceleration);
					} else {
						uni.$emit("bindAcc", {
							callback: (accId) => {
								console.log("开启的：globalAcc=", accId);
								this.bGameOpenListen = true;
								this.$store.state.globalAcc = accId;
								uni.$on('watchAcceleration', this.gWatchAcceleration);
							}
						});
					}


				} else if (temp.funName == "closeAccelerometer") {
					uni.$off('watchAcceleration', this.gWatchAcceleration);
					uni.$emit("unBindAcc", this.globalAcc);
					this.$store.state.globalAcc = null;

				} else if (temp.funName == "openOrientation") {
					//打开陀螺仪
					if (this.globalOri) {
						uni.$on('watchOrientation', this.gWatchOrientation);
					} else {
						// AccAndOri.bindOri((oriId) => {
						// 	this.$store.state.globalOri = oriId;
						// 	uni.$on('watchOrientation', this.gWatchOrientation);
						// });
						uni.$emit("bindOri", {
							callback: (oriId) => {
								console.log("开启的：globalOri=", oriId);
								this.bGameOpenListen = true;
								this.$store.state.globalOri = oriId;
								uni.$on('watchOrientation', this.gWatchOrientation);
							}
						});
					}
				} else if (temp.funName == "closeOrientation") {

					// uni.$off('watchOrientation', this.gWatchOrientation);
					uni.$off('watchOrientation', this.gWatchOrientation);
					uni.$emit("unBindOri", this.globalOri);
					this.$store.state.globalOri = null;

				} else if (temp.funName == "bindBoxingPost") {
					if (this.globalAcc) {
						uni.$on('watchAcceleration', this.gWatchBoxingAcc);
					} else {
						uni.$emit("bindAcc", {
							callback: (accId) => {
								console.log("bindBoxingPost开启的：globalAcc=", accId);
								this.bGameOpenListen = true;
								this.$store.state.globalAcc = accId;
								uni.$on('watchAcceleration', this.gWatchBoxingAcc);
							}
						});
					}
				} else if (temp.funName == "unbindBoxingPost") {

					uni.$off('watchAcceleration', this.gWatchBoxingAcc);
					uni.$emit("unBindAcc", this.globalAcc);
					this.$store.state.globalAcc = null;

				} else if (temp.funName == "setAngleRatio") {
					if (gameData) {
						this.angleRatio = Number(gameData.angleRatio);
						console.log("this.angleRatio:", this.angleRatio);
						this.sendMessage("onSetAngleRatio", {
							angleRatio: this.angleRatio
						});
					}
				} else if (temp.funName == "bindHitBoxingPost") {
					console.log("bindHitBoxingPost");
					
					if(this.ConnectBindingDevice){
						uni.$on('updateBLEDeviceData', this.gWatchBLEUpdate);
						//hotman 沙袋情景
						this.gCreateSandbagAlgorithm();
						this.gStartSimulateBLEUpdate();
						return;
					}
					
					if(!this.BLEConnectDevice)return;
					//用设备来区分,开启什么加速计;
					if (this.BLEConnectDevice.deviceType == "BLEHandle") {
						//处理蓝牙设备情况下
						//开启设备回调 3/4关闭
						this.onWriteBLEConnectionValue({
							value: "3"
						});
						setTimeout(()=>{
							//设置加速计b:20ms a:10ms
							this.onWriteBLEConnectionValue({
								value: config.refreshRate
							});
							
						},2000)
						
						uni.$on('updateBLEDeviceData', this.gWatchBLEUpdate);

						if (this.BLEConnectDevice.usageMode == "phone" || this.BLEConnectDevice.usageMode == "general") {
							//手机情景或者自由模式
							this._createEquipmentBasedOnBoxingPostHit();
						} else if (this.BLEConnectDevice.usageMode == "hotman") {
							//hotman 沙袋情景  
							this.gCreateFilterObj();
						}
					} else if (this.BLEConnectDevice.deviceType == "mySelf") {
						//处理手机本身情况下
						if (this.globalAcc) {
							uni.$on('watchAcceleration', this.gWatchHitBoxingAcc);
						} else {
							//开启手机加速计
							uni.$emit("bindAcc", {
								callback: (accId) => {
									console.log("bindHitBoxingPost开启的：globalAcc=", accId);
									this.bGameOpenListen = true;
									this.$store.state.globalAcc = accId;
									uni.$on('watchAcceleration', this.gWatchHitBoxingAcc);
									if (this.BLEConnectDevice.usageMode == "phone" || this.BLEConnectDevice.usageMode == "general") {
										//手机情景或者自由模式
										this._createEquipmentBasedOnBoxingPostHit();
									} else if (this.BLEConnectDevice.usageMode == "hotman") {
										//hotman 沙袋情景 todo
										console.warn("没有处理手机加速计的 gCreateFilterObj");
										// this.gCreateFilterObj();
									}
								}
							});
						}
					} else if(this.BLEConnectDevice.deviceType == "BLERope"){
						//todo 开启跳绳模式
						this.B_OpenRopeSkipping();
						//监听蓝牙回调
						uni.$on('updateBLEDeviceData', this.gWatchBLEUpdate);
					}


				} else if (temp.funName == "unbindHitBoxingPost") {
					
					if(this.ConnectBindingDevice){
						uni.$off('updateBLEDeviceData', this.gWatchBLEUpdate);
						this.gStopSimulateBLEUpdate();
						return;
					}
					
					if (this.BLEConnectDevice&&this.BLEConnectDevice.deviceType == "BLEHandle") {
						//开启设备回调 3/4关闭
						this.onWriteBLEConnectionValue({
							value: "4"
						});
						uni.$off('updateBLEDeviceData', this.gWatchBLEUpdate);
					}else if (this.BLEConnectDevice && this.BLEConnectDevice.deviceType == "BLERope") {
					 	console.warn("unbindHitBoxingPost 还没设置关闭跳绳模式")
						this.B_CloseRopeSkipping();
						uni.$off('updateBLEDeviceData', this.gWatchBLEUpdate);
					} else {
						uni.$off('watchAcceleration', this.gWatchHitBoxingAcc);
						uni.$emit("unBindAcc", this.globalAcc);
						this.$store.state.globalAcc = null;
					}
				} else if (temp.funName == "closeGame") {
					uni.getCurrentSubNVue().hide('auto');
				} else if (temp.funName == "addQuitModal") {
					this.gameQuitListener = true;
					this.sendMessage("onQuitModalListener", {
						bListener: this.gameQuitListener
					});
				} else if (temp.funName == "removeQuitModal") {
					this.gameQuitListener = false;
					this.sendMessage("onQuitModalListener", {
						bListener: this.gameQuitListener
					});
				} else if (temp.funName == "writeBLEConnectionValue") {
					if (!gameData.value || gameData.value == "") return;
					
					if(!this.BLEConnectDevice)return;
					//蓝牙写入数据
					this.onWriteBLEConnectionValue(gameData);
				} else if (temp.funName == "log") {
					console.log(gameData);
				} else if (temp.funName == "addDeviceUpdateListener") {
					uni.$on('updateBLEDeviceData', this.BLECallback);
				} else if (temp.funName == "closeDeviceUpdateListener") {
					uni.$off('updateBLEDeviceData', this.BLECallback);
				} else if (temp.funName == "addDeviceJsonUpdateListener") {
					uni.$on('updateBLEDeviceJson', this.BLEJsonCallback);
				} else if (temp.funName == "closeDeviceJsonUpdateListener") {
					uni.$off('updateBLEDeviceJson', this.BLEJsonCallback);
				}
				//获取手机原始陀螺仪和加速计数据
				else if(temp.funName == "onStartAccAndGyro"){
					this.bMyAttitudeListen = true;
					this.gStartSimulateBLEUpdate();
					//监听蓝牙回调
					uni.$on('updateBLEDeviceData', this.gWatchBLEUpdate);
				}
				else if(temp.funName == "onStopAccAndGyro"){
					this.bMyAttitudeListen = false;
					this.gStopSimulateBLEUpdate();
					//监听蓝牙回调
					uni.$off('updateBLEDeviceData', this.gWatchBLEUpdate);
				}
			},
			onPageStart: function(e) {
				// 监听页面加载成功
				this.PageStart = true;
				console.log("onPageStart==", e);
				setTimeout(()=>{
					//加载成功后，显示
					uni.getCurrentSubNVue().show('fade-in', 250, () => {});
				},100)
				

			},
			onPageFinish: function(e) {
				console.log("onPageFinish==", e);
			},
			onError: function(e) {
				// 监听页面加载错误
				// this.error = this.url;
				console.error(e);
			},
			gWatchAcceleration: function(a) {
				this.sendMessage("onWatchAccelerometer", a);
				return;
				if (this.ConnectBindingDevice && this.ConnectBindingDevice.deviceType == 1) {
					this.sendMessage("onWatchAccelerometer", a);
				} else if (this.BLEConnectDevice && this.cIndex != -1) {
					this.sendMessage("onWatchAccelerometer", a);
				}
			},
			gWatchOrientation: function(o) {
				this.sendMessage("onWatchOrientation", o);
				return;
				if (this.ConnectBindingDevice && this.ConnectBindingDevice.deviceType == 1) {
					this.sendMessage("onWatchOrientation", o);
				} else if (this.BLEConnectDevice && this.cIndex != -1) {
					this.sendMessage("onWatchOrientation", o);
				}
			},
			//监听返回计算好的puch
			gWatchBoxingAcc: function(a) {
				if (this.ConnectBindingDevice && this.ConnectBindingDevice.deviceType == 1) {
					//计算返回 puch  leftPunch  rightPunch
					this.updateHitData(a);
				} else if (this.BLEConnectDevice && this.cIndex != -1) {
					this.updateHitData(a);
				}
			},
			//只返回一个hit状态
			gWatchHitBoxingAcc: function(a) {
				if (this.ConnectBindingDevice && this.ConnectBindingDevice.deviceType == 1) {
					//计算返回 puch  leftPunch  rightPunch
					this.EquipmentActionObj.updateAcc({
						xA: a.xAxis,
						zA: a.yAxis,
						yA: a.zAxis
					})
				} else if (this.cIndex != -1 && this.BLEConnectDevice != null) {
					if (this.BLEConnectDevice.usageMode == "phone" || this.BLEConnectDevice.usageMode == "general") {
						this.EquipmentActionObj.updateAcc({
							xA: a.xAxis,
							zA: a.yAxis,
							yA: a.zAxis,
							bLimitRebound: false
						})
					} else if (this.BLEConnectDevice.usageMode == "hotman") {
						//hotman 沙袋情景 todo
						//后面处理手机加速计的数据
					}

				}
			},
			gWatchBLEUpdate: function(data) {
				
				//如果是模块外面触发，需要离线打包
				if(this.bMyAttitudeListen){
					this.sendMessage("updateAccAndGyro", data);
					return;
				}
				
				if(this.ConnectBindingDevice){
					//hotman 沙袋情景 todo
					this.gUpdateSandbagAlgorithm({
						data: data,
						callback: (res) => {
							// console.log(res);
							if (res.type == 'hit') {
								// console.log('gUpdateFilter callback:',res)
					
								let temp = {
									direction: res.direction,
									angle:res.angle,
									name: res.name,
									ename: res.ename,
									value: res.hit,
									mass: 10, //质量
									hitPower: res.hit //计算的力
								}
								this.sendMessage("onBoxingPostHit", temp);
							}
						}
					});
					return;
				}
				
				if (this.BLEConnectDevice.usageMode == "phone" || this.BLEConnectDevice.usageMode == "general") {
					//手机情景或者自由模式
					let {
						ax,
						ay,
						az
					} = data.acc;
					//this.BLEConnectDevice.limitType == "rebound"
					//这里是监听 _createEquipmentBasedOnBoxingPostHit 回调
					this.EquipmentActionObj.updateTriaxialAcc({
						xA: ax * 9.80665,
						zA: ay * 9.80665,
						yA: az * 9.80665,
						bLimitRebound: false
					})
				} else if (this.BLEConnectDevice.usageMode == "hotman") {
					//hotman 沙袋情景 todo
					this.gUpdateFilter({
						data: data,
						callback: (res) => {
							// console.log(res);
							if (res.type == 'hit') {
								// console.log('gUpdateFilter callback:',res)

								let temp = {
									direction: res.direction,
									angle:res.angle,
									name: res.name,
									ename: res.ename,
									value: res.hit,
									mass: 10, //质量
									hitPower: res.hit //计算的力
								}
								this.sendMessage("onBoxingPostHit", temp);
							}
						}
					});
				} else if(this.BLEConnectDevice.usageMode == "ropeSkipping"){
					//跳绳模式场景，简单更新触发
					//看看是否反馈一个角度，180 ，360
					let temp = {
						direction: "all",
						angle: 0,
						name: "击中",// this.BLEConnectDevice.name,
						ename: "hit",//this.BLEConnectDevice.ename,
						value: 10,
						mass: 10, //质量
						hitPower: 10 //计算的力
					}
					this.sendMessage("onBoxingPostHit", temp);
				}
			},

			updateHitData(a) {
				this.xA = a.xAxis;
				this.yA = a.yAxis;
				this.zA = a.zAxis;

				if (Math.abs(this.xA) > 8 && this.oldxA != this.xA && !this.bCalculation) {
					this.xAccArray.push(this.xA);
					this.oldxA = this.xA;

					if (this.calTimeout == null) {
						this.calTimeout = setTimeout(() => {
							this.bCalculation = true;
							for (let i = 0; i < this.xAccArray.length; i++) {
								if (this.xAccArray[i] < 0 && this.xAccArray[i] < this.xAccArray[this.xMin]) {
									this.xMin = i;
								} else if (this.xAccArray[i] > 0 && this.xAccArray[i] > this.xAccArray[this.xMax]) {
									this.xMax = i;
								}
							}
							console.log(this.xAccArray, "==", this.xMin, "==", this.xMax);
							if (this.xAccArray[this.xMin] < 0 && this.xAccArray[this.xMax] > 0) {
								if (this.xMin > this.xMax)
									this.onHit("xRCount", "左勾拳", "leftPunch", this.xAccArray[this.xMin], Math.ceil(Math.abs(this.xAccArray[this.xMin]) *
										puchConfig.BOXING_MASS));
								else if (this.xMin < this.xMax)
									this.onHit("xLCount", "右勾拳", "rightPunch", this.xAccArray[this.xMax], Math.ceil(Math.abs(this.xAccArray[this
										.xMax]) * puchConfig.BOXING_MASS));
							} else if (this.xAccArray[this.xMin] < 0) {
								this.onHit("xLCount", "右勾拳", "rightPunch", this.xAccArray[this.xMin], Math.ceil(Math.abs(this.xAccArray[this.xMin]) *
									puchConfig.BOXING_MASS));
							} else if (this.xAccArray[this.xMax] > 0) {
								this.onHit("xRCount", "左勾拳", "leftPunch", this.xAccArray[this.xMax], Math.ceil(Math.abs(this.xAccArray[this.xMax]) *
									puchConfig.BOXING_MASS));
							}
							setTimeout(() => {
								this.onResetCal();
							}, 100);
							this.calTimeout = null;
						}, 200);
					}
				} else if (this.zA < -10 && this.oldzA != this.zA && this.xAccArray.length == 0) {
					console.log("this.zA:", this.zA);
					this.oldzA = this.zA;
					setTimeout(() => {
						this.onResetCal();
					}, 200);
					this.onHit("zLCount", "直拳", "punch", this.zA, Math.ceil(Math.abs(this.zA) * puchConfig.BOXING_MASS));
				}
			},
			onHit(direction, name, ename, direValue, power) {
				// console.log(direction, direValue, power);
				let temp = {
					direction: direction,
					angle: 0,
					name: name,
					ename: ename,
					value: direValue,
					mass: this.mass, //质量
					hitPower: power //计算的力
				}

				this.sendMessage("onBoxingPostHit", temp);
			},
			onResetCal() {
				this.xAccArray = [];
				this.xMax = 0;
				this.xMin = 0;
				this.bCalculation = false;
				this.oldxA = 0;
				this.oldzA = 0;
				this.calTimeout = null;
			},
			//创建一个 打击对象
			_createEquipmentBasedOnBoxingPostHit() {
				this.EquipmentActionObj = new EquipmentAction();
				this.EquipmentActionObj.addEventListener("resultantHit", (e) => {
					console.log(e);
					let temp = {
						direction: "allCount",
						angle: 0,
						name: "击中",
						ename: "hit",
						value: e.acc,
						mass: e.mass, //质量
						hitPower: e.power //计算的力
					}
					this.sendMessage("onBoxingPostHit", temp);
				})
			}
		}
	}
</script>

<style>
	/* #ifdef APP-PLUS */
	.web-view {
		flex: 1;
		flex-direction: column;
		/* background-color: #007AFF; */
	}

	.web-view-child {
		width: 750rpx;
		height: 100%;
		flex: 1;
	}

	/* #endif */
	/* #ifdef H5 */

	.web-view {
		display: flex;
		flex-direction: column;
		position: absolute;
		bottom: 0;
		top: 0;
		left: 0;
		right: 0;
	}

	.web-view-child {
		position: relative;
		width: 100%;
		height: 100%;
	}

	/* #endif */


	.sendMessage {
		width: 300rpx;
		position: fixed;
		bottom: 100rpx;
		left: 50rpx;
	}

	.web-back {
		position: fixed;
		top: 40px;
		right: 20px;
		width: 160rpx;
		height: 80rpx;
		border-radius: 45px;
		/* border: 1px solid #FFFFFF; */
		/* box-shadow: 0px 0px 1px #FFFFFF; */
		background-color: rgba(0, 0, 0, 1);
		opacity: 0.5;

		/* #ifndef APP-PLUS-NVUE */
		z-Index: 10;
		display: flex;
		/* #endif */

		justify-content: center;
		align-items: center;
	}
</style>
