<template>
	<view class="web-view">
		<!-- :src="url" src = 'http://192.168.0.108:7456/build/index.html' -->
		<!-- @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"

	var currentWebview;
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		computed: mapState(['avatarUrl', 'gender', 'userName', 'city', 'BLEConnectDevice']),
		data() {
			return {
				url: '',
				pagefinish: '',
				error: '',
				canGoBack: false,
				canGoForward: false,
				PageStart: false, // 记录网页请求的加载状态，true 加载成功 false 加载失败
			}
		},
		onLoad(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)
					});

			}

			// #ifdef APP-PLUS
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			currentWebview = page.$getAppWebview();
			// #endif

			// 监听事件    
			uni.$on('callbackCloseBLE', this.callbackCloseBLE);
			uni.$on('callbackBLEState', this.callbackBLEState);
			uni.$on('updateBLEDeviceData', this.callback);
			
		},
		onUnload() {
			uni.$off('callbackCloseBLE', this.callbackCloseBLE);
			uni.$off('callbackBLEState', this.callbackBLEState);
			uni.$off('updateBLEDeviceData', this.callback);
		},
		methods: {
			...mapMutations([ 'addlocalCalorie']),
			navBack() {
				uni.navigateBack();
			},
			//蓝牙断开连接时候
			callbackCloseBLE() {
				this.sendMessage("onDeviceClose", {
					msg: '设备断开连接。'
				});
			},
			//蓝牙状态回调
			callbackBLEState(res) {
				// console.log("game callbackBLEState==", res);
				// 暂时只返回数据连接错误信息
				// uni.$emit("callbackBLEState", {
				// 	state: -1,
				// 	msg: "设备数据错误"
				// });
				this.sendMessage("onDeviceState", res)
			},
			callback(data) {
				// 设备回调后面用这个接口
				this.sendMessage("onDeviceUpdateData", data);
			},
			/**
			 * 图片转化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() {
				if (!this.PageStart) {
					uni.showModal({
						title: "暴躁的提示",
						content: "只有网页加载成功了才可以传参过去，不然无效哦。。"
					})
					return false;
				}

				this.urlToBase64(this.avatarUrl, (toBase64Url) => {
					let device = null;
					if (this.BLEConnectDevice) {
						device = {
							cname: this.BLEConnectDevice.cname,
							ename: this.BLEConnectDevice.ename,
							name: this.BLEConnectDevice.name
						}

					}
					/**
					 * 卡路里消耗参数
					 */
					
					let calorieParams ={
						runUnit:10,
						jumpUnit:20
					};
					
					// console.log(this.BLEConnectDevice, device);
					let gameData = {
						avatarUrl: this.avatarUrl,
						avatarBase64Url: toBase64Url,
						userName: this.userName,
						gender: this.gender,
						caloriUnit: 10,
						calorieParams:calorieParams,
						//蓝牙连接的设备
						device: device
					}
					this.sendMessage("onGameInit", gameData);
				})


			},
			/**
			 * 统一发送信息
			 * @param {Object} gameData
			 */
			sendMessage(functionName, gameData) {
				let data = {
					"funName": functionName,
					"gameData": gameData
				}
				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];
				if (temp.funName == "uploadInfo") {
					//TODO 后续游戏数据处理
					this.sendMessage("onUploadInfo", {});

					let gameData = temp.gameData;
					//TODO:写入排行榜分数,后面需要在游戏完结里面调用
					//TODO: 后面游戏时间,卡路里的需要写入数据库,目前只是处理了分数
					// let num = Math.round(Math.random() * 10000);
					//1. gameScore 处理上传的分数
					reqUtil.requestData(config.URL.UPLOADRANKING, {
						gameId: this.decodeItem.gameId,
						score: gameData.gameScore,
						cityCode: this.city.cityCode,
					}, "POST").then(res => {
							console.log('UPLOADRANKING =====', res);
							if (res.code == 0) {}

						},
						e => {
							console.log(e)
						});
					//2. calorieBurned 处理卡路里
					// 记录卡路里到本地
					this.addlocalCalorie(gameData.calorieBurned);
					
					//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 gameData = temp.gameData;
					let fruitIndexArray = [0, 0, 0];
					if (temp.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"){
					let gameData = temp.gameData;
					if(gameData.url){
						this.urlToBase64(gameData.url, (toBase64Url) => {
							this.sendMessage("onUrlToBase64", {
								base64: toBase64Url,
							});
						})
					}else{
						this.sendMessage("onUrlToBase64", {
							base64: {},
						});
					}
					
				}
			},
			goBack: function() {
				// 返回
				var webview = weex.requireModule('webview');
				webview.goBack(this.$refs.webview);
			},
			goForward: function() {
				//前进
				var webview = weex.requireModule('webview');
				webview.goForward(this.$refs.webview);
			},

			onPageStart: function(e) {
				// 监听页面加载成功
				this.PageStart = true;
				console.log("onPageStart==", e);
			},
			onPageFinish: function(e) {
				//clearHistory
				// currentWebview.clear();
				console.log("onPageFinish==", e);
				// if (e.url)
				// 	this.pagefinish = e.url;
				// if (e.canGoBack)
				// 	this.canGoBack = e.canGoBack;
				// if (e.canGoForward)
				// 	this.canGoForward = e.canGoForward;
				// var tn = currentWebview.getStyle().titleNView;
				// tn.titleText = e.detail.title || '郁野科技游戏';
				// currentWebview.setStyle({
				// 	titleNView: tn
				// });

			},
			onError: function(e) {
				// 监听页面加载错误
				// this.error = this.url;
				console.error(e);
			},
			onReceivedTitle: function(e) {
				// if (e.title) {
				// 	var tn = currentWebview.getStyle().titleNView;
				// 	tn.titleText = e.detail.title || '郁野科技游戏';
				// 	currentWebview.setStyle({
				// 		titleNView: tn
				// 	});
				// }
			},
			reloadWebviewUrl() {
				// 刷新网页
				var webview = weex.requireModule('webview');
				webview.reload(this.$refs.webview);
			}
		}
	}
</script>

<style>
	/* #ifdef APP-PLUS */
	.web-view {
		flex: 1;
		flex-direction: column;
		border-style:solid;
		border-width: 1rpx;
	}

	.web-view-child {
		width: 750rpx;
		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: 20px;
		right: 20px;
		width: 140rpx;
		height: 60rpx;
		border-radius: 45px;
		/* border: 0.5rpx solid #FFFFFF; */
		box-shadow: 0px 0px 1px #FFFFFF;
		background-color: rgba(0, 0, 0, 0.3);

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

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