const saveKey = "DataKey_Cocos_ET18";
const BaseUI = require('BaseUI');
import { DefaultData } from './DefaultData';
import EventMgr from './EventMgr';
cc.Class({

	extends: BaseUI,

	properties: {
		pfbItem: cc.Prefab,
		pfbItemWord: cc.Prefab,
		pfbItemCollisionEffect: cc.Prefab,
		layerOver: cc.Prefab,
		spfAudio: [cc.SpriteFrame],
		spfLeft: [cc.SpriteFrame],
		spfRight: [cc.SpriteFrame],
		audEnter: cc.AudioClip,
		audReplay: cc.AudioClip,
		audWelldone: cc.AudioClip,
		audGoodjob: cc.AudioClip,
	},

	// 生命周期 onLoad
	onLoad() {
		this._super();
		this.initNodes();
		this.initSceneData();
		this.initSize();
		GameData.scene = this;
	},
	initNodes() {
		this.sprAudio = this.nodeDict.sprAudio.getComponent(cc.Sprite);
	},

	onEnable() {

	},

	onDisable() {

	},

	_resList: null,
	initSceneData() {
		this._resList = [];
		window.GameData = {};
	},

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {

	},


	// 生命周期 start
	start() {
		this.getData((data) => {
			console.log('data:', data);
			this.data = data;
			if (data) {
				this.preloadItem()
			}
		})
	},

	getData(cb) {
		// 获取数据
		if (window.courseware) {
			const getData = window.courseware.getData;
			getData((data) => {
				data = data || this.getDefaultData();
				cb && cb(data);
			}, saveKey);
		} else {
			cb && cb(this.getDefaultData());
		}
	},

	getDefaultData() {
		let data = DefaultData;
		return data;
	},

	preloadItem() {
		this.addPreloadItem();
		this.preload();
	},

	addPreloadItem() {
		this._resList.push({ url: this.data.questionAudio });
		for (let i = 0; i < this.data.questionList.length; i++) {
			for (let j = 0; j < this.data.questionList[i].optionList.length; j++) {
				this._resList.push({ url: this.data.questionList[i].optionList[j].optionAudio });
			}
		}
	},

	preload() {
		cc.assetManager.loadAny(this._resList, null, null, (err, data) => {
			this.loadEnd();
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}

			cc.debug.setDisplayStats(false);
		});
	},


	loadEnd() {
		if (this.data.questionList.length === 0) {
			return;
		}
		GameData.questionIndex = 0;
		this.questionList = [];
		for (let i = 0; i < this.data.questionList.length; i++) {
			this.questionList.push(i);
		}

		this.initData();
		this.updateBtnStatus();
		this.startGame();
	},

	initData() {
		let manager = cc.director.getCollisionManager();
		manager.enabled = true;
		this.nodeDict.layerParts.destroyAllChildren();
		this.nodeDict.layerParts.getComponent(cc.Layout).enabled = true;
		this.audioSpfIndex = 0;
		GameData.audioCount = 0;
		this.initTitle();
		this.initOptions();
	},

	startGame() {
		this.playAudioEnter();
	},

	initTitle() {
		let label = this.nodeDict.labTitle.getComponent(cc.Label);
		label.string = this.data.questionText;
		label._forceUpdateRenderData();
		if (this.nodeDict.labTitle.width > 290) {
			this.nodeDict.labTitle.scale = 290 / this.nodeDict.labTitle.width
		}
		this.nodeDict.nodBgTitle.on('touchstart', () => {
			GameData.audioCount++;
			let url = this.data.questionAudio;
			// url = 'http://127.0.0.1/iamflying.mp3';
			cc.assetManager.loadRemote(url, null, (err, clip) => {
				if (err) {
					console.log(err)
					return;
				}
				let id = cc.audioEngine.play(clip, false, 1);
				cc.audioEngine.setFinishCallback(id, () => {
					if (!cc.isValid(this)) {
						return;
					}
					GameData.audioCount--;
				})
			});
		});
	},

	initOptions() {
		for (let i = 0; i < this.data.questionList[GameData.questionIndex].optionList.length; i++) {
			// this._resList.push({ url: this.data.questionList[GameData.questionIndex].optionList[i].optionAudio });
			let node = cc.instantiate(this.pfbItem);
			node.parent = this.nodeDict.layerParts;
			node.getComponent('ItemPart').init(i, this.data.questionList[GameData.questionIndex].optionList[i], this);
		}
		this.scheduleOnce(() => {
			this.nodeDict.layerParts.getComponent(cc.Layout).enabled = false;
		})
	},

	playAudioEnter() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audEnter, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
		})
	},

	updateBtnStatus() {
		if (this.data.questionList.length === 1) {
			this.nodeDict.btnLast.active = false;
			this.nodeDict.btnNext.active = false;
			return;
		}
		if (GameData.questionIndex == 0) {
			this.nodeDict.btnLast.getComponent(cc.Sprite).spriteFrame = this.spfLeft[0];
		} else {
			this.nodeDict.btnLast.getComponent(cc.Sprite).spriteFrame = this.spfLeft[1];
		}
		if (GameData.questionIndex == this.data.questionList.length - 1) {
			this.nodeDict.btnNext.getComponent(cc.Sprite).spriteFrame = this.spfRight[0];
		} else {
			this.nodeDict.btnNext.getComponent(cc.Sprite).spriteFrame = this.spfRight[1];
		}
	},

	checkDone(length, pos) {
		if (length < this.data.questionList[GameData.questionIndex].optionList.length) {
			return;
		}
		for (let i = 0; i < this.questionList.length; i++) {
			if (this.questionList[i] === GameData.questionIndex) {
				this.questionList.splice(i, 1);
				i--;
			}
		}
		this.nodeDict.layerParts.destroyAllChildren();
		let node = cc.instantiate(this.pfbItemWord);
		node.parent = this.nodeDict.layerParts;
		node.x = 0;
		node.y = pos.y;
		node.getComponent('ItemWord').init(this.data.questionList[GameData.questionIndex]);
		this.showCollisionEffect(pos);

		this.showLayerDone();
	},
	showLayerDone() {
		this.nodeDict.layerDone.active = true;
		this.nodeDict.layerDone.scale = 0;
		cc.tween(this.nodeDict.layerDone)
			.to(0.25, { scale: 1.05 })
			.to(0.1, { scale: 1 })
			.call(() => {
				this.onBtnClickAudio(() => {
					this.playAudioGoodjob();
				});
			})
			.start()
	},
	playAudioGoodjob() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audGoodjob, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
			this.checkOver();
		})
	},
	resetDate() {
		this.nodeDict.layerDone.active = false;
		cc.audioEngine.stopAll();
		this.initData();
		this.updateBtnStatus();
	},
	onTurnLast() {
		if (GameData.audioCount != 0) {
			return;
		}
		GameData.questionIndex--;
		this.resetDate();
	},
	onReplay() {
		if (GameData.audioCount != 0) {
			return;
		}
		this.resetDate();
		this.playAudioReplay();
	},
	onTurnNext() {
		if (GameData.audioCount != 0) {
			return;
		}
		GameData.questionIndex++;
		this.resetDate();
	},

	buttonListener(button) {
		if (button.node.name == 'btnTitle') {
			if (GameData.audioCount != 0) {
				return;
			}
			this.playAudio()
		} else if (button.node.name == 'btnLast') {
			if (this.nodeDict.btnLast.getComponent(cc.Sprite).spriteFrame === this.spfLeft[0]) {
				return;
			}
			this.onTurnLast();
		} else if (button.node.name == 'btnReplay') {
			this.onReplay();
		} else if (button.node.name == 'btnNext') {
			if (this.nodeDict.btnNext.getComponent(cc.Sprite).spriteFrame === this.spfRight[0]) {
				return;
			}
			this.onTurnNext();
		} else if (button.node.name == 'btnAudio') {
			this.onBtnClickAudio();
		}
	},
	playAudioReplay() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audReplay, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
		})
	},
	changeAudioSpfCb() {
		this.sprAudio.spriteFrame = this.spfAudio[this.audioSpfIndex];
		this.audioSpfIndex++;
		this.audioSpfIndex = this.audioSpfIndex % 3;
	},
	onBtnClickAudio(cb) {
		this.sprAudio.spriteFrame = this.spfAudio[0];
		this.unschedule(this.changeAudioSpfCb)
		this.schedule(this.changeAudioSpfCb, 0.2)
		this.playAudio(() => {
			cb && cb();
			this.unschedule(this.changeAudioSpfCb)
			this.sprAudio.spriteFrame = this.spfAudio[2];
		});
	},

	playAudio(cb) {
		GameData.audioCount++;
		let url = this.data.questionList[GameData.questionIndex].audio;
		// url = 'http://127.0.0.1/iamflying.mp3';
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				console.log(err)
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				if (!cc.isValid(this)) {
					return;
				}
				GameData.audioCount--;
				cb && cb();
			})
		});
	},

	showCollisionEffect(pos) {
		let node = cc.instantiate(this.pfbItemCollisionEffect);
		node.parent = this.nodeDict.layerParts;
		node.position = pos;
		node.getComponent(cc.Animation).play();
		this.scheduleOnce(() => {
			if (cc.isValid(node)) {
				node.destroy();
			}
		}, 2)
	},

	checkOver() {
		if (this.questionList.length !== 0) {
			return;
		}
		if (this.gameOver) {
			return;
		}
		this.gameOver = true;
		this.showGameOver();
	},

	showGameOver() {
		let node = cc.instantiate(this.layerOver);
		node.parent = this.node;
	},
});
