import Scene from "../views/Scene";
import { DataManager } from "../../libs/tw/manager/DataManager";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { NetManager } from "../../libs/tw/manager/NetManager";
import SceneCtrl from "../ctrls/sceneCtrl";
import Loading from "../loading/Loading";

export default class MainScene extends Scene {

	public costTipsTxt: eui.Label;
	public startBtn: eui.Button;
	public iconImg: eui.Image;
	public detailCloseBtn: eui.Button;
	public nameTxt: eui.Label;
	public mainbg: eui.Image;
	public text0: eui.Label;
	public text1: eui.Label;
	public appleLb: eui.Label;
	public prizeRateTxt: eui.Label;
	public detailInfoTxt: eui.Label;
	public detailGroup: eui.Group;


	public get skinKey() { return 'MainScene' }
	public get groupName() { return 'main_scene' }

	constructor(data?) {
		super(data);
		this.percentHeight = 100;
	}

	initEvents() {
		super.initEvents();
		this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_startBtn, this);
		this.detailCloseBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_detailCloseBtn, this);
		this.itemAddEvent();
	}

	removeEvents() {
		super.removeEvents();
		this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_startBtn, this);
		this.detailCloseBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_detailCloseBtn, this);
		this.itemRemoveEvent();
	}

	private itemAddEvent(): void {
		for (let i = 0; i < 10; i++) {
			this['itemIcon' + i].name = i;
			this['itemIcon' + i].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_item, this);
		}
	}

	private itemRemoveEvent(): void {
		for (let i = 0; i < 10; i++) {
			this['itemIcon' + i].removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_item, this);
		}
	}

	protected onSkinComplete(): void {
		super.onSkinComplete();
		this.mainbg.texture = this.bgtexture;

		this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
		if (this.stage) {
			this.onLoad();
		}
	}

	start(data?) {
	}

	private onLoad(): void {

		this.showAct();
		this.initUI();

		this.playAnimation(this['act1'], true);
		this.playAnimation(this['act2'], true);
	}

	private initUI(): void {
		var str1: string = '1.玩转拼图游戏需要使用66捞币/次；\n2.第一关，在规定时间30秒内完成九块拼图，将获得第二关拼图机会；\n3.第二关，在规定时间30秒内完成十六块拼图，将获得抽奖机会。';
		this.text0.text = window['ruleText'] ? window['ruleText'] : str1;

		var str2: string = '1.美味拼图参与1次需要使用66捞币，参与后捞币概不退回；\n2.抽奖机会至获得之日起30天内有效，过期未抽奖将默认放弃抽奖机会；\n3.每位用户每日最多可参与3次；\n4.抽奖获得的代金券、菜品券可在“我的卡券”中查询；游戏道具奖品，将自动同步在“app——火舞游戏：火锅美食家 、抢食大作战”中；\n5.用户若以非正当的方式参与活动，在活动中获得的奖品，海底捞有权对该用户采取包括但不限于收回奖品、限制登录或封禁等措施。';
		this.text1.text = window['warmText'] ? window['warmText'] : str2;

		if (DataManager.ins.getInfoData.status.code == 0) {
			this.playAnimation(this['act0'], true);

			this.startBtn.touchEnabled = true;
			this.startBtn.currentState = 'up';
			this.startBtn.invalidateState();
		} else {
			this.startBtn.touchEnabled = false;
			this.startBtn.currentState = 'disabled';
			this.startBtn.invalidateState();
			this['act0'].pause();
			this['act0'].stop();
		}

		if (DataManager.ins.getInfoData.status.code == 2) {
			this.setStatus('捞币不足!');
		} else {
			this.setStatus(DataManager.ins.getInfoData.status.text);
		}

		if (egret.Capabilities.os == "iOS") {
			this.appleLb.visible = true;
		}
		else {
			this.appleLb.visible = false;
		}

		console.log('DataManager.ins.getInfoData.status.text=' + DataManager.ins.getInfoData.status.text);
	}

	private onClick_startBtn(e: egret.TouchEvent): void {
		console.log('开始游戏！');
		if (!window['isJudgeLogin']) {
			this.startChange();
			return;
		}

		//待测试
		Loading.instace.show();
		this.initBridge(function (bridge) {
			this.callHandler(bridge);
		}.bind(this));


	}

	private callHandler(bridge: any): void {
		bridge.callHandler('pullUpLogin', function (response) {
			console.log(response);
			console.log('isLogin: ', JSON.parse(response).isLogin);
			if (JSON.parse(response).isLogin) {
				Loading.instace.hide();
				this.startChange();
			} else {
				this.callHandler();
			}
		}.bind(this));
	}
	private onOkBtnCallBack(): void {
		console.log('点击了确认花费捞币进入游戏！');
		Loading.instace.show();
		NetManager.ins.doStart(function (success: boolean) {
			if (success) {
				NetManager.ins.getStartStatus(
					(data) => {
						console.log('data轮询失败=' + data);
						Loading.instace.hide();
						if (data == 'pollingFaild' || !data) {//统一处理异常？？？？？？？
							this.showMsg('iknowBtn',
								[
									{ text: "捞币扣除出故障了～\n截图反馈给捞小秘,捞小秘\n将根据捞币扣除情况处理" }
								], 3, this.errorMsgCallBack, this.errorMsgCallBack);
						} else {
							this.loadPintuImg();
						}
					},
					DataManager.ins.doStartData.ticketId,
					() => { return DataManager.ins.getStartStatusData.code == 0; },
					5);
			} else {
				Loading.instace.hide();
				console.log('dostart失败');
				//统一处理异常？？？？？？？
				this.showMsg('iknowBtn',
					[
						{ text: "捞币扣除出故障了～\n截图反馈给捞小秘,捞小秘\n将根据捞币扣除情况处理" }
					], 3, this.errorMsgCallBack, this.errorMsgCallBack);
			}
		}.bind(this), false);
	}

	private bgtexture: egret.Texture;
	protected async preLoadRes() {
		//加载背景并设置背景图片
		this.bgtexture = await RES.getResAsync('mainBg_jpg');
		console.log('载背景并设置背景图片mainscene');
		return new Promise(function (resolve, reject) {
			resolve();
		});
	}

	private async loadPintuImg() {

		// RES.getResAsync('lightEff_png');
		// RES.getResAsync('selectRect1_png');
		// RES.getResAsync('line1_png');//需要删除的代码？？？？？？
		// RES.getResAsync('selectRect0_png');
		// RES.getResAsync('line0_png');//需要删除的代码？？？？？？
		// RES.getResAsync('levelTxt1_png');
		// RES.getResAsync('levelTxt0_png');

		Loading.instace.show();
		const texture = await RES.getResAsync('ptImg' + Math.floor(Math.random() * 9) + '_jpg');
		Loading.instace.hide();
		SceneCtrl.instance.change(ModuleTypes.GAME_SCENE, texture);

		// RES.getResByUrl('resource/assets/img/ptImg' + Math.floor(Math.random() * 9) + '.jpg', function(texture){
		// 	SceneCtrl.instance.change(ModuleTypes.GAME_SCENE, texture);
		// });
	}

	private onClick_item(e: egret.TouchEvent): void {
		console.log('e.target.name=' + e.target.name);
		this.showDetailPanel(e.target.name);
		this.detailGroup.visible = true;

	}

	private onClick_detailCloseBtn(): void {
		this.detailGroup.visible = false;
	}

	//开始游戏切换场景
	private startChange(): void {
		// 海底捞登录成功回调
		var msgData: any = { btnName: 'okBtn', fontSize: 35, lineCount: 2, lineSpace: 15, callBack: this.onOkBtnCallBack.bind(this) };
		msgData.msgArr = [
			{ text: "确认消耗" },
			{ text: DataManager.ins.gameCfgData.gameInfo['credits'] + '捞币\n', style: { "textColor": 0xf8550d } },
			{ text: '参与“美味拼图”吗？' }
		];

		PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
	}

	private showDetailPanel(id: any): void {
		const idx = Number(id);
		if (idx == 0) {
			this.detailInfoTxt.text = this.describeArr[idx];

		} else if (idx > 0 && idx < 8) {
			this.detailInfoTxt.text = this.describeArr[1];

		} else if (idx == 8) {
			this.detailInfoTxt.text = this.describeArr[2];

		} else {
			this.detailInfoTxt.text = this.describeArr[3];
		}

		this.nameTxt.text = this.nameArr[idx];
		this.prizeRateTxt.text = this.rateArr[idx];

		this.loadImg(this.iconImg, 'item' + idx + '_png');
	}

	//设置花费提示
	private setStatus(str: string): void {
		this.costTipsTxt.text = str;
	}

	//加载图片
	private async loadImg(img: eui.Image, imgName: string) {
		// var a = await RES.getResAsync(imgName);
		img.width = 124;
		img.height = 162;
		img.y = 350;
		img.texture = await RES.getResAsync(imgName);
	}

	//消息弹出框
	private showMsg(bname: string, msgArr: any, linecount: number = 2, callBack?: Function, closeCallBack?: Function): void {
		var msgData: any = {
			btnName: bname,
			fontSize: 35,
			lineCount: linecount,
			lineSpace: 15,
			callBack: callBack ? callBack.bind(this) : null,
			closeCallBack: closeCallBack ? closeCallBack.bind(this) : null
		};
		msgData.msgArr = msgArr;

		PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
	}

	private errorMsgCallBack(): void {
		//获取游戏信息
		Loading.instace.show();
		NetManager.ins.getInfo((success: boolean) => {
			if (success) {
				this.initUI();
			} else {
				//提示用户，返回上一层，重新进入活动？？？？？
				this.showMsg('iknowBtn',
					[
						{ text: "网络开小差了\n世界上最遥远的距离莫过于此" }
					]);
			}
			Loading.instace.hide();
		});
	}

	//循环播放动画
	private playAnimation(target: egret.tween.TweenGroup, isLoop: boolean): void {
		if (isLoop) {
			for (var key in target.items) {
				target.items[key].props = { loop: true };
			}
		}
		target.play();
	}

	private nameArr = [
		'30元代金券',
		'午餐肉（半份）',
		'冻豆腐（半份）',
		'捞面一条',
		'海带（半份）',
		'鹌鹑蛋（半份）',
		'蟹味棒（半份）',
		'土豆（半份）',
		'火锅美食家-连击翻倍',
		'抢食大作战-抵御炸弹'
	];
	private rateArr = [
		'中奖概率：1%',
		'中奖概率：10%',
		'中奖概率：10%',
		'中奖概率：20%',
		'中奖概率：10%',
		'中奖概率：9%',
		'中奖概率：5%',
		'中奖概率：5%',
		'中奖概率：15%',
		'中奖概率：15%'
	];
	private describeArr = [
		'奖品详情：\n1、仅限中国大陆地区门店使用，兑换成功之日起30天内有效，过期自动失效\n2、此券不与任何折扣同享,且每次仅限使用一张\n3、本券不能转赠，且仅限堂食使用\n4、本券不能与服务费用进行抵用\n5、本券不能兑现，不能找零\n6、海底捞保有在法律允许范围内对活动规则进行解释的权利',
		'奖品详情：\n1、会员在门店IPAD端登录会员账号，选择对应菜品名称和分量下单，买单时选择本券使用\n2、仅限中国大陆地区门店使用，获券之日起30天内有效，过期自动失效\n3、“美味拼图”活动奖励券，不找零，不兑现，不能转赠，且仅限堂食使用\n4、在门店同款菜品售罄的情况下不能兑换，也不能使用\n5、海底捞保有在法律允许范围内对活动规则进行解释的权利',
		'奖品详情：火锅美食家-连击翻倍',
		'奖品详情：抢食大作战-抵御炸弹'
	];
	//切换要加载的图片
	// private async loadMainBg(){
	// 	var bgtexture:egret.Texture = await RES.getResAsync(this.currBgName);
	// 	this.mainbg.texture 		= bgtexture;
	// }


	// const setupWebViewJavascriptBridge = function(callback) {
	// 	this.initBridge(callback);
	//   };

	private initBridge(callback) {
		const u = navigator.userAgent;
		const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
		const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if (isiOS) {
			this.initIOSJsBridge(callback);
		} else if (isAndroid) {
			console.log('isAndroid');
			this.initAndroidJsBridge(callback);
		} else {
			// alert('未知机型')
			console.log('未知机型');
		}
	}

	private initIOSJsBridge(callback) {
		if (window['WebViewJavascriptBridge']) {
			return callback(window['WebViewJavascriptBridge']);
		}
		if (window['WVJBCallbacks']) {
			return window['WVJBCallbacks'].push(callback);
		}
		window['WVJBCallbacks'] = [callback];
		var WVJBIframe = document.createElement('iframe');
		WVJBIframe.style.display = 'none';
		WVJBIframe.src = 'https://__bridge_loaded__';
		document.documentElement.appendChild(WVJBIframe);
		setTimeout(function () {
			document.documentElement.removeChild(WVJBIframe);
		}, 0);
	}

	private initAndroidJsBridge(callback) {
		if (window['WebViewJavascriptBridge']) {
			callback(window['WebViewJavascriptBridge']);
		} else {
			console.log('andriod');
			document.addEventListener(
				'WebViewJavascriptBridgeReady',
				function () {
					callback(window['WebViewJavascriptBridge']);
				},
				false
			);
		}
	}

	//   window.setupWebViewJavascriptBridge = setupWebViewJavascriptBridge;
	//   window.setupWebViewJavascriptBridge(function(bridge) {
	// 	bridge.callHandler('pullUpLogin', function(response) {
	// 	  console.log(response);
	// 	  console.log('isLogin: ', JSON.parse(response).isLogin);
	// 	  if (JSON.parse(response).isLogin) {
	// 		// 海底捞登录成功回调
	// 		location.reload();
	// 	  } else {
	// 		self.callHDLLogin();
	// 	  }
	// 	});
	//   });

}