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

	extends: cc.Component,

	properties: {
		dragonBone: dragonBones.ArmatureDisplay,
		audEnter: cc.AudioClip,
		audTrain: cc.AudioClip,
		audOver: cc.AudioClip,
		layerCoach: cc.Node,
		pfbLayerResult: cc.Prefab,
		pfbLayerOver: cc.Prefab,
		pfbItemCoaches: [cc.Prefab],
	},

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


		window.addEventListener('onblur', function (e) {
            console.log('onblur');
        });
	},
	initNodes() {
		this.layerTrain = this.layerCoach.parent;
		let bg = this.node.getChildByName('bg');
		this.speedLevels = bg.getChildByName('speedLevels');
		this.level1 = this.speedLevels.getChildByName('level1');
		this.level2 = this.speedLevels.getChildByName('level2');
		this.level3 = this.speedLevels.getChildByName('level3');
	},

	onEnable() {
		this.speedLevels.on('touchend', this.onSpeedTouchend, this);
		this.node.on('showResult', this.onShowResult, this);
		this.node.on('showResultDone', this.onShowResultDone, this);
		this.node.on('stopMove', this.onStopMove, this);
	},

	onDisable() {
		this.speedLevels.off('touchend', this.onSpeedTouchend, this);
		this.node.off('showResult', this.onShowResult, this);
		this.node.off('showResultDone', this.onShowResultDone, this);
		this.node.off('stopMove', this.onStopMove, this);
	},



	onSpeedTouchend(e) {
		if (window.isPlayEnter) {
			return
		}
		let pos = e.getLocation();
		pos = this.speedLevels.convertToNodeSpaceAR(pos);
		if (pos.x < -this.speedLevels.width / 6) {
			this.level1.active = true;
			this.level2.active = false;
			this.level3.active = false;
			this.speedLevel = 1;
			this.restartRunTrain();
		} else if (pos.x < this.speedLevels.width / 6) {
			this.level1.active = false;
			this.level2.active = true;
			this.level3.active = false;
			this.speedLevel = 2;
			this.restartRunTrain();
		} else {
			this.level1.active = false;
			this.level2.active = false;
			this.level3.active = true;
			this.speedLevel = 3;
			this.restartRunTrain();
		}
	},


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

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {
		return
		// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
		let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
		let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
		let f = screen_size >= design_size
		cc.Canvas.instance.fitHeight = f
		cc.Canvas.instance.fitWidth = !f

		const frameSize = cc.view.getFrameSize();
		this._frameSize = frameSize;

		this._designSize = cc.view.getDesignResolutionSize();

		let sx = cc.winSize.width / frameSize.width;
		let sy = cc.winSize.height / frameSize.height;
		this._cocosScale = Math.min(sx, sy);

		sx = frameSize.width / this._designSize.width;
		sy = frameSize.height / this._designSize.height;
		this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
		this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
	},


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

  getData(func) {
    if (window && window.courseware) {
      window.courseware.getData(func, 'scene');
      return;
    }

    const middleLayer = cc.find('middleLayer');
    if (middleLayer) {
      const middleLayerComponent = middleLayer.getComponent('middleLayer');
      middleLayerComponent.getData(func);
      return;
    }

    func(this.getDefaultData());
  },


	getDefaultData() {
		let dataJson = '{"contentObj":{"version":"1.1","key":"DataKey_Cocos_Test","haveCover":true,"dataArray":[{"type":"Image","text":"没 有 数 据","image_url":""},{"type":"Spine","text":"没 有 数 据","image_url":""}]}}'
		dataJson = '{"contentObj":{"version":"1.1","key":"DataKey_Cocos_Test","dataArray":[{"text":"apple","isRight":true,"shortAudio_url":"","image_url":"","letterIndex":0},{"text":"banana","isRight":true,"shortAudio_url":"","image_url":"","letterIndex":0},{"text":"cat","isRight":false,"shortAudio_url":"","image_url":"","letterIndex":0},{"text":"test","isRight":false,"shortAudio_url":"","image_url":"","letterIndex":0}],"letter1":"a","letter2":"b"}}';
		let data = JSON.parse(dataJson);
		return data;
	},

	preloadItem() {
		// this.addPreloadImage();
		this.addPreloadDragonBone();
		this.addPreloadAudio();
		// 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 || ''});
			}
		}
	},

	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.initCoaches();

		this.initLayerTrainPosition();
		this.playAudioEntrer();
	},

	initData() {
		// 所有全局变量 默认都是null 
	},

	initRightChoose() {
		this.rightChooseArr = [];
		for (let i = 0; i < this.data.contentObj.dataArray.length; i++) {
			if (this.data.contentObj.dataArray[i].isRight) {
				this.rightChooseArr.push(i);
			}
		}
	},

	initLayerTrainPosition() {
		this.layerTrain.x = cc.view.getVisibleSize().width / 2 - 1280;
		this.dragonBone.playAnimation('normal', -1);
	},

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

	playAudioQuestion() {
		// this.data.contentObj.bgm_url = 'http://127.0.0.1/iamflying.mp3';
		if (!this.data.contentObj.bgm_url) {
			this.playAudioTrain();
			return;
		}
		
		cc.assetManager.loadRemote(this.data.contentObj.bgm_url, null, (err, clip) => {
			if (err) {
				console.log(err)
				this.playAudioTrain();
				return;
			}
			this.layerTrain.getComponent(cc.Animation).play('fingerMove');
			let id = cc.audioEngine.play(clip, false, 1);
			let duration = cc.audioEngine.getDuration(id);
			this.scheduleOnce(() => {
				this.playAudioTrain();
			}, Math.max(duration, 3.4))
		});
	},

	playAudioTrain() {
		this.initRightChoose();
		window.isPlayEnter = false;
		this.tTween && this.tTween.stop();
		this.tTween = cc.tween(this.layerTrain)
			.to(0.2, { opacity: 0 })
			.call(() => {
				this.layerTrain.opacity = 255;
				this.startRunTrain();
			})
			.start()
		this.trainVolume = 0.01;
		this.audTrainId = cc.audioEngine.play(this.audTrain, true, this.trainVolume);
		let duration = cc.audioEngine.getDuration(this.audTrainId);
		if (!this.tFunc1) {
			this.tFunc1 = () => {
				this.trainVolume += 0.02;
				cc.audioEngine.setVolume(this.audTrainId, this.trainVolume);
				if (this.trainVolume >= 1) {
					this.unschedule(this.tFunc1)
				}
			}
		}
		this.unschedule(this.tFunc1)
		this.schedule(this.tFunc1, duration / 50)
	},

	playAudioTrainEase() {
		let volume = 0;
		if (!this.tFunc3) {
			this.tFunc3 = () => {
				volume += 0.03;
				if (volume > 1) {
					volume = 1;
				}
				cc.audioEngine.setVolume(this.audTrainId, volume);
				if (volume >= 1) {
					this.unschedule(this.tFunc3)
				}
			}
		}
		this.unschedule(this.tFunc3)
		this.schedule(this.tFunc3, 0.02)
	},

	stopAudioTrainEase() {
		let volume = 1;
		if (!this.tFunc2) {
			this.tFunc2 = () => {
				volume -= 0.06;
				if (volume < 0) {
					volume = 0;
				}
				cc.audioEngine.setVolume(this.audTrainId, volume);
				if (volume <= 0) {
					this.unschedule(this.tFunc2)
				}
			}
		}
		this.unschedule(this.tFunc1)
		this.unschedule(this.tFunc3)
		this.unschedule(this.tFunc2)
		this.schedule(this.tFunc2, 0.02)
	},

	stopAudioTrain() {
		cc.audioEngine.stop(this.audTrainId);
	},
	puaseAudioTrain() {
		cc.audioEngine.pause(this.audTrainId);
	},
	resumeAudioTrain() {
		cc.audioEngine.resume(this.audTrainId);
	},

	startRunTrain() {
		if (window.isPlayEnter) {
			return
		}
		this.layerTrain.x = cc.view.getVisibleSize().width / 2;
		window.isTrainMove = true;
		this.dragonBone.playAnimation('move', -1);
	},

	restartRunTrain() {
		this.destroyLayerOver();
		this.stopAudioTrain();
		this.playAudioTrain();
	},

	checkTrainMoveDone() {
		let width = this.layerCoach.width + 680;
		let width2 = cc.view.getVisibleSize().width;
		if (this.layerTrain.x < -width2 / 2 - width) {
			this.showGameOver();
		}
	},

	getSpeed() {
		if (this.speedLevel == 1) {
			return 50;
		} else if (this.speedLevel == 2) {
			return 120;
		} else if (this.speedLevel == 3) {
			return 200;
		}
	},

	update(dt) {
		if (!window.isTrainMove) {
			return;
		}
		this.layerTrain.x -= dt * this.getSpeed();
		this.checkTrainMoveDone();
	},



	initCoaches() {
		let l = this.data.contentObj.dataArray.length;
		for (let i = 0; i < l; i++) {
			let prefabIndex = i % 4;
			let prefab = this.pfbItemCoaches[prefabIndex];
			let node = cc.instantiate(prefab);
			node.parent = this.layerCoach;
			node.zIndex = l - i;
			node.getComponent('ItemCoach' + (prefabIndex + 1)).setData(this.data.contentObj.dataArray[i], i);
		}
	},

	onShowResult(event) {
		let index = event.getUserData();
		let node = cc.instantiate(this.pfbLayerResult);
		node.parent = this.node;
		node.getComponent('LayerResult').setData(this.data.contentObj, index);
	},

	playDragonResult(index) {
		let isRight = this.data.contentObj.dataArray[index].isRight;
		if (isRight) {
			this.playRight();
		} else {
			this.playWrong();
		}
	},

	playRight() {
		this.dragonBone.playAnimation('right', -1);
	},
	playWrong() {
		// this.dragonBone.playAnimation('normal', -1);
	},

	onStopMove(event){
		let index = event.getUserData();
		window.isTrainMove = false;
		this.stopAudioTrainEase();
		this.playDragonResult(index);
	},

	onShowResultDone(event) {
		let index = event.getUserData();
		this.playAudioTrainEase();
		window.isTrainMove = true;
		this.dragonBone.playAnimation('move', -1);
		this.removeRightChoose(index);
	},

	removeRightChoose(index) {
		let index2 = this.rightChooseArr.indexOf(index);
		if (index2 >= 0) {
			this.rightChooseArr.splice(index2, 1);
			this.checkOver();
		}
	},

	checkOver() {
		if (this.rightChooseArr.length == 0) {
			this.showGameOver();
		}
	},


	showGameOver() {
		window.isTrainMove = false;
		this.stopAudioTrain();
		this.layerOver = cc.instantiate(this.pfbLayerOver);
		this.layerOver.parent = this.node;
		cc.audioEngine.play(this.audOver, false, 1)
		this.dragonBone.playAnimation('normal', -1);
	},
	destroyLayerOver() {
		this.layerOver && this.layerOver.destroy();
	},


	// ------------------------------------------------
	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();
					});
				}
			});
		}
	},

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

});
