<template>
	<view>
		<!--  rgba(116, 172, 240, 1)-->
		<uni-nav-bar id="nav-bar" :status-bar="true" :border="false" @clickLeft="onBack()" @clickRight="onNavConver" title="全部游戏"
		 :fixed="true">
			<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">
				<view class="align-center text-13px" style="width: 130rpx;">
					我的游戏
				</view>
			</view>
		</uni-nav-bar>
		<view class="cu-bar search bg-white">
			<view class="search-form ">
				<text class="cuIcon-search"></text>
				<!-- @focus="InputFocus" @blur="InputBlur" -->
				<input :adjust-position="false" type="text" placeholder="搜索游戏" confirm-type="search"></input>
			</view>

		</view>
		<view class="scrollX">
			<scroll-view scroll-x class="bg-white nav scrollX-padding" scroll-with-animation :scroll-left="scrollLeft">
				<view class="cu-item text-15px" :class="index == TabCur ? 'text-bold black text-22px' : 'cu-color'" v-for="(item, index) in tabList"
				 :key="index" @tap="tabSelect" :data-id="index" :data-category_id="item.categoryType" >
					{{ item.categoryName }}
				</view>
			</scroll-view>
		</view>
		<button @click="getFile">getFile</button>
		<button @click="navGame">game</button>
		<scroll-view scroll-y="true" :style="{ height: scrollviewHigh + 'px' }" @scrolltolower="lower">

			<view class="fc-list">
				<view class="fc-li" v-for="(item, index) in gameList" :key="index" :data-id="index" @tap="onNavToWebviewGame(item)">
					<image mode="aspectFill" class="game-item-image" :src="item.gamePicture"></image>

					<view class="fc-bottom-container">
						<view class="text-center text-white text-bold">{{item.gameName}}</view>
						<view class="text-center text-white">{{item.gamePlayNum}}人在玩</view>
					</view>

					<view v-if="item.bDownload" class="play-bg-download">
						<view class="text-center text-white text-bold">下载中...</view>
						<view class="text-center text-white text-bold margin-sm">{{item.progressVal}}%</view>
					</view>
				</view>
			</view>

			<view v-if="gameList.length == 0" class="text-16px text-gray text-center margin">没有更多数据</view>
			<view style="height: 17px;"></view>
		</scroll-view>
		<!-- https://www.yuyekeji.cn/Cocos/TestDownload -->
		<!-- <view class="web-view">
			<web-view class="web-view-child" src = 'https://www.yuyekeji.cn/Cocos/TestEmulatrix15'></web-view>
		</view> -->

	</view>
</template>

<script>
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
	import sideBar from '@/components/side-bar/side-bar.vue';
	import config from '../../../common/config.js';
	import reqUtil from '../../../util/util-js/requstUtil.js';
	import roundMenu from "@/components/round-menu/round-menu.vue";

	import {
		mapState
	} from 'vuex';

	export default {
		components: {
			uniNavBar,
			sideBar,
			roundMenu
		},
		computed: mapState(['ConnectBindingDevice', 'BLEConnectDevice', 'cIndex']),
		data() {
			return {
				// tabList: [{
				// 	categoryType: 1,
				// 	categoryName: "全部"
				// }, {
				// 	categoryType: 1,
				// 	categoryName: "热门"
				// }, {
				// 	categoryType: 1,
				// 	categoryName: "对战"
				// }, {
				// 	categoryType: 1,
				// 	categoryName: "最新"
				// }, {
				// 	categoryType: 1,
				// 	categoryName: "益智"
				// }, {
				// 	categoryType: 1,
				// 	categoryName: "单机"
				// }],
				tabList: [],
				TabCur: 0,
				Category: 0,
				scrollLeft: 0,
				scrollviewHigh: '',


				bDontUpdate: false,

				//游戏列表
				gameList: [{
					gameIcon: "/static/avatar/1.png",
					gamePicture: "/static/conversion/game.png",
					gameName: "giabbit.nes",
					gamePlayNum: 100,
					gameDownloadUrl: "https://www.yuyekeji.cn/Cocos/FCEmulator/roms/giabbit/giabbit.nes",
					gameFileName: "giabbit",
					suffix: "nes",
					type: "NES",
					task: null,
					progressVal: 0,
					bFileExists: false,
					bDownload: false,
				}, {
					gameIcon: "/static/avatar/1.png",
					gamePicture: "/static/conversion/game.png",
					gameName: "giabbit.nes",
					gamePlayNum: 100,
					gameDownloadUrl: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
					gameFileName: "big_buck_bunny",
					suffix: "mp4",
					type: "mp4",
					task: null,
					progressVal: 0,
					bFileExists: false,
					bDownload: false,
				}],
				gamePage: 1,
				gameSize: 10,

				//编码的item
				encodeItem: ''
			};
		},
		onLoad(option) {
			let _this = this;
			// 	console.log("option========:", option);
			// 	let _index = 1;
			// 	if (option && option.type) {
			// 		if (option.type == "game") {
			// 			_index = 1;
			// 		} else if (option.type == "video") {
			// 			_index = 2;
			// 		}
			// 	}

			//获得游戏类目
			reqUtil.requestData(config.URL.FCCATEGORYBYTYPE,{categoryType:1}).then(
				res => {
					// console.log('FCCATEGORYBYTYPE =====', res);
					if (res.code == 0) {
						this.tabList = res.data;
						this.TabCur = 0;
						this.categoryType = this.tabList[0].categoryType;
						this.getGameList(this.categoryType);
					}
				},
				e => {
					console.log(e);
				}
			);

		},
		onReady() {
			let _this = this;
			uni.getSystemInfo({
				success(res) {
					// 计算组件的高度
					let view = uni.createSelectorQuery().select('#nav-bar');
					view.boundingClientRect(data => {
						let navHeight = data.height;
						let scrollXHight = uni.upx2px(90);
						_this.scrollviewHigh = res.windowHeight - navHeight - scrollXHight;
					}).exec();
				}
			});
		},
		methods: {
			onBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 跳转转换页面
			onNavConver() {
				uni.navigateTo({
					url: '../fc-list/fc-list',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},

			tabSelect(e) {
				if (this.TabCur != e.currentTarget.dataset.id) {
					//重新设置参数
					this.bDontUpdate = false;
					this.gameList = [];
					this.gamePage = 1;
					this.gameSize = 10;
					this.TabCur = e.currentTarget.dataset.id;
					this.categoryType = e.currentTarget.dataset.category_id;
					this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
					this.getGameList(this.categoryType);
				}

			},
			showClickEvent() {
				this.$refs.sideBar.showModal();
			},
			onNavSearch() {

				uni.showToast({
					title: '功能尚未开放',
					icon: 'none'
				})
				return;

				uni.navigateTo({
					url: '../game-search/game-search',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			//收藏
			onFavoriteAdd(item) {
				//添加收藏
				let favoritesTemp = {
					'fObjectId': item.gameId,
					'favoritesType': 0,
				}

				reqUtil.requestData(config.URL.FAVORITESMODIFY, favoritesTemp).then(res => {
						console.log('FAVORITESMODIFY =====', res);
						if (res.code == 0) {
							if (!res.data.bHas) {
								item.gameFavorite = false;
								uni.showToast({
									title: "取消收藏",
									icon: "none"
								})
							} else {
								uni.showToast({
									title: "收藏成功",
									icon: "none"
								})
								item.gameFavorite = true;
							}
						}

					},
					e => {
						console.log(e)
					});
			},
			onNavComment() {
				uni.showToast({
					title: '功能尚未开放',
					icon: 'none'
				})
				return;
				uni.navigateTo({
					url: '../game-comment/game-comment',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			onNavDetail(item) {
				// console.log(item);
				let temItem = encodeURIComponent(JSON.stringify(item));
				// return;
				uni.navigateTo({
					url: '../game-detail/game-detail?item=' + temItem,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			onNavToWebviewGame(item) {
				//#ifdef H5 
				console.log("h5");
				let _FCList = uni.getStorageSync("FCList");
				if (_FCList) {
					item.task = null;
					_FCList.push(item);
					uni.setStorageSync("FCList", _FCList);
				} else {
					uni.setStorageSync("FCList", [item]);
				}
				//#endif

				//#ifdef APP-PLUS
				console.log("====item == ", item);
				let downloadUrl = item.gameDownloadUrl;
				let name = item.gameFileName;
				item.task = plus.downloader.createDownload(downloadUrl, {
					filename: '_doc/' + name
				});
				item.task.addEventListener("statechanged", (download, status) => {
					// console.log("status", status);
					//连接服务器后
					// no default
					switch (download.state) {
						case 1:
							console.log('开始下载');
							// item.bDownload = true;
							break;
						case 2:
							console.log('链接到服务器...');
							item.bDownload = true;
							break;
						case 3:
							if (status !== 200) {
								uni.showToast({
									title: 'status=' + status
								})
								return;
							}
							item.progressVal = Math.ceil(download.downloadedSize / download.totalSize * 100);
							// _this.precent = progressVal;
							console.log(item.progressVal);
							break;
						case 4:
							// 下载完成
							console.log("监听下载 success: " + download.getFileName());
							setTimeout(() => {
								item.bDownload = false;
							}, 500)
							//todo 下载完成,设置记录数据到本地，
							let _FCList = plus.storage.getItem("FCList");
							console.log("_FCList:", _FCList);
							if (_FCList) {
								item.task = null;
								_FCList.push(item);
								plus.storage.setItem("FCList", _FCList);
								console.log("_FCList1:", _FCList);
							} else {
								plus.storage.setItem("FCList", [item])
								console.log("_FCList2:", [item]);
							}
							break;
					}
				}, false);
				item.task.start();

				//#endif
				return;

				if (!this.BLEConnectDevice || this.cIndex == -1) {
					uni.showToast({
						title: "没有连接绑带,请连接后重试！",
						icon: "none"
					})
					return;
				}


				reqUtil.requestData(config.URL.GAMEDETAIL, item).then(res => {
						console.log('GAMEDETAIL =====', res);
						if (res.code == 0) {
							this.encodeItem = encodeURIComponent(JSON.stringify(res.data.gameInfo));

							// #ifdef APP-PLUS
							uni.navigateTo({
								url: '../game-play-sub/game-play-sub?item=' + this.encodeItem,
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
							// #endif 
							// #ifdef H5
							uni.navigateTo({
								url: '../game-play/game-play-web?item=' + this.encodeItem,
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
							// #endif
						}

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

			},

			getGameList(categoryType) {
				uni.showToast({
					icon: "loading",
					title: "",
					mask: true,
					duration: 10000
				})
				//获得游戏列表
				reqUtil.requestData(
					config.URL.FCListByCategory, {
						categoryNumber: categoryType,//类目编号
						//endTime 可以不设置，服务器默认设置一个值
						// endTime: config.endTime,
						page: this.gamePage,
						size: this.gameSize
					}
				).then(res => {
						console.log('GAMELIST_FROM_CATEGORY =====', res);
						if (res.code == 0) {
							uni.hideToast();

							if (res.data.length < this.gameSize) {
								this.bDontUpdate = true;
							}

							if (res.data.length != 0) {
								uni.showToast({
									icon: "none",
									title: "更新成功",
								})
							} else {
								uni.showToast({
									icon: "none",
									title: "没数据啦",
								})
							}
							this.gameList = this.gameList.concat(res.data);
						}
					},
					e => {
						console.log(e);
						uni.showToast({
							icon: "none",
							title: "更新出错",
						})
					}
				);
			},

			onRoundTrigger(data) {
				console.log("onRoundTrigger==", data);
				// return;
				let url = '';
				switch (data.item.type) {
					case "personal":
						//个人中心页面
						url = '../../personal-page/personal/personal';
						break;
					case "game":
						url = '../../game-page/game/game';
						break;
					default:
						url = '../../personal-page/personal/personal';
						break;
				}
				uni.reLaunch({
					url: url,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			lower(e) {
				return;
				if (this.bDontUpdate) return;
				console.log(e);
				this.gamePage++;
				this.getGameList(this.categoryType);
			},
			getFile() {
				let url = "_doc/uniapp_save/1603173965127.nes";

				uni.getSavedFileList({
					success: function(res) {
						console.log(res.fileList);
						for (var i = 0, len = res.fileList.length; i < len; i++) {
							var path = plus.io.convertLocalFileSystemURL(res.fileList[i].filePath);
							console.log(path);
						}
					}
				});
			},
			navGame() {
				plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
					// 可通过fs操作PRIVATE_DOC文件系统 
					var directoryReader = fs.root.createReader();
					directoryReader.readEntries(function(entries) {
						var i;
						for (i = 0; i < entries.length; i++) {
							console.log(entries[i].name);
						}
					}, function(e) {
						console.log("Read entries failed: " + e.message);
					});
				}, function(e) {
					console.log("Request file system failed: ", e.message);
				});
			}
		}
	};
</script>

<style>
	.page {
		height: 100vh;
	}

	page {
		background-color: #fff;
	}

	.float-png {
		position: absolute;
		right: 15px;
		bottom: 200px;
		width: 56px;
		height: 56px;
	}

	.png-search {
		width: 50rpx;
		height: 100%;
		position: absolute;
		right: 20px;
		top: 0;
		bottom: 0;
		margin: auto;
		display: flex;
		justify-content: center;
		align-items: center;
		/* border: 1rpx solid #000000; */
	}

	.scrollX {
		position: relative;
		width: 100%;
		height: 90rpx;
		margin-bottom: 10px;
		/* border: 1rpx solid #000000; */
	}

	.scrollX-padding {
		padding: 0 20px;
	}

	.game-item {
		/* display: flex; */
		/* justify-content: space-between; */
		/* flex-direction: row; */
		/* background-color: white; */

		flex: 0 0 33.3%;
		max-width: 33.3%;
		width: 226rpx;
		height: 270rpx;
		margin: 17px 10px 0 10px;
		border: 1rpx solid #000000;
		border-radius: 10rpx;
		position: relative;
		/* border-bottom: 1rpx solid rgba(240, 240, 240, 1); */
	}

	.game-item-image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
		z-index: 99;
	}

	.head-image {
		position: absolute;
		bottom: -20px;
		left: 0;
		margin-left: 17px;
		width: 80rpx;
		height: 80rpx;
		border: 2px solid white;
		border-radius: 100px;
		z-index: 100;
	}

	.play-bg-download {
		position: absolute;
		bottom: 0;
		left: 0;
		top: 0;
		right: 0;
		margin: auto;
		background: rgba(0, 0, 0, 0.3);
		z-index: 100;
		display: flex;
		flex-direction: column;
		justify-content: center;
		text-align: center;
		border-radius: 12rpx;
	}

	.play-image {
		position: absolute;
		bottom: 0;
		left: 0;
		top: 0;
		right: 0;
		width: 44rpx;
		height: 54rpx;
		margin: auto;
		z-index: 100;
	}

	.game-image-container {
		position: relative;
	}

	.game-index {
		z-index: 300;
	}

	.cu-color {
		color: rgba(191, 191, 193, 1);
	}

	.right-png {
		width: 36rpx;
		height: 32rpx;
	}

	.fc-bottom-container {
		position: absolute;
		bottom: 0;
		left: 0;
		/* top: 0; */
		right: 0;
		width: 100%;
		height: 80rpx;
		border-radius: 0 0 10rpx 10rpx;
		margin: auto;
		z-index: 100;
		background: linear-gradient(left, rgb(66, 202, 96), rgb(23, 193, 14));
	}

	.fc-list {
		display: flex;
		flex-wrap: wrap;
		padding: 10px 10rpx 0px;
		justify-content: flex-start;
	}

	.fc-li {
		border-radius: 12rpx;
		width: 32%;
		height: 270rpx;
		margin: 0 0 20rpx 8rpx;
		position: relative;
		z-index: 1;
	}

	.fc-li::after {
		content: "";
		position: absolute;
		z-index: -1;
		background-color: inherit;
		width: 100%;
		height: 100%;
		left: 0;
		bottom: -10%;
		border-radius: 10upx;
		opacity: 0.2;
		transform: scale(0.9, 0.9);
	}

	.fc.cur {
		color: #fff;
		background: rgb(94, 185, 94);
		box-shadow: 4upx 4upx 6upx rgba(94, 185, 94, 0.4);
	}

	.web-view {
		position: relative;
		display: flex;
		flex-direction: column;
		border-style: solid;
		border-width: 1rpx;
		border: 1rpx solid #007AFF;
	}

	.web-view-child {
		width: 650rpx;
		height: 1280rpx;
		/* flex: 1; */
	}
</style>
