const saveKey = "DataKey_Cocos_FT07";
cc.Class({

	extends: cc.Component,

	properties: {
		audEnter: cc.AudioClip,
		audReady: cc.AudioClip,
		audGo: cc.AudioClip,
		audNewQuestion: cc.AudioClip,
		audChoose: cc.AudioClip,
		audChooseRight: cc.AudioClip,
		audChooseWrong: cc.AudioClip,
		audTryAgain: cc.AudioClip,
		pfbLayerResult: cc.Prefab,
		pfbLayerOver: cc.Prefab,
		pfbItemCoaches: [cc.Prefab],
		spfAudio: [cc.SpriteFrame],
	},

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

	},
	initNodes() {
		let bg = this.node.getChildByName('bg');
		let question = bg.getChildByName('question');
		this.labWhite = question.getChildByName('labWhite').getComponent(cc.Label);
		this.labRed = question.getChildByName('labRed').getComponent(cc.Label);
		this.right = bg.getChildByName('right');
		this.left = bg.getChildByName('left');
		this.animationLeft = this.left.getComponent(cc.Animation);
		this.animationRight = this.right.getComponent(cc.Animation);
		this.labWordRight = this.right.getChildByName('word').getComponent(cc.Label);
		this.labWordLeft = this.left.getChildByName('word').getComponent(cc.Label);
		this.sprAudioLeft = bg.getChildByName('btnAudioLeft').getComponent(cc.Sprite);
		this.sprAudioRight = bg.getChildByName('btnAudioRight').getComponent(cc.Sprite);

		let ui = bg.getChildByName('ui');
		this.red = ui.getChildByName('red');
		this.yellow = ui.getChildByName('yellow');
		this.blue = ui.getChildByName('blue');
	},

	onEnable() {

	},

	onDisable() {

	},

	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	initSceneData() {
		this._imageResList = [];
		this._jsonResList = [];
		this._audioResList = [];
		this._animaResList = [];
		window.GameData = {};
		GameData.questionIndex = 0;
	},

	_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 = '{"contentObj":{"version":"1.1","key":"DataKey_Cocos_Test","dataArray":[{"letter":"a","text1":"apple","text2":"cat","isRight":false,"shortAudio_url":"","image_url":"","isRight1":true},{"letter":"b","text1":"dear","text2":"bear","isRight":false,"shortAudio_url":"","image_url":"","isRight2":true},{"letter":"a","text1":"apple","text2":"cat","isRight":false,"shortAudio_url":"","image_url":"","isRight1":true,"isRight2":false}]}}';
		let data = JSON.parse(dataJson);
		return data;
	},

	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadDragonBone();
		// this.addPreloadAnima();
		this.preload();
	},

	addPreloadDragonBone() {
		for (let i = 0; i < this.data.contentObj.dataArray.length; i++) {
			if (this.data.contentObj.dataArray[i].tex_png) {
				this._imageResList.push({ url: this.data.contentObj.dataArray[i].tex_png });
			}
			if (this.data.contentObj.dataArray[i].ske_json) {
				this._jsonResList.push({ url: this.data.contentObj.dataArray[i].ske_json });
			}
			if (this.data.contentObj.dataArray[i].tex_json) {
				this._jsonResList.push({ url: this.data.contentObj.dataArray[i].tex_json });
			}
		}
	},

	addPreloadImage() {
		// for (let i = 0; i < this.data.contentObj.dataArray.length; i++) {
		// 	if(this.data.contentObj.dataArray[i].image_url){
		// 		this._imageResList.push({ url: this.data.contentObj.dataArray[i].image_url });
		// 	}
		// }
	},

	addPreloadAudio() {
		for (let i = 0; i < this.data.contentObj.dataArray.length; i++) {
			if (this.data.contentObj.dataArray[i].shortAudio_url) {
				this._audioResList.push({ url: this.data.contentObj.dataArray[i].shortAudio_url });
			}
			if (this.data.contentObj.dataArray[i].shortAudio_url2) {
				this._audioResList.push({ url: this.data.contentObj.dataArray[i].shortAudio_url2 });
			}
			if (this.data.contentObj.dataArray[i].shortAudio_url3) {
				this._audioResList.push({ url: this.data.contentObj.dataArray[i].shortAudio_url3 });
			}
			if (this.data.contentObj.dataArray[i].shortAudio_url4) {
				this._audioResList.push({ url: this.data.contentObj.dataArray[i].shortAudio_url4 });
			}
		}
	},

	addPreloadAnima() {

	},

	preload() {
		const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList).concat(this._jsonResList);
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {
			this.loadEnd();
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}

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


	loadEnd() {
		this.initData();

		this.initLabelReady();
		this.initYaoGan();
		this.playAudioEntrer();
	},

	initData() {
		// 所有全局变量 默认都是null 
		GameData.questionList = [];
		for (let i = 0; i < this.data.contentObj.dataArray.length; i++) {
			GameData.questionList[i] = false;
		}
	},

	initLabelReady() {
		this.labWhite.string = 'Ready';
		this.labRed.string = 'Ready';
		this.labWhite.fontSize = 80;
		this.labRed.fontSize = 80;
		this.labWhite.node.color = new cc.Color().fromHEX('#f9ff88');
		this.playQuestionColor();
	},

	// 初始化摇杆，倒下状态
	initYaoGan() {
		this.stopColorLight();
		this.sprAudioLeft.node.active = true;
		this.sprAudioRight.node.active = true;
		this.labWordLeft.node.color = new cc.Color().fromHEX('#ffffff');
		this.labWordRight.node.color = new cc.Color().fromHEX('#ffffff');
		this.animationLeft.node.eulerAngles = cc.v3(-60, 0, 0);
		this.animationRight.node.eulerAngles = cc.v3(-60, 0, 0);
	},

	playQuestionColor() {
		this.schedule(this.changeLabelReadyColorCb, 0.06);
	},
	changeLabelReadyColorCb() {
		if (this.labWhite.node.color.toHEX() == 'f9ff88') {
			this.labWhite.node.color = new cc.Color().fromHEX('#ffffff');
		} else {
			this.labWhite.node.color = new cc.Color().fromHEX('#f9ff88');
		}
	},
	stopQuestionColor() {
		this.labWhite.node.color = new cc.Color().fromHEX('#ffffff');
		this.unschedule(this.changeLabelReadyColorCb);
	},

	setLabelReadyGo() {
		this.labWhite.string = 'Go!';
		this.labRed.string = 'Go!';
	},

	resumeLabelReady() {
		this.labWhite.fontSize = 110;
		this.labRed.fontSize = 110;
		this.stopQuestionColor();
	},

	// 节点震动效果
	shakeEffect(node, duration) {
		let oldPos = node.position;
		let pos = cc.v2(oldPos.x, oldPos.y);
		node.runAction(
			cc.repeatForever(
				cc.sequence(
					cc.moveTo(0.02, pos.add(cc.v2(5, 7))),
					cc.moveTo(0.02, pos.add(cc.v2(-6, 7))),
					cc.moveTo(0.02, pos.add(cc.v2(-13, 3))),
					cc.moveTo(0.02, pos.add(cc.v2(3, -6))),
					cc.moveTo(0.02, pos.add(cc.v2(-5, 5))),
					cc.moveTo(0.02, pos.add(cc.v2(2, -8))),
					cc.moveTo(0.02, pos.add(cc.v2(-8, -10))),
					cc.moveTo(0.02, pos.add(cc.v2(3, 10))),
					cc.moveTo(0.02, pos.add(cc.v2(0, 0)))
				)
			)
		);

		setTimeout(() => {
			node.stopAllActions();
			node.position = oldPos;
		}, duration * 1000);
	},

	playAudioEntrer() {
		GameData.isAudio = true;
		GameData.isStart = false;
		let id = cc.audioEngine.play(this.audEnter, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			this.playAudioQuestion();
		}, duration)
	},

	playAudioQuestion() {
		GameData.isAudio = true;
		GameData.isStart = false;
		// this.data.contentObj.bgm_url = 'http://127.0.0.1/iamflying.mp3';
		cc.assetManager.loadRemote(this.data.contentObj.bgm_url, null, (err, clip) => {
			if (err) {
				console.log(err)
				this.playAudioReady();
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			let duration = cc.audioEngine.getDuration(id);
			this.scheduleOnce(() => {
				GameData.isAudio = false;
				this.playAudioReady();
			}, Math.max(duration, 3.4))
		});
	},

	playAudioReady() {
		GameData.isAudio = true;
		GameData.isStart = false;
		let id = cc.audioEngine.play(this.audReady, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			this.playAudioGo();
		}, duration)
	},
	playAudioGo() {
		GameData.isAudio = true;
		this.setLabelReadyGo();
		GameData.isStart = false;
		let id = cc.audioEngine.play(this.audGo, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			this.resumeLabelReady();
			this.playAudioNewQuestion();
			this.refreshQuestion();
			this.playYaoGanResumeAction();
		}, duration)
	},

	refreshQuestion() {
		this.refreshQuestionLabel();
		this.refreshAnswerLabel();
	},

	refreshQuestionLabel() {
		let letter = this.data.contentObj.dataArray[GameData.questionIndex].letter;
		let string = letter.toUpperCase() + ' ' + letter.toLowerCase();
		this.labWhite.string = string;
		this.labRed.string = string;
	},
	refreshAnswerLabel() {
		let text1 = this.data.contentObj.dataArray[GameData.questionIndex].text1;
		let text2 = this.data.contentObj.dataArray[GameData.questionIndex].text2;
		this.labWordLeft.string = text1;
		this.labWordRight.string = text2;
		this.scheduleOnce(() => {
			if (text1.length > 5 || text2.length > 5) {
				let maxWidth = Math.max(this.labWordLeft.node.width, this.labWordRight.node.width);
				let scale = 160 / maxWidth;
				this.labWordLeft.node.scale = scale;
				this.labWordRight.node.scale = scale;
			}
		})
	},

	// 摇杆恢复
	playYaoGanResumeAction() {
		this.animationLeft.play('animLeft2');
		this.animationRight.play('animRight2');
	},

	playAudioNewQuestion() {
		GameData.isAudio = true;
		GameData.isStart = false;
		let id = cc.audioEngine.play(this.audNewQuestion, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			this.startGame();
		}, duration)
	},

	startGame() {
		GameData.isStart = true;
	},

	// 播放拳击声音
	playAudioChoose(cb) {
		GameData.isAudio = true;
		let id = cc.audioEngine.play(this.audChoose, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			cb && cb();
		}, 0.2)
	},

	// 播放正确音效
	playAudioRight(cb) {
		GameData.isAudio = true;
		let id = cc.audioEngine.play(this.audChooseRight, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			cb && cb();
		}, duration)
	},
	// 播放错误音效
	playAudioWrong(cb) {
		GameData.isAudio = true;
		let id = cc.audioEngine.play(this.audChooseWrong, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			cb && cb();
		}, duration)
	},

	playAudioTryAgain(cb) {
		GameData.isAudio = true;
		let id = cc.audioEngine.play(this.audTryAgain, false, 1);
		let duration = cc.audioEngine.getDuration(id);
		this.scheduleOnce(() => {
			GameData.isAudio = false;
			cb && cb();
		}, duration)
	},

	showLeftWrong() {
		this.left.getChildByName('mask').active = true;
		this.left.getChildByName('cross').active = true;
	},
	showRightWrong() {
		this.right.getChildByName('mask').active = true;
		this.right.getChildByName('cross').active = true;
	},
	hideLeftWrong() {
		this.left.getChildByName('mask').active = false;
		this.left.getChildByName('cross').active = false;
	},
	hideRightWrong() {
		this.right.getChildByName('mask').active = false;
		this.right.getChildByName('cross').active = false;
	},

	// 点击左边摇杆
	onBtnClickLeft() {
		if (!GameData.isStart) {
			return;
		}
		if (GameData.isAudio) {
			return;
		}
		GameData.isAudio = true;
		this.shakeEffect(this.node.getChildByName('bg'), 0.2);
		this.playAudioChoose(() => {
			GameData.isAudio = false;
			let isRight = this.data.contentObj.dataArray[GameData.questionIndex].isRight1;
			if (isRight) {
				this.animationLeft.play('animLeft');
				this.playQuestionColor();
				this.playColorLight();
				this.playAudioRight(() => {
					this.showResult(true);
				});
			} else {
				this.playAudioWrong(() => {
					this.playAudioTryAgain(() => {
						this.hideLeftWrong();
					})
				});
				this.showLeftWrong();
			}
		})
	},
	// 点击右边摇杆
	onBtnClickRight() {
		if (!GameData.isStart) {
			return;
		}
		if (GameData.isAudio) {
			return;
		}
		GameData.isAudio = true;
		this.shakeEffect(this.node.getChildByName('bg'), 0.2);
		this.playAudioChoose(() => {
			GameData.isAudio = false;
			let isRight = this.data.contentObj.dataArray[GameData.questionIndex].isRight2;
			if (isRight) {
				this.animationRight.play('animRight');
				this.playQuestionColor();
				this.playColorLight();
				this.playAudioRight(() => {
					this.showResult();
				});
			} else {
				this.playAudioWrong(() => {
					this.playAudioTryAgain(() => {
						this.hideRightWrong();
					})
				});
				this.showRightWrong();
			}
		})
	},

	showResult(isLeft = false) {
		let node = cc.instantiate(this.pfbLayerResult);
		node.parent = this.node;
		node.getComponent('LayerResult').setData(this.data.contentObj, GameData.questionIndex, isLeft, this);

		GameData.questionList[GameData.questionIndex] = true;

		// 喇叭按钮消失
		this.sprAudioLeft.node.active = false;
		this.sprAudioRight.node.active = false;
		this.scheduleOnce(() => {
			this.stopQuestionColor();
			// 错误靶子倒下，颜色变深
			if (isLeft) {
				this.animationRight.play('animRight');
				this.labWordRight.node.color = new cc.Color().fromHEX('#000000');
			} else {
				this.animationLeft.play('animLeft');
				this.labWordLeft.node.color = new cc.Color().fromHEX('#000000');
			}
		}, 0.5)
	},

	// 点击问题
	onBtnClickQuestion() {
		if (GameData.isAudio) {
			return;
		}
		if (!GameData.isStart) {
			return;
		}
		GameData.isAudio = true;
		this.labWhite.node.color = new cc.Color().fromHEX('#f9ff88');
		this.playAudioLetter(() => {
			this.labWhite.node.color = new cc.Color().fromHEX('#ffffff');
			GameData.isAudio = false;
		});
	},
	// 点击左边音效
	onBtnAudioLeft() {
		if (!GameData.isStart) {
			return;
		}
		if (GameData.isAudio) {
			return;
		}
		GameData.isAudio = true;
		this.sprAudioLeft.spriteFrame = this.spfAudio[1];
		this.schedule(this.changeLeftAudioSpfCb, 0.2)
		this.playAudioWordLeft(() => {
			this.unschedule(this.changeLeftAudioSpfCb)
			this.sprAudioLeft.spriteFrame = this.spfAudio[0];
			GameData.isAudio = false;
		});
	},
	// 点击右边音效
	onBtnAudioRight() {
		if (!GameData.isStart) {
			return;
		}
		if (GameData.isAudio) {
			return;
		}
		GameData.isAudio = true;
		this.sprAudioRight.spriteFrame = this.spfAudio[1];
		this.schedule(this.changeRightAudioSpfCb, 0.2)
		this.playAudioWordRight(() => {
			this.unschedule(this.changeRightAudioSpfCb)
			this.sprAudioRight.spriteFrame = this.spfAudio[0];
			GameData.isAudio = false;
		});
	},
	changeLeftAudioSpfCb() {
		this.sprAudioLeft.spriteFrame = this.sprAudioLeft.spriteFrame == this.spfAudio[0] ? this.spfAudio[1] : this.spfAudio[0];
	},
	changeRightAudioSpfCb() {
		this.sprAudioRight.spriteFrame = this.sprAudioRight.spriteFrame == this.spfAudio[0] ? this.spfAudio[1] : this.spfAudio[0];
	},

	playAudioLetter(cb) {
		let url = this.data.contentObj.dataArray[GameData.questionIndex].shortAudio_url;
		// 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);
			let duration = cc.audioEngine.getDuration(id);
			this.scheduleOnce(() => {
				cb && cb();
			}, duration)
		});
	},

	playAudioWordLeft(cb) {
		let url = this.data.contentObj.dataArray[GameData.questionIndex].shortAudio_url2;
		// url = 'http://127.0.0.1/iamflying.mp3'
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				cb && cb();
				console.log(err)
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			let duration = cc.audioEngine.getDuration(id);
			this.scheduleOnce(() => {
				cb && cb();
			}, duration)
		});
	},
	playAudioWordRight(cb) {
		let url = this.data.contentObj.dataArray[GameData.questionIndex].shortAudio_url3;
		// url = 'http://127.0.0.1/iamflying.mp3'
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				cb && cb();
				console.log(err)
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			let duration = cc.audioEngine.getDuration(id);
			this.scheduleOnce(() => {
				cb && cb();
			}, duration)
		});
	},

	replay() {
		this.initYaoGan();
		this.resumeLabelReady();
		this.playAudioNewQuestion();
		this.refreshQuestion();
		this.playYaoGanResumeAction();
	},

	onTurnLast() {
		GameData.questionIndex--;
		this.replay();
	},
	onReplay() {
		this.replay();
	},
	onTurnNext() {
		GameData.questionIndex++;
		this.replay();
	},




	// 彩灯闪烁
	playColorLight() {
		this.colorLightIndex = 0;
		this.schedule(this.colorLightCb, 0.2)
	},
	stopColorLight() {
		this.unschedule(this.colorLightCb);
		this.red.active = false;
		this.yellow.active = false;
		this.blue.active = false;
	},
	colorLightCb() {
		this.colorLightIndex++;
		let index = this.colorLightIndex % 3;
		if (index == 0) {
			this.red.active = true;
			this.yellow.active = false;
			this.blue.active = false;
		} else if (index == 1) {
			this.red.active = false;
			this.yellow.active = true;
			this.blue.active = false;
		} else {
			this.red.active = false;
			this.yellow.active = false;
			this.blue.active = true;
		}
	},



	// ------------------------------------------------
	getSprNode(resName) {
		const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
		const node = new cc.Node();
		node.addComponent(cc.Sprite).spriteFrame = sf;
		return node;
	},


	getSpriteFrimeByUrl(url, cb) {
		cc.loader.load({ url }, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			if (cb) {
				cb(spriteFrame);
			}
		})
	},

	getSprNodeByUrl(url, cb) {
		const node = new cc.Node();
		const spr = node.addComponent(cc.Sprite);
		this.getSpriteFrimeByUrl(url, (sf) => {
			spr.spriteFrame = sf;
			if (cb) {
				cb(node);
			}
		})
	},

	playAudioByUrl(audio_url, cb = null) {
		if (audio_url) {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				const audioId = cc.audioEngine.play(audioClip, false, 0.8);
				if (cb) {
					cc.audioEngine.setFinishCallback(audioId, () => {
						cb();
					});
				}
			});
		}
	},

	// ------------------------------------------

});
