import { playAudio, playDragonBoneAnimation } from "../script/util";
import { defaultData } from "../script/defaultData";

cc.Class({

	extends: cc.Component,
	properties: {
		level_bar: {
			default: null,
			type: cc.ProgressBar,
		},
		complete_ui:{
			default:null,
			type: cc.Node,
		},
		mike_btn:{
			default:null,
			type:cc.Button,
		},
		msg_node:{
			default:null,
			type:cc.Node
		},
		game_node:{
			default:null,
			type:cc.Node
		},
		timer_node:{
			default:null,
			type:cc.Node
		},
		level_node:{
			default:null,
			type:cc.Node
		},
		evaluate_ndoe:{
			default:null,
			type:cc.Node
		}
	},

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

	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	initSceneData() {
		this._imageResList = [];
		this._audioResList = [];
		this._animaResList = [];
	},

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {
		// 注意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() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}

		getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.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() {
		return defaultData;
	},

	preloadItem() {
		this.trasformData(this.data.contentObj.dataArray);
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},

	trasformData(data){
		this._words = [];
		let max_time = 0;
		for(let i = 0; i < data.length; i++){
			this._words.push({
				time:data[i].time,
				word:data[i].question.text,
				audio:data[i].question.audio_url
			});
			max_time += Number(this._words[i].time);
		}
		this._max_time = max_time;
		console.log(this._words);
		console.log('max_time = ' + max_time);
		window.scene = this;
	},

	addPreloadImage() {

		// this._imageResList.push({ url: this.data.pic_url });
		// this._imageResList.push({ url: this.data.pic_url_2 });
	},

	addPreloadAudio() {

		this._audioResList.push({ url: this.data.audio_url });
	},

	addPreloadAnima() {

	},

	preload() {

		const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
		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.initAudio();
		this.initView();
		// this.initListener();
	},

	//_cantouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		//this._cantouch = true;
	},

	//audioBtn: null,
	// initAudio() {
	// 	const audioNode = cc.find('res/audio');

	// 	const getAudioByResName = (resName) => {
	// 		return audioNode.getChildByName(resName).getComponent(cc.AudioSource);
	// 	}

	// 	this.audioBtn = getAudioByResName('btn');

	// },


	initView() {
		const bgNode = cc.find('Canvas/bg');
		let _bg = bgNode.getChildByName('bg');
		_bg.width = cc.winSize.width;
		_bg.height = cc.winSize.height;
		//bgNode.scale = this._mapScaleMax;

		let res = cc.find('res');
		//console.log(res);
		
		this._res = res;
		res.sv_item = res.getChildByName('sv_item');
		res.word_item = res.getChildByName('word_item');

		this._level_num = this.level_node.getChildByName('level_num').getComponent(cc.Label);
		this._evaluate = this.evaluate_ndoe.getComponent(cc.js.getClassByName('Evaluate'));
		this._complete = this.complete_ui.getComponent(cc.js.getClassByName('CompleteUI'));
		this._wlist = this.game_node.getChildByName('word_list');

		this._last_time = cc.find('audio/last321').getComponent(cc.AudioSource);

		let _cbg = this.complete_ui.getChildByName('bg');
		_cbg.scale = 10;
		

		//this._log = cc.find('Canvas').getChildByName('log').getComponent(cc.Label);

		if (cc.winSize.width > cc.Canvas.instance.designResolution.width){
			this.game_node.getChildByName('fg').width = cc.winSize.width;
		}

		this.resetData();

	},

	tapReplay(){
		this.playAudioByName('replay');
		this.resetData();
	},

	tapMikeStart(){
		this._current.x = -446;
		this.playAudioByName('record');
	},

	fallAnimation(){
		this.mike_btn.interactable = false;
		this.playAudioByName('fall');
		let wi = this._current.getComponent(cc.js.getClassByName('WordItem'));
		this._item_ani = cc.tween(wi.body)
		.repeatForever(
			cc.tween()
				.to(0.1, {angle:-10})
				.to(0.2, {angle:10})
				.to(0.1, {angle:0}))
		.start();

		wi.db_item.active = true;
		//playDragonBoneAnimation(wi.db_item, 'newAnimation', 1);
	},

	tapMikeEnd(v){
		this._current.getComponent(cc.js.getClassByName('WordItem')).db_item.active = false;
		console.log('v = ' + v);
		let ev = v;

		if (this._item_ani){
			this._item_ani.stop();
		}
		let cx = 0, cy = 104;
		if (v == 1){
			this._down_dir *= -1;
			cx = this._down_dir * 64;
		}
		else if (v == 2){
			cy = 0;
			cx = 2000;
			ev = -1;
		}

		this._result[v].push(this._words[this._count].word);

		if (this.no_tap_horn == false && v < 2){
			this._result[2].push(this._words[this._count].word);
			v = 2;
			ev = 2;
		}

		let wi = this._current.getComponent(cc.js.getClassByName('WordItem'));
		wi.horn.node.active = false;
		this._current.runAction(
			cc.sequence(
				cc.jumpTo(0.5, cc.v2(cx, this._height), this._space, 1)
				,cc.callFunc(()=>{
						this._current.angle = 0;
						cc.tween(this.game_node)
						.by(0.1, {y: -cy})
						.call(()=>{
							if (this._show_complete)
								return;
							
							if (ev >= 0){
								this.playAudioByName(['perfect','good','nicetry'][v]);
								this._evaluate.setEvaluate(v, ()=>{
	
									if (this._show_complete)
										return;

									if (this._count < this._words.length){
										this._current = this.newWordItem();
									}
									else{
										this.completeResult();
										return;
									}
								});
								this._count ++;
							}
							else{
								this.playAudioByName('nicetry');
								this._evaluate.setEvaluate(2, ()=>{
									if (ev < 0 && this.show_horn == false){
										this.show_horn = true;
										this.bar_ani.stop();
										this.showMsgBar(1);
										this.timer321(()=>{
											this.showMsgBar(-1);
											this.bar_ani.stop();
											let lastPos = 1-(3/(this._max_time));
											let t1 = this._max_time * (1-this.level_bar.progress);
											let t2 = t1-3;
		
											if (t2 > 0){
												this.bar_ani = cc.tween(this.level_bar)
												.to(t2, {progress: lastPos})
												.call(()=>{
													this._last_time.play();
												})
												.to(3, {progress: 1})
												.call(()=>{
													this.completeResult();
												})
												.start();
						
											}
											else{
												if (this._last_time.isPlaying){
													this._last_time.play();
												}
												this.bar_ani = cc.tween(this.level_bar)
												.to(t1, {progress: 1})
												.call(()=>{
													this.completeResult();
												})
												.start();
											}
										});
									}
									this._current = this.newWordItem();
								})
							}
							
							this._height += cy;		
							this.setLevelNum(this._count);
						})
						.start();
				})
			));
	},

	setLevelNum(num){
		this._level_num.string = ''+num;
	},

	showMsgBar(idx){
		this.msg_node.active = idx >= 0;
		if (idx >= 0){
			this.msg_node.children[0].active = idx == 0;
			this.msg_node.children[1].active = idx == 1;
		}
	},

	timer321(cb){
		this.timer_node.active = true;
		this.playAudioByName('time321');
		playDragonBoneAnimation(this.timer_node, 'newAnimation', 1, ()=>{
			cb();
			this.timer_node.active = false;
		});
	},

	resetData(){
		this._down_dir = -1;
		this.timer_node.active = false;
		this.msg_node.active = false;
		this.game_node.y = -360;
		this._count = 0;
		this._height = 348;
		this._space = 104;
		this.level_bar.progress = 0;
		this.no_tap_horn = true;
		this.show_horn = false;
		this._result = [[],[],[]];
		this._show_complete = false;

		this._wlist.removeAllChildren();
		this.setLevelNum(0);
		this.showMsgBar(0);
		this.timer321(()=>{
			this.showMsgBar(-1);
			this._current = this.newWordItem();
			let lastPos = 1-(3/(this._max_time));
			this.bar_ani = cc.tween(this.level_bar)
			.to(this._max_time-3, {progress:lastPos})
			.call(()=>{
				this._last_time.play();
			})
			.to(3, {progress: 1})
			.call(()=>{
				this.completeResult();
			})
			.start();
		});
	},

	newWordItem(){
		this.no_tap_horn = true;
		let item = cc.instantiate(this._res.word_item);
		let wi = item.getComponent(cc.js.getClassByName('WordItem'));
		wi.db_item.active = false;
		wi.word.string = this._words[this._count].word;
		wi.audio = this._words[this._count].audio;
		console.log(this.show_horn);
		
		wi.horn.node.active = this.show_horn;
		wi.horn.node.on('click', ()=>{
			this.no_tap_horn = false;
			this.playAudioByUrl(wi.audio);
		});
		this._wlist.addChild(item);
		item.position = cc.v2(-1000, this._height);
		cc.tween(item)
			.to(0.8, {x: -446})
			.call(()=>{
				this.mike_btn.interactable = true;
			})
			.start();
		if (this._current){
			this._current.angle = 0;
		}
		return item;
	},

	completeResult(){
		if (this._show_complete == true)
			return;
		this._show_complete = true;
		if (this._count < this._words.length){
			for(let i = this._count; i < this._words.length; i++)
				this._result[2].push(this._words[i].word);
		}
		if (this._last_time.isPlaying){
			this._last_time.stop();
		}

		this._result[0] = this.unique(this._result[0]);
		this._result[1] = this.unique(this._result[1]);
		this._result[2] = this.unique(this._result[2]);

		this._result[1] = this.removeArray(this._result[1], this._result[2]);
		this._result[0] = this.removeArray(this._result[0], this._result[1]);
		this._result[0] = this.removeArray(this._result[0], this._result[2]);

		this.bar_ani.stop();
		this._complete.show();
		this.playAudioByName('victory');
	},

	// update (dt) {},

	removeArray(ar, dar){
		var ret = [];
		for (var i = 0, j = ar.length; i < j; i++) {
			if (dar.indexOf(ar[i]) === -1) {
				ret.push(ar[i]);
			}
		}
		return ret;
	},
	unique(ar) {
		var ret = [];
		for (var i = 0, j = ar.length; i < j; i++) {
			if (ret.indexOf(ar[i]) === -1) {
				ret.push(ar[i]);
			}
		}
		return ret;
	},

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

	playAudioByName(audioName) {
		return new Promise((resolve, reject) => {
			try {
				const audioNode = cc.find('audio/'+audioName);
				const audioClip = audioNode.getComponent(cc.AudioSource).clip;
				playAudio(audioClip, resolve);
			} catch (e) {
				reject(e);
			}
		});
	},
	// ------------------------------------------

});
