class UI_Index extends UIBaseComponent {
	private gaming: boolean = false;

	private clockGroup: eui.Group;
	private userGroup: eui.Group;
	private myCardGroup: eui.Group;
	private dealerCardGroup: eui.Group;
	private betArr: eui.Group[] = [];
	private betMyWinGroup: eui.Group;
	private betDealerWinGroup: eui.Group;
	private betMyDoubleGroup: eui.Group;
	private betDrawGroup: eui.Group;
	private betDealerDoubleGroup: eui.Group;

	private myCardArr: eui.Image[] = [];
	private dealerCardArr: eui.Image[] = [];
	private myCard1: eui.Image;
	private myCard2: eui.Image;
	private myCard3: eui.Image;
	private dealerCard1: eui.Image;
	private dealerCard2: eui.Image;
	private dealerCard3: eui.Image;

	private onlineNumber: eui.Label;//当前在线人数
	private clockText: eui.Label;//时钟倒计时文本
	private clockBeting: eui.Label;//时钟下注中
	private clockLotterying: eui.Label;//时钟开奖中
	private myCountText: eui.Label;
	private dealerCountText: eui.Label;
	private dealerIdentityText: eui.Label;//庄
	private myIdentityText: eui.Label;//闲
	private betMyWinText: eui.Label;//閒赢1 : 1
	private betDealerWinText: eui.Label;//莊赢1 : 0.95
	private betMyDoubleText: eui.Label;//閒對1:11
	private betDrawText: eui.Label;//和1:8
	private betDealerDoubleText: eui.Label;//莊對1:11

	private notificationComponent: eui.Group;
	private userHeaderComponent: eui.Group;
	private betComponent: eui.Group;
	private rateComponent: eui.Group;
	private tradeComponent: eui.Group;
	private chipComponent: eui.Group;

	private musicToggle: eui.ToggleButton;

	private winArr: eui.Image[] = [];
	private betMyWinImg: eui.Image;
	private betDealerWinImg: eui.Image;
	private betMyDoubleWinImg: eui.Image;
	private betDrawWinImg: eui.Image;
	private betDealerDoubleWinImg: eui.Image;

	private resultArr: eui.Group[] = [];
	private myWinResult: eui.Group;
	private dealerWinResult: eui.Group;
	private myDoubleWinResult: eui.Group;
	private drawWinResult: eui.Group;
	private dealerDoubleWinResult: eui.Group;

	//h5
	private rateBtn: eui.Button;
	private tradeBtn: eui.Button;

	private clockTimer: number;
	private online: number = 0;

	private totalPokerLength: number = 0;//本轮展示扑克的个数，用于判断是否已经展示完成
	private showingPoker: boolean = false;
	private showedPokerQueen: any[] = [];//展示过的poker队列
	private showingPokerQueen: any[] = [];//待展示的poker队列
	private totalPokerShowedCb: Function;
	public constructor() {
		super();
	}

	/**
	 * 绑定事件
	 */
	protected bindEvents(): void {
		super.bindEvents();
		mouse.setButtonMode(this.betMyWinGroup, true);
		mouse.setButtonMode(this.betDealerWinGroup, true);
		mouse.setButtonMode(this.betMyDoubleGroup, true);
		mouse.setButtonMode(this.betDrawGroup, true);
		mouse.setButtonMode(this.betDealerDoubleGroup, true);
		mouse.setButtonMode(this.musicToggle, true);


		this.betDealerWinGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onChipBtn(1), this);
		this.betMyWinGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onChipBtn(0), this);
		this.betDrawGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onChipBtn(2), this);
		this.betDealerDoubleGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onChipBtn(4), this);
		this.betMyDoubleGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onChipBtn(3), this);

		this.musicToggle.addEventListener(eui.UIEvent.CHANGE, this.onMusicToggle, this);

		this.tradeBtn && this.tradeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTradeBtn, this);
		this.rateBtn && this.rateBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onRateBtn, this);

		this.chipComponent.touchEnabled = false;
		this.chipComponent.touchChildren = false;
	}

	/**
	 * 创建完成时调用
	 */
	protected onCreate(): void {
		super.onCreate();
		this.betArr.push(this.betMyWinGroup, this.betDealerWinGroup, this.betDrawGroup, this.betMyDoubleGroup, this.betDealerDoubleGroup);
		this.winArr.push(this.betMyWinImg, this.betDrawWinImg, this.betDealerWinImg, this.betDealerDoubleWinImg, this.betMyDoubleWinImg);
		this.resultArr.push(this.myWinResult, this.dealerWinResult, this.drawWinResult, this.myDoubleWinResult, this.dealerDoubleWinResult);
		this.myCardArr.push(this.myCard1, this.myCard2, this.myCard3);
		this.dealerCardArr.push(this.dealerCard1, this.dealerCard2, this.dealerCard3);

		this.addComponent(this.betComponent, Bet.instance.getBetView());
		this.addComponent(this.notificationComponent, Notice.instance.getNoticeView());
		this.addComponent(this.userHeaderComponent, Userinfo.instance.getUserHeaderView());

		if (!GAME_ISMOBILE) {
			this.addComponent(this.rateComponent, Rate.instance.getRateView());
			this.addComponent(this.tradeComponent, Trade.instance.getTradeView());
		}

		this.render();
		this.onLangChange();

		this.rateComponent.touchThrough = true;
		this.tradeComponent.touchThrough = true;
		this.betMyWinText.touchEnabled = false;
		this.betDealerWinText.touchEnabled = false;
	}

	/**
	 * 渲染UI时调用
	 */
	protected render(): void {
		this.myCountText.text = this.dealerCountText.text = '';

		this.setWinGroupVisible(false);
		this.setCardGroupVisible(false);
		this.setBetGroupEnable(false);

		this.musicToggle.selected = AudiosMgr.instance.bgmAllow;
	}

	setOnlineNumber(onlineNumber: number): void {
		this.online = onlineNumber;

		let { Index } = Lang.instance.lang();

		this.onlineNumber.text = Index.online + '：' + this.online;
	}

	// render gameInfo [pb_11_play.pbGame]
	renderGameInfo(gameInfo: any): void {
		Index.instance.gameInfo = gameInfo;
		DEBUG && console.log('gameInfo:', gameInfo);
		this.renderGameStart(gameInfo);
	}

	//TODO render gamestart
	renderGameStart(gameInfo: { timeout: number, id: string }): void {
		let {gameStart} = Lang.instance.lang().Alert;
		
		this.gaming = true;

		this.totalPokerLength = 0;

		this.showedPokerQueen = [];

		this.showingPokerQueen = [];

		AlertMgr.instance.hideAlert()

		AlertMgr.instance.hideFairAlert()

		AlertMgr.instance.showAlert(gameStart);

		AudiosMgr.instance.playNewRound();

		Bet.instance.renderGameStart();

		Trade.instance.emptyTradeList();//清空投注信息

		Trade.instance.renderGameId(gameInfo.id);

		Index.instance.clearChip();//清空下注数量

		this.setBetGroupEnable(true);
		this.setWinGroupVisible(false);
		this.setCardGroupVisible(false);

		this.myCountText.text = this.dealerCountText.text = ' ';

		let {beting} = Lang.instance.lang().Index;

		this.clockLotterying.visible = false;

		this.clockBeting.visible = this.clockText.visible = true;

		let {timeout} = gameInfo;

		timeout = Math.max(0, timeout);

		this.clockText.text = timeout.toString();

		clearInterval(this.clockTimer);

		if (timeout === 0) {
			this.beforeLottery();
			return;
		}

		this.clockTimer = setInterval(() => {
			timeout--;
			this.clockText.text = timeout.toString();
			if (timeout <= 0) {
				DEBUG && console.log('clock stop');
				this.beforeLottery();
			}
		}, 1000)

	}

	beforeLottery() {
		this.gaming = false;

		this.setBetGroupEnable(false);

		clearInterval(this.clockTimer);

		let {rewarding} = Lang.instance.lang().Index;

		AlertMgr.instance.showAlert(rewarding, true);

		this.clockLotterying.visible = true;

		this.clockBeting.visible = this.clockText.visible = false;
	}

	// render lotteryInfo
	//如果没有通知展示poker 直接按照原方式显示扑克。不然进行校验
	async renderLotteryInfo(lotteryInfo: any, _newGame: any) {
		if (this.showedPokerQueen.length === 0 && !this.showingPoker) {
			DEBUG && console.log('lotteryInfo:', lotteryInfo);

			AlertMgr.instance.hideAlert();

			let {offer, reveal_info} = lotteryInfo;

			let {player, banker, win, playerPair, bankerPair, blockInfo} = reveal_info;

			Bet.instance.renderLotteryInfo();

			await this.showLotteryPoker(player, banker, blockInfo);

			this.showLotteryResult(win, bankerPair, playerPair);

			offer && Userinfo.instance.addOffer(offer);

			setTimeout(() => {
				_newGame.timeout -= 3;
				this.renderGameInfo(_newGame);
			}, 3000);
		} else {
			let {player, banker} = lotteryInfo.reveal_info;

			this.totalPokerLength = player.length + banker.length;

			let timestamp = Date.now();

			this.totalPokerShowedCb = () => {
				let {offer, reveal_info} = lotteryInfo;

				let { win, playerPair, bankerPair, blockInfo} = reveal_info;

				this.showLotteryResult(win, bankerPair, playerPair);

				offer && Userinfo.instance.addOffer(offer);

				setTimeout(() => {
					let now = Date.now();
					let seconds = Math.round((now - timestamp) / 1000);
					_newGame.timeout -= seconds;
					this.renderGameInfo(_newGame);
				}, 3000);
			}

			if (this.showedPokerQueen.length === this.totalPokerLength) {
				this.totalPokerShowedCb();
			}
		}
	}

	/**
	 * 0-player 1-banker 2-tie 3-playerpair 4-bankerpair
	 * */
	renderLotteryResult(result: number[]): void {
		// AudiosMgr.instance.playWin();
		this.resultArr.forEach(ele => { ele.visible = false });

		let {Index, Bet } = Lang.instance.lang();

		result.forEach((total, index) => {
			if (index == 0) {
				total > 0 && this.showResult(this.myWinResult, `${Index.playerWin.toUpperCase()}  ${total} EOS`);
			} else if (index == 1) {
				total > 0 && this.showResult(this.dealerWinResult, `${Index.bankerWin.toUpperCase()}  ${total} EOS`);
			} else if (index == 2) {
				total > 0 && this.showResult(this.drawWinResult, `${Bet.tie.toUpperCase()}  ${total} EOS`);
			} else if (index == 3) {
				total > 0 && this.showResult(this.myDoubleWinResult, `${Bet.playerPair.toUpperCase()}  ${total} EOS`);
			} else if (index == 4) {
				total > 0 && this.showResult(this.dealerDoubleWinResult, `${Bet.bankerPair.toUpperCase()}  ${total} EOS`);
			}
		});
	}

	setBetGroupEnable(enable: boolean): void {
		this.betArr.forEach(ele => { ele.touchEnabled = ele.touchChildren = enable; });
	}

	setCardGroupVisible(visible: boolean): void {
		this.myCardArr.forEach(ele => { ele.visible = visible; ele.source = 'poker_json.poker_back' });
		this.dealerCardArr.forEach(ele => { ele.visible = visible; ele.source = 'poker_json.poker_back' });
	}

	setWinGroupVisible(visible: boolean): void {
		this.winArr.forEach(ele => { ele.visible = visible });
		this.resultArr.forEach(ele => { ele.visible = false });
	}

	private showResult(component: eui.Group, content: string): void {
		let label = <eui.Label>component.getChildAt(1);

		label.text = content;
		component.width = label.width + 10;
		component.visible = true;
	}

	/**
	 *根据通知信息显示扑克牌
	 *data:{"type":"player","poker":13,"num":13,"color":0,"block_num":6510197,"block_id":"0063567567f09f9c27b6c7ae82d4ac7bce3eef2aaf4713b8b4b07dc5d109798d"} 
	 */
	async showChannelPoker(data) {
		if (this.showingPoker) {
			this.showingPokerQueen.push(data);
			return;
		};

		AlertMgr.instance.hideAlert();

		let showedpoker = this.showedPokerQueen.filter(poker => poker.type === data.type);

		let i = showedpoker.length;

		let sameBlockLength = this.showedPokerQueen.filter(poker => poker.block_num === data.block_num).length;

		if (sameBlockLength === 0) {
			let displayArr = data.type === 'player' ? this.myCardArr : this.dealerCardArr;

			this.showingPoker = true

			await this.showPoker(displayArr[i], data.poker, { poker: data.poker, blockId: data.block_id }, i);

			this.showingPoker = false;

			let countText: eui.Label = data.type === 'player' ? this.myCountText : this.dealerCountText;

			countText.text = ([].concat(showedpoker, [data]).reduce((prev, cur) => { return prev + Util.pointPoker(cur.poker) }, 0) % 10).toString();

			this.showedPokerQueen.push(data);

			//如果已经完成所有扑克的展示
			if (this.totalPokerLength !== 0 && this.totalPokerLength === this.showedPokerQueen.length) {
				this.totalPokerShowedCb && this.totalPokerShowedCb();
			}
		}

		this.showNextChannelPoker();
	}

	//显示下一张扑克牌
	private showNextChannelPoker() {
		if (this.showingPokerQueen.length) {
			this.showChannelPoker(this.showingPokerQueen.shift());
		}
	}

	async showLotteryPoker(player: number[], banker: number[], blockInfo: { player: any[], banker: any[] }) {
		let playerBlock = blockInfo.player
		let bankerBlock = blockInfo.banker
		for (let i = 0, len = Math.max(player.length, banker.length); i < len; i++) {
			await this.showPoker(this.myCardArr[i], player[i], playerBlock[i], i);
			this.myCountText.text = (player.slice(0, i + 1).reduce((prev, cur) => { return prev + Util.pointPoker(cur) }, 0) % 10).toString();
			await this.showPoker(this.dealerCardArr[i], banker[i], bankerBlock[i], i);
			this.dealerCountText.text = (banker.slice(0, i + 1).reduce((prev, cur) => { return prev + Util.pointPoker(cur) }, 0) % 10).toString();
		}
	}

	showLotteryResult(result: number, bankerPair: boolean, playerPair: boolean): void {
		AlertMgr.instance.hideFairAlert()

		this.betDealerDoubleWinImg.visible = bankerPair;
		this.betMyDoubleWinImg.visible = playerPair;

		this.betMyWinImg.visible = result === 0;
		this.betDrawWinImg.visible = result === 2;
		this.betDealerWinImg.visible = result === 1;

		AudiosMgr.instance.playWin();
	}

	showPoker(element: eui.Image, value: number, block: { blockId: string, poker: number }, index: number): Promise<Object> {
		if (!value) return null;

		return new Promise((resovle, reject) => {
			element.visible = true;
			let begin = { y: element.y }
			element.y = -200;
			let start = index == 2 ? { scaleY: 0 } : { scaleX: 0 };
			let end = index == 2 ? { scaleY: 1 } : { scaleX: 1 };
			let imgUrl = `poker_${Util.toPoker(value)}_${Util.toPokerColour(value)}`;
			egret.Tween.get(element)
				.wait(index === 2 ? 500 : 0)
				.to(begin, 300, egret.Ease.backOut)
				.to(start, 250)
				.call(() => { element.source = imgUrl; AlertMgr.instance.showFairAlert(block, imgUrl) })
				.to(end, 250)
				.wait(100)
				.call(resovle)
		})
	}

	setMusicToggle(selected: boolean): void {
		DEBUG && console.log('musicToggle:', selected);
		this.musicToggle.selected = selected;
	}

	//TODO music control
	private onMusicToggle(ev: eui.UIEvent): void {
		DEBUG && console.log('onMusicToggle:', this.musicToggle.selected);
		AudiosMgr.instance.setBgmAllow(this.musicToggle.selected);
		if (this.musicToggle.selected) {
			AudiosMgr.instance.playBgm();
		} else {
			AudiosMgr.instance.stopBgm();
		}
	}

	private onTradeBtn(ev: egret.TouchEvent): void {
		AudiosMgr.instance.playButtonClick();

		Trade.instance.openTradeView();
	}

	//RateBtn-h5
	private onRateBtn(ev: egret.TouchEvent): void {
		AudiosMgr.instance.playButtonClick();
		Rate.instance.openRateView();
	}

	/**
	 * 改变语言时调用
	 */
	protected onLangChange(ev?: egret.Event): void {
		let {Index, Bet } = Lang.instance.lang();

		this.onlineNumber.text = Index.online + '：' + this.online;
		this.dealerIdentityText.text = Bet.banker.toUpperCase();//庄
		this.myIdentityText.text = Bet.player.toUpperCase();//闲
		this.betMyWinText.text = Index.playerWin.toUpperCase() + '\n2x';//閒赢1 : 1
		this.betDealerWinText.text = Index.bankerWin.toUpperCase() + '\n1.95x';//莊赢1 : 0.95
		this.betMyDoubleText.text = Bet.playerPair.toUpperCase() + '\n12x';//閒對1:11
		this.betDrawText.text = Bet.tie.toUpperCase() + '\n9x';//和1:11
		this.betDealerDoubleText.text = Bet.bankerPair.toUpperCase() + '\n12x';//莊對1:11
		this.clockBeting.text = Index.beting;
		this.clockLotterying.text = Index.rewarding
		setTimeout(() => {
			this.refreshLotteryResult()
		}, 0);

		if (GAME_ISMOBILE) {
			this.rateBtn.label = Index.rateBtnText;
			this.tradeBtn.label = Index.tradeBtnText;
		}
	}

	private refreshLotteryResult(): void {
		Index.instance.refreshLotteryResult();
	}

	private addComponent(target: egret.DisplayObjectContainer, component: UIBaseComponent): void {
		target.addChild(component);
	}

	/**
	 * 下注区域事件
	 */
	private onChipBtn(type: number): Function {
		return function (ev: egret.TouchEvent) {
			AudiosMgr.instance.playButtonClick();

			if (Bet.instance.chipValue == 0) {
				DEBUG && console.log('请选择筹码');
				return;
			} else {
				if (UserMgr.instance.isLogin()) {
					let target = <eui.Group>ev.currentTarget;

					let leftCircleCenter = { x: 960, y: -450 }
					let rigthCircleCenter = { x: -208, y: -450 }
					let r = 900

					let {localX, localY, stageX, stageY} = ev;

					//庄闲位置
					if (!GAME_ISMOBILE && type <= 1) {
						let center = type === 0 ? leftCircleCenter : rigthCircleCenter
						let point = { x: localX, y: localY }
						let distance = Util.getDistanceBetweenTwoPoint(center, point)
						//大于半径则默认扔到合理区域
						if (distance > r) {
							let randomX: number, randomY: number;
							if (type === 0) {
								randomX = (Math.random() * 3 + 5) / 10;//[0.5-0.8]
							} else {
								randomX = (Math.random() * 3 + 2) / 10;//[0.2-0.5]
							}
							randomY = (Math.random() * 6 + 2) / 10;
							let x = target.width * randomX;
							let y = target.height * randomY;

							stageX += (x - localX);
							localX = x;
							stageY += (y - localY);
							localY = y;
						}
					}

					if (localX < 47) {
						stageX += (47 - localX);
					} else if (target.width - localX < 47) {
						stageX -= (localX - target.width + 47);
					}

					if (localY < 47) {
						stageY += (47 - localY);
					} else if (target.height - localY < 47) {
						stageY -= (localY - target.height + 47);
					}
					Index.instance.addChip(type, Bet.instance.chipValue)
					Bet.instance.largeChipIn(type, this.chipComponent, stageX, stageY);
				}
			}
		}

	}

	/**
	 * 显示他人投注筹码
	 */
	showOtherBet(pbBetList: any[], isLarge: boolean = false): void {
		pbBetList.forEach(({type, counter}) => {
			let component = this.betArr[type];
			let {width, height} = component;
			counter.forEach(({key, val}) => {
				while (val > 0) {

					let randomX: number, randomY: number;

					if (!GAME_ISMOBILE && component === this.betMyWinGroup) {
						randomX = (Math.random() * 3 + 5) / 10;//[0.5-0.8]
					} else if (!GAME_ISMOBILE && component === this.betDealerWinGroup) {
						randomX = (Math.random() * 3 + 2) / 10;//[0.2-0.5]
					} else {
						randomX = (Math.random() * 6 + 2) / 10;//[0.2-0.8]
					}

					randomY = (Math.random() * 6 + 2) / 10;

					let x = width * randomX;
					let y = height * randomY;
					let stagePoint = component.localToGlobal(x, y);
					if (isLarge) {
						Bet.instance.largeChipIn2(type, Number(key), this.chipComponent, stagePoint.x, stagePoint.y);
					} else {
						Bet.instance.smallChipIn(Number(key), this.chipComponent, stagePoint.x, stagePoint.y);
					}
					val--;
				}
			})
		})
	}

	/**
	 * 界面关闭时调用
	 */
	public onClose(): void {
	}
}