/**
 * 胜率逻辑
 */
class Rate {
	private static _instance: Rate;
	static get instance(): Rate {
		if (!this._instance) {
			this._instance = new Rate();
		}
		return this._instance;
	}

	public uiRate: UI_Rate;
	public uiRateDetail: UI_RateDetail;
	private type: number[] = [0, 0, 0, 0, 0]
	public rateHistory: { type: number[], result: any };

	public constructor() {

	}

	openRateView(): void {
		if (this.uiRate) {
			this.uiRate.visible = true;
			this.uiRate.renderHistory();
		} else {
			this.uiRate = UIController.instance.popupView<UI_Rate>(UI_Rate);
		}
	}
	openRateDetailView(index: number): void {
		if (this.uiRateDetail) {
			this.uiRateDetail.visible = true;
		} else {
			this.uiRateDetail = UIController.instance.popupView<UI_RateDetail>(UI_RateDetail);
			this.uiRateDetail.x = (GameMgr.instance.main.stage.stageWidth - this.uiRateDetail.width) / 2
			this.uiRateDetail.y = GAME_ISMOBILE ? 160 : 26
		}
		this.uiRateDetail.renderDetail(index);
	}
	/**
	 * 0:庄,1:闲,2:和,3:庄对,4:闲对
	 */
	renderRateHistory(data: any[]) {
		data.sort(function (a, b) {
			return a.reveal_block_num - b.reveal_block_num;
		})
		if (GAME_ISMOBILE) {
			data.splice(0, data.length - 50)
		}
		let {type} = this
		this.rateHistory = { type, result: data }
		//winner 0:闲,1:庄,2:和
		data.forEach(item => {
			item.winner === 0 && (type[1] += 1)
			item.winner === 1 && (type[0] += 1)
			item.winner === 2 && (type[2] += 1)
			item.banker_pair && (type[3] += 1)
			item.player_pair && (type[4] += 1)
		})
		this.uiRate && this.uiRate.renderHistory();
	}
	shiftRateHistory(item) {
		let {type} = this.rateHistory;

		item.winner === 0 && (type[1] -= 1);
		item.winner === 1 && (type[0] -= 1);
		item.winner === 2 && (type[2] -= 1);
		item.banker_pair && (type[3] -= 1);
		item.player_pair && (type[4] -= 1);
	}
	pushRateHistory(data) {
		let {id, reveal_info} = data;

		let item = {
			id: id,
			block_info: reveal_info.blockInfo,
			winner: reveal_info.win,
			banker_pair: reveal_info.bankerPair ? 1 : 0,
			player_pair: reveal_info.playerPair ? 1 : 0,
			reveal_block_num: reveal_info.revealBlockNum
		}

		let {rateHistory} = this
		let {type, result} = rateHistory
		item.winner === 0 && (type[1] += 1)
		item.winner === 1 && (type[0] += 1)
		item.winner === 2 && (type[2] += 1)
		item.banker_pair && (type[3] += 1)
		item.player_pair && (type[4] += 1)

		let historyMax = GAME_ISMOBILE ? 50 : 60

		if (result.length >= historyMax) {
			if (GAME_ISMOBILE) {
				this.shiftRateHistory(result.shift())
			} else {
				result.splice(0, 6).forEach(item => this.shiftRateHistory(item));
			}

		}
		result.push(item)

		this.uiRate && this.uiRate.renderHistory();
	}

	closeRateView(): void {
		if (this.uiRate) this.uiRate.visible = false;
	}

	getRateView(): UI_Rate {
		return this.uiRate = UIController.instance.createView<UI_Rate>(UI_Rate);
	}
}