/**
 * Created by rockyl on 2019-04-09.
 */

import { Button } from "scilla-components/src";
import ScillaComponent from "scilla-components/src/base/ScillaComponent";
import { dynamic, Entity } from "scilla/src";
import { alien } from "../navigator/StackNavigator";
import { INavigatorViewBase } from "../navigator/VirtualNavigator";
import { setText, setRotation, getRotation } from "../transformUtils";
import { getRankURL, getRecordURL, getURL } from "../dialogs/ScoreDialogContent";

export default class SceneStart extends ScillaComponent implements INavigatorViewBase {
	doJoin: dynamic;
	getOrderStatus: dynamic;

	countTxt: Entity;
	startbtn: Entity;
	rankbtn: Entity;
	rulebtn: Entity;
	box: Entity;

	musiconbtn: Entity;
	musicoffbtn: Entity;
	onclick_music() {
		this.musicoffbtn.enabled = !this.musicoffbtn.enabled;
		this.musiconbtn.enabled = !this.musiconbtn.enabled;
		if (this.musiconbtn.enabled) {
			document.getElementById('bgmusic')['play']();
		} else {
			document.getElementById('bgmusic')['pause']();
		}
	}

	private INTERVAL = 3000;
	private STREN = 3;
	private FREQ = 5;
	private SHAK_TIMERS = 10;

	private _shakeTimes = -1;
	private _counter = -1;

	private _lastTime = -1;
	onUpdate() {
		if (Date.now() - this._lastTime > this.INTERVAL) {
			this._lastTime = Date.now();
			setRotation(this.box, this.STREN);
			this._shakeTimes = this.SHAK_TIMERS;
			this._counter = 0;
		}

		if (this._shakeTimes > 0) {
			if (this._counter <= 0) {
				this._shakeTimes--;
				setRotation(this.box, -getRotation(this.box))
				if (this._shakeTimes <= 0) {
					setRotation(this.box, 0);
				}
				this._counter = this.FREQ;
			} else {
				this._counter--;
			}
		}

	}

	updateCountFromNet(limit: number) {
		if (limit < 0)
			limit = 0;
		setText(this.countTxt, `剩余次数：${limit}`);
		console.log('updateCountFromNet', `剩余次数：${limit}`)
	}

	onErrorLimitFree(data) {
		console.log('onErrorLimitFree', data);
		if (data == '400005')
			setText(this.countTxt, `剩余次数：${window['CFG'].freeLimit}`);
		else
			setText(this.countTxt, `剩余次数：0`);
	}

	updateCountTxtFromDojoin() {
		let limit = 0;
		if (this.doJoin) {
			limit = this.doJoin.freeLimit;
		}
		if (limit < 0)
			limit = 0;
		setText(this.countTxt, `剩余次数：${limit}`);
		console.log('updateCountTxtFromDojoin', `剩余次数：${limit}`)
	}

	onAwake() {
		super.onAwake();
		this.broadcast('callApi', 1, 'rankInfo2', {
			weddingId: window['CFG'].weddingId,
			activityId: window['CFG'].activityId
		});

		this.broadcast('callApi', 1, 'limitTimes', {
			weddingId: window['CFG'].weddingId,
			activityId: window['CFG'].activityId
		});

		this._shakeTimes = 0;
		this._counter = 0;
		this._lastTime = -1;
		setRotation(this.box, 0);
	}

	onResponse_rankInfo2(data) {
		if (data.openPrize && data.score > 0) {//开奖了，都是线下奖品
			console.log('开奖了....');
			console.log('prizelist', JSON.stringify(window['CFG'].activity.prizeList));
			let prize;
			window['CFG'].activity.prizeList.forEach(p => {
				if (p.prizeType == data.prizeType)
					prize = p;
			});
			if (prize)
				console.log('中奖了', JSON.stringify(prize))
			else
				console.log('没有中奖')
			if (!window.localStorage.getItem(this.getKey())) {
				if (prize) //中奖了
					this.bubbling('showDialog', 'Prize', prize);
				else
					this.bubbling('showDialog', 'Alert', '您与奖品擦肩而过~');
			} else {
				console.log('已经弹窗过了', this.getKey())
			}

			window.localStorage.setItem(this.getKey(), '1')
		}
	}

	getKey() {
		return 'prizeShowed-' + window['CFG'].weixinUid + '-' + window['CFG'].weddingId + '-' + window['CFG'].activityId
	}

	initGameStage() {
		console.log('initGameStage')
	}

	onClick_startbtn() {
		this.startbtn.getComponent(Button).enabled = false;
		this.sendDojoin();
	}

	sendDojoin() {
		// if (window['getDuibaToken']) {
		// 	window['getDuibaToken']((tokenObj: any) => {
		// 		this.dojoinFunc(tokenObj.token);
		// 	}, (key: string, messageObj: any) => {
		// 		// this.onError(net);
		// 	});
		// } else {
		this.dojoinFunc();
		// }
	}

	dojoinFunc(token?) {
		this.broadcast('callApi', 1, 'doJoin', {
			activityId: window['CFG'].activityId,
			weddingId: window['CFG'].weddingId,
		});
	}

	onGotDojoin() {
		console.log('onGotDojoin', this.doJoin);
		this.startbtn.getComponent(Button).enabled = true;
		this.updateCountTxtFromDojoin();
		setTimeout(() => {
			if (localStorage.getItem('yylguide')) {
				this.bubbling('fuck', 'play');
			} else {
				this.bubbling('fuck', 'guide');
				localStorage.setItem('yylguide', '1')
			}

		}, 50);
	}

	onGotDojoinError(error) {
		this.startbtn.getComponent(Button).enabled = true;
		if (error === '400005') {
			this.bubbling('showToast', '活动还未开始\n敬请期待~');
		} else if (error === '400006') {
			this.bubbling('showToast', '活动已结束\n下次早点来哦~');
		} else if (error === '400002') {
			this.bubbling('showDialog', 'Alert', '您已经没有抽奖机会了');
		}
		else {
			this.bubbling('showDialog', 'Alert', '网络异常，请稍后再试~');
		}
		console.log('onGotDojoinError', error);
	}

	onClick_rulebtn() {
		console.log('onClick_rulebtn');
		this.bubbling('showDialog', 'Rule');
	}

	onClick_rankbtn() {
		window.location.href = getRankURL();
	}

	onClick_backbtn() {
		// console.log('onClick_backbtn');
		window.location.href = getURL()
	}

	onResponse_rank() {
		this.bubbling('fuck', 'result');
		this.rankbtn.getComponent(Button).enabled = true;
	}

	onClick_recordbtn() {
		// alert('onClick_recordbtn')
		window.location.href = getRecordURL();
		// globalEvent.emit('alert', {title: 'Success', content: 'You complete this puzzle', button: 'Next level'}, this.onAlertClose);
	}

	onDidEnter(last: string, action: alien.NavigatorAction, parameters: any): void {
		this.entity.enabled = true;
	}

	onDidLeave(next: string, action: alien.NavigatorAction, parameters: any): void {
		this.entity.enabled = false;
	}

	async onWillEnter(last: string, action: alien.NavigatorAction, parameters: any) {
	}

	async onWillLeave(next: string, action: alien.NavigatorAction, parameters: any) {
	}

	onWillMount(last: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
		return undefined;
	}

	onWillUnMount(next: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
		return undefined;
	}

}
