declare interface ChipConfig {
	value: number,
	color: number,
	bg: string
}
const chipConfig: ChipConfig[] = [
	{ value: 0.1, color: 0x93100e, bg: 'chip_r_t' },
	{ value: 0.5, color: 0x126ae4, bg: 'chip_b_t' },
	{ value: 1, color: 0x7630a6, bg: 'chip_p_t' },
	{ value: 5, color: 0x196b31, bg: 'chip_b_t' },
	{ value: 10, color: 0x7f781b, bg: 'chip_y_t' },
	{ value: 20, color: 0x6c431e, bg: 'chip_o_t' }
]
const CHIPSIZE = {
	SMALL: 1,
	LARGE: 2
}
class UI_Bet extends UIBaseComponent {
	private gtTipsGroup: eui.Group;
	private gtTipsBtn: eui.Button;
	private gtTips1: eui.Label;
	private gtTips2: eui.Label;
	private rateLabel: eui.Label;

	private chipGroup: eui.Group;
	private radioGroup: eui.RadioButtonGroup;
	private chipElements: eui.RadioButton[] = [];
	private clearBtn: eui.Button;
	private confirmBtn: eui.Button;
	private autoConfirmBtn: eui.Button;

	private thisTimeBet: eui.Label;
	private betEosText: eui.Label;
	private betEosCount: number = 0;
	private thisPhaseBet: eui.Label;
	private thisPhaseBetEosCount: number = 0;
	private thisPhaseBetEosText: eui.Label;
	private getBetGtLangText: eui.Label;
	private getBetGtCount: number = 0;
	private getBetGtText: eui.Label;
	private getBetGtLangText0: eui.Label;
	private getBetGtText0: eui.Label;

	private succChipNodePool: UI_ChipItem[] = [];
	private chipNodePool: UI_ChipItem[] = [];
	private otherChipNodePool: UI_ChipItem[] = [];
	public constructor() {
		super();
	}

	/**
	 * 绑定事件
	 */
	protected bindEvents(): void {
		super.bindEvents();
		mouse.setButtonMode(this.gtTipsBtn, true);
		mouse.setButtonMode(this.clearBtn, true);
		mouse.setButtonMode(this.confirmBtn, true);
		mouse.setButtonMode(this.autoConfirmBtn, true);
		this.clearBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClearBtn, this);
		this.confirmBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onConfirmBtn, this);
		this.autoConfirmBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onAutoConfirmBtn, this);
		this.gtTipsBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onGtTipsBtn, this)
	}

	/**
	 * 创建完成时调用
	 */
	protected onCreate(): void {
		super.onCreate();
		this.render();
		this.onLangChange();
	}

	/**
	 * 渲染UI时调用
	 */
	protected render(): void {
		this.autoConfirmBtn.visible = false;
		this.initRadioButtonWithGroup();
		this.renderBetEosText(0);
		this.renderPhaseBetEosText(0);
		this.renderGetBetGtText(0);
	}

	private renderBetEosText(count: number): void {
		this.betEosCount = count;
		this.betEosText.text = count.toString();
	}

	private renderPhaseBetEosText(count: number): void {
		this.thisPhaseBetEosCount = count;
		this.thisPhaseBetEosText.text = count.toString();
	}

	//下注成功，更新数据
	transBetEosToPhase(): void {
		// this.resetChipElements();
		this.succChipNodePool = this.succChipNodePool.concat(this.chipNodePool);
		this.chipNodePool = [];

		this.renderPhaseBetEosText(NP.plus(this.thisPhaseBetEosCount, this.betEosCount));
		this.renderGetBetGtText(NP.plus(this.getBetGtCount, NP.times(Bet.instance.rate, this.betEosCount)));
		this.renderBetEosText(0);
	}

	private renderGetBetGtText(count: number): void {
		this.getBetGtCount = count;
		this.getBetGtText.text = this.getBetGtText0.text = count.toString();
	}

	private onGtTipsBtn(ev: egret.TouchEvent): void {
		AudiosMgr.instance.playButtonClick();
		EOS_VUE.$showGt();
	}

	private onClearBtn(ev: egret.TouchEvent): void {
		AudiosMgr.instance.playButtonClick();
		this.clearChip();
	}

	private clearSuccChip(): void {
		this.succChipNodePool.forEach(node => {
			node.parent.removeChild(node);
		})
		Bet.instance.setChipNodes(this.succChipNodePool);
		this.succChipNodePool = [];
	}

	private clearOtherChip(): void {
		this.otherChipNodePool.forEach(node => {
			node.parent.removeChild(node);
		})
		Bet.instance.setChipNodes(this.otherChipNodePool);
		this.otherChipNodePool = [];
	}

	private clearChip(): void {
		this.chipNodePool.forEach(node => {
			node.parent.removeChild(node);
		})
		Bet.instance.setChipNodes(this.chipNodePool);
		this.chipNodePool = [];

		this.renderBetEosText(0);
	}

	/**
	 * 获取此次游戏的上报数据
	 */
	private getChipMemo(): string {
		let pbbetArr: any[] = [];
		let memoArr: number[] = [];
		let memo = '';
		let counterMap = {}

		this.chipNodePool.forEach(chip => {
			let type = chip.type;
			if (!memoArr[type]) {
				memoArr[type] = 0;
				pbbetArr[type] = {
					type: type,
					account: UserMgr.instance.account.name,
					counter: [],
					total: '0.0000 EOS'
				}
				counterMap[type] = {}
			}
			if (!counterMap[type][chip.chipValue]) {
				counterMap[type][chip.chipValue] = 0;
			}

			counterMap[type][chip.chipValue]++;
			memoArr[type] = NP.plus(memoArr[type], chip.chipValue);
			pbbetArr[type].total = `${memoArr[type].toFixed(4)} EOS`;
		})

		Object.keys(counterMap).forEach(counterKey => {
			let counter = counterMap[counterKey];
			Object.keys(counter).forEach(key => {
				pbbetArr[counterKey].counter.push({
					key: NP.times(Number(key), 100),
					val: counter[key]
				})
			})
		})

		DEBUG && console.log('pbbetArr:', pbbetArr);

		memoArr.forEach((value, index) => {
			memo += `|${index}|${NP.times(value, 10000)}`;
		})

		return memo;
	}

	allowBet(allow: boolean): void {
		this.confirmBtn.enabled = allow;
	}

	//user confirm bet
	private onConfirmBtn(ev: egret.TouchEvent): void {
		AudiosMgr.instance.playButtonClick();
		let {Bet} = Lang.instance.lang();
		if (UserMgr.instance.isLogin()) {
			if (this.betEosCount > 0) {
				// 超过100EOS
				if (this.betEosCount > 100) {
					AlertMgr.instance.showAlert(Bet.moreBet);
					return
				}
				let memo = this.getChipMemo();

				DEBUG && console.log('memo:', memo);
				// 下注
				EOS_VUE.$doDeposit(Index.instance.gameInfo.id, this.betEosCount, memo);

				this.allowBet(false);
				
				Index.instance.allowBet(false);
			} else {
				AlertMgr.instance.showAlert(Bet.noBet);
			}
		}
	}

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

		if (UserMgr.instance.isLogin()) {
			Auto.instance.openAutoView();
		}
	}

	private initRadioButtonWithGroup(): void {
		this.radioGroup = new eui.RadioButtonGroup();
		this.radioGroup.addEventListener(eui.UIEvent.CHANGE, this.radioChangeHandler, this);
		chipConfig.forEach((config, index) => {
			let rdb: eui.RadioButton = new eui.RadioButton();
			rdb.skinName = chipItem;
			rdb.label = config.value.toString();
			(<eui.Label>rdb['labelDisplay']).textColor = config.color;
			(<eui.Image>rdb['chipItemImage']).source = config.bg;
			rdb.value = config.value;
			rdb.selected = config.value === 1;//默认选项
			rdb.y = config.value === 1 ? -40 : 0;
			mouse.setButtonMode(rdb, true);
			rdb.group = this.radioGroup;
			rdb.x = 10 + rdb.width * index;
			this.chipElements.push(rdb);
			this.chipGroup.addChild(rdb);
		})
		Bet.instance.chipValue = 1
	}
	private radioChangeHandler(evt: eui.UIEvent): void {
		AudiosMgr.instance.playButtonClick();

		var radioGroup: eui.RadioButtonGroup = evt.target;
		this.chipElements.forEach(radio => {
			egret.Tween.removeTweens(radio);
			if (radio == radioGroup.selection) {
				if (radio.y == -40) return;
				egret.Tween.get(radio).to({ y: -40 }, 250, egret.Ease.sineIn);
			} else {
				if (radio.y == 0) return;
				egret.Tween.get(radio).to({ y: 0 }, 250, egret.Ease.sineIn);
			}
		})
		Bet.instance.chipValue = radioGroup.selectedValue;
	}

	resetChipElements(): void {
		this.chipElements.forEach(radio => {
			egret.Tween.removeTweens(radio);
			if (radio.y == 0) return;
			egret.Tween.get(radio).to({ y: 0 }, 250, egret.Ease.sineIn);
		})
		this.radioGroup.selectedValue = null;
	}

	getLocalPoint(childNode: egret.DisplayObjectContainer): egret.Point {
		let x: number = childNode.width / 2;
		let y: number = childNode.height / 2;
		while (childNode != this) {
			x += childNode.x;
			y += childNode.y;

			childNode = childNode.parent;
		}

		return new egret.Point(x, y);
	}

	private getRadioButton(value: number): eui.RadioButton {
		let radios = this.chipElements.filter(radio => {
			return radio.value == value;
		})

		return radios && radios[0];
	}

	largeChipIn(contaniner: egret.DisplayObjectContainer, stageX: number, stageY: number, chipNode: UI_ChipItem): void {
		let start = this.radioGroup.selection || this.getRadioButton(chipNode.chipValue);
		this.validateNow()
		let localStart = start.localToGlobal(0, 0);
		let localEnd = new egret.Point(stageX, stageY);

		contaniner.addChild(chipNode);
		this.chipNodePool.push(chipNode);
		chipNode.x = localStart.x;
		chipNode.y = localStart.y;

		egret.Tween.get(chipNode).to({ x: localEnd.x, y: localEnd.y }, 300, egret.Ease.sineIn);

		this.renderBetEosText(NP.plus(this.betEosCount, chipNode.chipValue));
	}

	largeChipIn2(contaniner: egret.DisplayObjectContainer, stageX: number, stageY: number, chipNode: UI_ChipItem): void {
		let start = this.radioGroup.selection || this.getRadioButton(chipNode.chipValue);
		this.validateNow()
		let localStart = start.localToGlobal(0, 0);
		let localEnd = new egret.Point(stageX, stageY);

		contaniner.addChild(chipNode);
		this.succChipNodePool.push(chipNode);
		chipNode.x = localStart.x;
		chipNode.y = localStart.y;

		egret.Tween.get(chipNode).to({ x: localEnd.x, y: localEnd.y }, 300, egret.Ease.sineIn);

		this.renderBetEosText(NP.plus(this.betEosCount, chipNode.chipValue));
	}

	smallChipIn(contaniner: egret.DisplayObjectContainer, stageX: number, stageY: number, chipNode: UI_ChipItem): void {
		let start = this.getRadioButton(chipNode.chipValue);
		if (start == null) return;

		let localStart = start.localToGlobal(0, 0);
		let localEnd = new egret.Point(stageX, stageY);

		contaniner.addChild(chipNode);
		this.otherChipNodePool.push(chipNode);
		chipNode.x = localStart.x;
		chipNode.y = localStart.y;

		egret.Tween.get(chipNode).to({ x: localEnd.x, y: localEnd.y }, 300, egret.Ease.sineIn);
	}

	// render gamestart
	renderGameStart(): void {
		this.confirmBtn.enabled = true;
		// this.resetChipElements();
		this.clearOtherChip();
		this.clearSuccChip();
		this.clearChip();

		this.renderBetEosText(0);
		this.renderPhaseBetEosText(0);
		this.renderGetBetGtText(0);
	}

	// render lotteryInfo
	renderLotteryInfo(): void {
		this.clearChip();
		this.confirmBtn.enabled = false;
		// if (this.radioGroup.selectedValue) {
		// 	egret.Tween.get(this.radioGroup.selection).to({ y: 0 }, 250, egret.Ease.sineIn);
		// 	this.radioGroup.selectedValue = null;
		// }
	}

	updateRate(): void {
		let {gtTips2} = Lang.instance.lang().Bet;
		this.gtTips2.text = gtTips2.replace(/\?/g, `${Bet.instance.rate}`);
		this.rateLabel.text = `x${Bet.instance.rate}`;
	}

	/**
	 * 改变语言时调用
	 */
	protected onLangChange(ev?: egret.Event): void {
		let {clear, confirmBet, autoBet, thisTime, thisPhase, getBetGtLangText, gtTips1, gtTips2 } = Lang.instance.lang().Bet;

		this.clearBtn.label = clear;
		this.confirmBtn.label = confirmBet;
		this.autoConfirmBtn.label = autoBet;
		this.thisTimeBet.text = thisTime;
		this.thisPhaseBet.text = thisPhase;
		this.getBetGtLangText.text = this.getBetGtLangText0.text = getBetGtLangText;
		this.gtTips1.text = gtTips1;
		this.gtTips2.text = gtTips2.replace(/\?/g, `${Bet.instance.rate}`);
		this.rateLabel.text = `x${Bet.instance.rate}`;
	}

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