const saveKey = "DataKey_Cocos_FT11";
const BaseUI = require('BaseUI');
cc.Class({

	extends: BaseUI,

	properties: {
		audEnter: cc.AudioClip,
		audMove: cc.AudioClip,
		audMerge: cc.AudioClip,
		audClick: cc.AudioClip,
		pfbItemAnswer: cc.Prefab,
		pfbItemQuestion: cc.Prefab,
		layerOver: cc.Prefab,
	},

	// 生命周期 onLoad
	onLoad() {
		this._super();
		this.initNodes();
		this.initSceneData();
		this.initSize();
	},
	initNodes() {

	},

	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 dataJson = '{"questionList":[{"questionAudio":"http://staging-teach.cdn.ireadabc.com/d2a9d8815d0370dc3b9aa18987dee584.mp3","questionText":"标题1","optionList":[{"text":"题干文本1","optionDragonBone":{"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/48b884b3c7b3a717f6e4b055f490a1f1.json","name":"walkingfish_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/608b2c5f85297f0b7930325733b7bea9.json","name":"walkingfish_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/ecfd66f932659635f5b66642378d826b.png","name":"walkingfish_tex.png"},"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/4e267b9c0b58ebb153bfc0ae520cb7fe.mp3"},{"text":"题干文本2","optionDragonBone":{"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"},"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/90fd9908a33a3d087ac53e6f7d794c18.mp3"},{"text":"题干文本3","optionDragonBone":{"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"},"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/7ee85feaee06931e85cd0dd4ee64eeb1.mp3"},{"text":"题干文本45","optionDragonBone":{"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"},"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/248e684b0680d5ae39bacab7242b49f0.mp3"}]},{"questionAudio":"http://staging-teach.cdn.ireadabc.com/1d192b1cb2f2b1864ca55e903711081a.mp3","questionText":"","optionList":[{"text":"题干文本","optionDragonBone":{"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"},"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/d2a9d8815d0370dc3b9aa18987dee584.mp3"},{"text":"题干文本","optionDragonBone":{"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"},"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/4e267b9c0b58ebb153bfc0ae520cb7fe.mp3"},{"text":"题干文本","optionDragonBone":{"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"},"skeJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/efbe7f9b1ab7d7bc90ff13ac730882cc.json","name":"NewProject_2_ske.json"},"texJsonData2":{"url":"http://staging-teach.cdn.ireadabc.com/adb8e6c461753848a4650c74dc21c522.json","name":"NewProject_2_tex.json"},"texPngData2":{"url":"http://staging-teach.cdn.ireadabc.com/b132de0ee0425657eb64ed0b4f5f70a8.png","name":"NewProject_2_tex.png"}},"optionAudio":"http://staging-teach.cdn.ireadabc.com/90fd9908a33a3d087ac53e6f7d794c18.mp3"}]}]}';
		let data = JSON.parse(dataJson);
		return data;
	},

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

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

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

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


	loadEnd() {
		GameData.questionIndex = 0;
		this.initData();

		this.startGame();
	},

	initData() {
		// 所有全局变量 默认都是null 
		GameData.audioCount = 0;

		let optionList = this.data.questionList[GameData.questionIndex].optionList;
		this.optionList = [];
		for (let i = 0; i < optionList.length; i++) {
			this.optionList[i] = i;
		}
		GameData.isMoving = false;
		this.initQuestionAndAnswer();
		this.initTitle();
		this.updateBtnStatus();
	},

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

	initTitle() {
		let label = this.nodeDict.labTitle.getComponent(cc.Label);
		label.string = this.data.questionList[GameData.questionIndex].questionText;
		label._forceUpdateRenderData();
		if (this.nodeDict.labTitle.width > 567) {
			this.nodeDict.labTitle.scale = 567 / this.nodeDict.labTitle.width
		}
	},

	// 初始化题干以及选项
	initQuestionAndAnswer() {
		let optionList = this.data.questionList[GameData.questionIndex].optionList;
		let answerIndexs = [1, 2, 3];
		if (optionList.length == 4) {
			answerIndexs = [1, 2, 3, 4];
		}
		for (let i = 0; i < optionList.length; i++) {
			let question = cc.instantiate(this.pfbItemQuestion);
			question.parent = this.nodeDict.nodQuestionParent;
			question.x = this.getItemX(optionList, i);
			let ItemQuestion = question.getComponent('ItemQuestion');
			ItemQuestion.setInfo(optionList[i], i, this);
			ItemQuestion.setGray();

			let answer = cc.instantiate(this.pfbItemAnswer);
			answer.parent = this.nodeDict.nodAnswerParent;

			let index = Math.floor(Math.random() * answerIndexs.length)
			answer.x = this.getItemX(optionList, answerIndexs[index] - 1);
			answerIndexs.splice(index, 1);

			answer.getComponent('ItemAnswer').setInfo(optionList[i], i, this);
		}
	},
	getItemX(optionList, index) {
		let itemWidth = 300;
		let space = 10;
		let x = index * (itemWidth + space) - 1.5 * (itemWidth + space);
		if (optionList.length == 3) {
			space = 56;
			x = index * (itemWidth + space) - 1 * (itemWidth + space);
		}
		return x;
	},


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

	playAudioQuestion(isBtn) {
		GameData.audioCount++;
		let url = this.data.questionList[GameData.questionIndex].questionAudio;
		// url = 'http://127.0.0.1/iamflying.mp3';
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				console.log(err)
				this.showRandomQuestion();
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				GameData.audioCount--;
				if (!isBtn) {
					this.showRandomQuestion();
				}
			})
		});
	},
	playAudioMove() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audMove, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
		})
	},
	playAudioMerge() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audMerge, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
		})
	},

	// 随机亮起一个题干
	showRandomQuestion() {
		GameData.currOptionIndex = this.optionList[Math.floor(Math.random() * this.optionList.length)]
		let question = this.nodeDict.nodQuestionParent.children[GameData.currOptionIndex];
		let ItemQuestion = question.getComponent('ItemQuestion');
		ItemQuestion.setNormal();
		ItemQuestion.showQipao();
		ItemQuestion.playAudioOption();
	},

	showNext(index) {
		for (let i = 0; i < this.optionList.length; i++) {
			if (this.optionList[i] == index) {
				this.optionList.splice(i, 1);
				break;
			}
		}
		if (this.optionList.length == 0) {
			this.checkOver();
		} else {
			this.showRandomQuestion();
		}
	},

	checkOver() {
		if (GameData.questionIndex != this.data.questionList.length - 1) {
			return;
		}
		let node = cc.instantiate(this.layerOver);
		node.parent = this.node;
	},

	moveToQuestion(ItemAnswer) {
		GameData.isMoving = true;
		let index = ItemAnswer.index;
		let question = this.nodeDict.nodQuestionParent.children[index];
		let pos = this.nodeDict.nodQuestionParent.convertToWorldSpaceAR(question.position);
		pos = this.nodeDict.nodAnswerParent.convertToNodeSpaceAR(pos);
		this.playAudioMove();
		cc.tween(ItemAnswer.node)
			.to(0.8, { position: pos })
			.call(() => {
				question.getComponent('ItemQuestion').setChooseRight(ItemAnswer.dragonBone, ItemAnswer.animationName);
				ItemAnswer.node.destroy();
				this.getComponent(cc.Animation).play('animLight');
				this.playAudioMerge();
				cc.tween(question)
					.delay(3)
					.call(() => {
						question.getComponent('ItemQuestion').stopRightAnimation();
						this.getComponent(cc.Animation).play('animDark');
						GameData.isMoving = false;
					})
					.start()
			})
			.start()
	},

	updateBtnStatus() {
		if (GameData.questionIndex == 0) {
			this.nodeDict.btnLast.getComponent(cc.Button).interactable = false;
		} else {
			this.nodeDict.btnLast.getComponent(cc.Button).interactable = true;
		}
		if (GameData.questionIndex == this.data.questionList.length - 1) {
			this.nodeDict.btnNext.getComponent(cc.Button).interactable = false;
		} else {
			this.nodeDict.btnNext.getComponent(cc.Button).interactable = true;
		}
	},

	onTurnLast() {
		this.nodeDict.nodAnswerParent.destroyAllChildren();
		this.nodeDict.nodQuestionParent.destroyAllChildren();
		cc.audioEngine.stopAll();
		GameData.questionIndex--;
		this.initData();
		this.playAudioQuestion();
	},
	onReplay() {
		this.nodeDict.nodAnswerParent.destroyAllChildren();
		this.nodeDict.nodQuestionParent.destroyAllChildren();
		cc.audioEngine.stopAll();
		this.initData();
		this.startGame();
	},
	onTurnNext() {
		this.nodeDict.nodAnswerParent.destroyAllChildren();
		this.nodeDict.nodQuestionParent.destroyAllChildren();
		cc.audioEngine.stopAll();
		GameData.questionIndex++;
		this.initData();
		this.startGame();
	},

	buttonListener(button) {
		if (button.node.name == 'btnTitle') {
			if (GameData.audioCount != 0) {
				return;
			}
			this.playAudioQuestion(true);
		} else if (button.node.name == 'btnLast') {
			this.onTurnLast();
		} else if (button.node.name == 'btnReplay') {
			this.onReplay();
		} else if (button.node.name == 'btnNext') {
			this.onTurnNext();
		}
	},

});
