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

	extends: BaseUI,

	properties: {
		audEnter: cc.AudioClip,
		audMove: cc.AudioClip,
		audTryAgain: cc.AudioClip,
		pfbItemAnswer: cc.Prefab,
		layerOver: cc.Prefab,
		layerTryAgain: cc.Prefab,
		layerFive: cc.Prefab,
		layerSeven: cc.Prefab,
		dragonBone: dragonBones.ArmatureDisplay,
		spfAudio: [cc.SpriteFrame],
	},

	/**
	 * 图片文字N选N-默认页面，所有选项蒙黑，右下角小女巫播放"normal"动画，选项里的正方形是个图片，此时没有播放音频按钮
	 * 图片文字N选N-五个选项以上选项布局
	 * 图片文字N选N-喇叭按钮弹出，点击按钮播放音频，播放时喇叭有三个点和没三个点状态反复切换
	 * 图片文字N选N-选择一个选项，选项发光,所有选项喇叭先放大后缩小消失，如果选错，弹出x，女巫动作切换为“wrong”
	 * 图片文字N选N-错误选项上x号缩小消失，界面蒙半透明黑，错误选项旋转掉落出界面，界面中间弹出“try again!”然后缩小消失，界面亮起
	 * 图片文字N选N-选择一个选项，选项发光，如果选对，女巫飞到正确选项旁边，播放选对动作"right"，播放选对选中特效
	 * 图片文字N选N-女巫回到右下角，界面蒙半透明黑，正确选项放大到屏幕中间，图片区域播放骨骼动画
	 * 图片文字N选N-正确选项放大后，伴随音频播放，文字依次变绿，音频结束完全变绿，然后再依次变成白色，再次点击再次重播
	 * 图片文字N选N-最后一道题做对放大到中间后，屏幕中间弹出“Well Done!"
	 * 图片文字N选N-女巫飞到屏幕中间靠下位置播放“finish”动画
	 * 图片文字N选N-女巫飞行轨迹
	 * 图片文字N选N-well done缩小淡出，女巫飞回原来位置
	 * 
	 */
	// 生命周期 onLoad
	onLoad() {
		this._super();
		this.initNodes();
		this.initSceneData();
		this.initSize();
	},
	initNodes() {
		this.sprAudio = this.nodeDict.sprAudio.getComponent(cc.Sprite);
		this.sprAudio.node.active = false;

		this.startDragonbonePos = this.dragonBone.node.position;
		this.animation = this.getComponent(cc.Animation);
	},

	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() {
		for (let i = 0; i < this.data.questionList.length; i++) {
			this._resList.push({ url: this.data.questionAudio });
			this._resList.push({ url: this.data.questionList[i].pageAudio });
			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 });

			}
		}
	},

	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.questionList = [];
		for (let i = 0; i < this.data.questionList.length; i++) {
			this.questionList[i] = i;
		}
		// this.questionList[0] = 0;
		this.initData();

		this.startGame();

		this.dragonBone.on(dragonBones.EventObject.COMPLETE, (event) => {
			if (event.animationState.name == 'wrong') {
				this.playNormal();
			}
		}, this)
	},

	initData() {
		// 所有全局变量 默认都是null 
		GameData.audioCount = 0;
		this.nodeDict.nodButtons.zIndex = 6;
		let optionList = this.data.questionList[GameData.questionIndex].optionList;
		this.optionList = [];
		for (let i = 0; i < optionList.length; i++) {
			this.optionList[i] = i;
		}
		this.initAnswer();
		this.initTitle();
		this.updateBtnStatus();
	},

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

	initTitle() {
		let label = this.nodeDict.labTitle.getComponent(cc.Label);
		label.string = this.data.questionText;
		label._forceUpdateRenderData();
		if (this.nodeDict.labTitle.width > 545) {
			this.nodeDict.labTitle.scale = 545 / this.nodeDict.labTitle.width
		}
	},

	// 初始化选项
	initAnswer() {
		this.nodeDict.nodLayerAnswer.destroyAllChildren();
		let optionList = this.data.questionList[GameData.questionIndex].optionList;
		if (optionList.length <= 5) {
			this.layerAnser = cc.instantiate(this.layerFive);
			this.layerAnser.parent = this.nodeDict.nodLayerAnswer;
		} else {
			this.layerAnser = cc.instantiate(this.layerSeven);
			this.layerAnser.parent = this.nodeDict.nodLayerAnswer;
		}
		this.nodeDict.nodLayerAnswer.zIndex = 2;
		this.layerAnser.active = true;
		for (let i = 0; i < optionList.length; i++) {
			let node = this.layerAnser.children[i];
			node.active = true;
			let isRight = false;
			if (this.data.questionList[GameData.questionIndex].rightOptionIdx == i) {
				isRight = true;
			}
			node.getComponent('ItemAnswer').setInfo(optionList[i], i, this, isRight);
		}
		for (let i = this.layerAnser.children.length - 1; i >= optionList.length; i--) {
			this.layerAnser.children[i].active = false;
		}
	},


	playAudioEntrer() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audEnter, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
			this.playAudioQuestion();
		})
	},
	playAudioPage(isBtn,cb) {
		GameData.audioCount++;
		let url = this.data.questionList[GameData.questionIndex].pageAudio;
		// url = 'http://127.0.0.1/iamflying.mp3';
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				console.log(err)
				this.startStepDone();
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				GameData.audioCount--;
				cb && cb();
				if (!isBtn) {
					this.startStepDone();
				}
			})
		});
	},
	playAudioQuestion() {
		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, () => {
				GameData.audioCount--;
				this.playAudioPage();
			})
		});
	},
	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--;
		})
	},

	startStepDone() {
		this.sprAudio.node.active = true;
		GameData.startStepDone = true;
		EventMgr.emit('showAudioButton');
	},

	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;
		}
	},

	onClickAnswer(itemAnser, isRight) {
		for (let i = 0; i < this.layerAnser.children.length; i++) {
			this.layerAnser.children[i].getComponent('ItemAnswer').playHideAudioButton();
		}
		if (isRight) {
			this.showDragonBonesMove(itemAnser.node);
		} else {
			this.scheduleOnce(() => {
				for (let i = 0; i < this.layerAnser.children.length; i++) {
					this.layerAnser.children[i].getComponent('ItemAnswer').playShowAudioButton();
				}
			}, 2)
			this.playWrong();
			GameData.audioCount++;
			this.scheduleOnce(() => {
				this.showLayerTryagain();
			}, 0.8)
		}
	},

	showDragonBonesMove(target) {
		this.playAudioMove();
		GameData._showDragonbones = true;
		GameData._showDragonbonesMove = true;
		let pos = target.parent.convertToWorldSpaceAR(target.position);
		pos = this.node.convertToNodeSpaceAR(pos);
		pos = pos.add(cc.v2(180, -100))
		this.dragonBone.node.zIndex = 3;
		this.dragonBone.node.runAction(
			cc.sequence(
				cc.moveTo(2, pos),
				cc.callFunc(() => {
				})
			)
		)
		this.playRight();
		this.scheduleOnce(() => {
			if (cc.isValid(target)) {
				this.showChooseRight(target);
			}
		}, 2.2)
	},

	showChooseRight(target) {
		let itemAnswer = target.getComponent('ItemAnswer');
		for(let i = 0;i<this.questionList.length;i++){
			if(this.questionList[i] === GameData.questionIndex){
				this.questionList.splice(i, 1);
			}
		}
		this.nodeDict.nodMask.active = true;
		this.nodeDict.nodMask.parent = this.layerAnser;
		target.zIndex = 2;
		this.playNormal();
		this.dragonBone.node.runAction(
			cc.sequence(
				cc.moveTo(0.5, this.startDragonbonePos),
				cc.callFunc(() => {
					this.dragonBone.node.zIndex = 1;
				})
			)
		)
		itemAnswer.playRotateNormal();
		target.runAction(cc.sequence(
			cc.spawn(
				cc.moveTo(0.5, 0, 0),
				cc.scaleTo(0.5, 1.2)
			),
			cc.callFunc(() => {
				itemAnswer.playLabelGreen(()=>{
					if(GameData.isOver){
						return;
					}
					if (this.checkOver()) {
						this.showLayerOver();
					}
				});
				GameData._showDragonbonesMove = false;
			})
		))
	},

	checkOver() {
		if (this.questionList.length == 0) {
			return true;
		}
	},
	showLayerOver() {
		GameData.isOver = true;
		let node = cc.instantiate(this.layerOver);
		node.parent = this.node;
		node.zIndex = 6;

		this.dragonBone.node.stopAllActions();
		this.dragonBone.node.zIndex = 7;
		
		this.animation.play('anim_over_girl');

		this.scheduleOnce(()=>{
			this.playFinish();
		},0.6)
		this.scheduleOnce(() => {
			node.getChildByName('bg_verygood').runAction(
				cc.sequence(
					cc.scaleTo(1,0),
					cc.callFunc(()=>{
						this.dragonBone.node.zIndex = 1;
					})
				)
			)
		}, 3.5)
	},

	showLayerTryagain() {
		let node = cc.instantiate(this.layerTryAgain);
		node.parent = this.node;
		node.zIndex = 5;
		GameData.audioCount--;
		this.playAudioTryagain();
		this.scheduleOnce(() => {
			node.destroy();
		}, 1.7)
	},

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

	resetDate() {
		GameData._showDragonbones = false;
		this.nodeDict.nodMask.active = false;
		this.nodeDict.nodMask.parent = this.node;
		cc.audioEngine.stopAll();
		this.initData();
		this.playAudioPage();
		GameData.startStepDone = false;
	},
	onTurnLast() {
		if (GameData.audioCount != 0) {
			return;
		}
		GameData.questionIndex--;
		this.resetDate();
	},
	onReplay() {
		if (GameData.audioCount != 0) {
			return;
		}
		this.resetDate();
	},
	onTurnNext() {
		if (GameData.audioCount != 0) {
			return;
		}
		GameData.questionIndex++;
		this.resetDate();
	},

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


	playNormal() {
		this.dragonBone.playAnimation('normal', 0);
	},
	playWrong() {
		this.dragonBone.playAnimation('wrong', 1);
	},
	playRight() {
		this.dragonBone.playAnimation('right', 1);
	},
	playFinish() {
		this.dragonBone.playAnimation('finish', 1);
	},

	changeAudioSpfCb() {
		this.sprAudio.spriteFrame = this.sprAudio.spriteFrame == this.spfAudio[0] ? this.spfAudio[1] : this.spfAudio[0];
	},
	onBtnClickAudio() {
		if (GameData.audioCount > 0) {
			return;
		}
		this.dragonBone.playAnimation(this.animationName, 0);
		this.sprAudio.spriteFrame = this.spfAudio[0];
		this.schedule(this.changeAudioSpfCb, 0.2)
		this.playAudioPage(true,() => {
			this.unschedule(this.changeAudioSpfCb)
			this.sprAudio.spriteFrame = this.spfAudio[1];
			GameData.isAudio = false;
		});
	},

	playAudio(cb) {
		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--;
				cb && cb();
			})
		});
	},
});
