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

cc.Class({

	extends: cc.Component,

	properties: {
		missionOptions:{
			default:[],
			type:cc.Node
		},
		missionOptionTitles:{
			default:[],
			type:cc.RichText
		},
		title:{
			default:null,
			type:cc.Label
		},
		timer:{
			default:null,
			type:cc.Label
		},
		timer1:{
			default:null,
			type:cc.Label
		},
		timerRight:{
			default:null,
			type:cc.Node
		},
		timerRight2:{
			default:null,
			type:cc.Node
		},
		bg00:{
			default:null,
			type:cc.Node
		},
		bg02:{
			default:null,
			type:cc.Node
		},
		bg03:{
			default:null,
			type:cc.Node
		},
		bubble0:{
			default:null,
			type:cc.Node
		},
		bubble1:{
			default:null,
			type:cc.Node
		},
		bubble2:{
			default:null,
			type:cc.Node
		},
		bubble3:{
			default:null,
			type:cc.Node
		},
		bubble11:{
			default:null,
			type:cc.Node
		},
		bubble12:{
			default:null,
			type:cc.Node
		},
		bubble13:{
			default:null,
			type:cc.Node
		},
		bubble21:{
			default:null,
			type:cc.Node
		},
		bubble22:{
			default:null,
			type:cc.Node
		},
		bubble23:{
			default:null,
			type:cc.Node
		},
		comeon:{
			default:null,
			type:cc.Node
		},
		ballani:{
			default:null,
			type:cc.Node
		},
		clicktoplay:{
			default:null,
			type:cc.Node
		},
		audioRight:{
			default:null,
			type:cc.AudioSource
		},
		audioNewMission:{
			default:null,
			type:cc.AudioSource
		},
		audioTree:{
			default:null,
			type:cc.AudioSource
		},
		audioEnd:{
			default:null,
			type:cc.AudioSource
		},
		audioEnd2:{
			default:null,
			type:cc.AudioSource
		},
		audioFail:{
			default:null,
			type:cc.AudioSource
		},
		
	},

	// 生命周期 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.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},


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

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

	initAudio() {
	},

	initView() {

		this.initBg();
		this.title.string = this.data.title;
		this._curMission = 0;
		this.initMissionOptions();
		this.initTimerRight();
		this.updateFlagArea();

		this.nextMission();

	},


	// initBg() {
	// 	const bgNode = cc.find('Canvas/bg');
	// 	bgNode.scale = this._mapScaleMax;
	// },

	pic1: null,
	pic2: null,
	initPic() {
		const canvas = cc.find('Canvas');
		const maxW = canvas.width * 0.7;

	},

	initIcon() {
		const iconNode = this.getSprNode('icon');
		iconNode.zIndex = 5;
		iconNode.anchorX = 1;
		iconNode.anchorY = 1;
		iconNode.parent = cc.find('Canvas');
		iconNode.x = iconNode.parent.width / 2 - 10;
		iconNode.y = iconNode.parent.height / 2 - 10;

		iconNode.on(cc.Node.EventType.TOUCH_START, () => {
			playAudioByUrl(this.data.audio_url);
		})
	},

updateFlagArea(cb){
	this._score = 0;
		let flag_area = cc.find('Canvas/flag_area');
		flag_area.removeAllChildren();
		let node = cc.find('res/img/icon_0');
		let missions = this.data.missions;

		let lyt = flag_area.getComponent(cc.Layout);
		let width = flag_area.width - lyt.paddingRight;
		let padding_x = lyt.spacingX;

		let item, len = missions.length;
		for(let i = 0; i < len; i++){
			item = cc.instantiate(node);
			flag_area.addChild(item);
			item.y = 0;
			item.scale = this.Between(0.5, (width/len - padding_x)/item.width, 1);
		}
		this._flag_index = 0;
		cb && cb();
	},

	setTimerString(str){
		this.timer.string = str;
		this.timer1.string = str;
	},
	playTimer(cb){
		
		this.timer.node.active = true;
		cc.audioEngine.play(this.audioTree.clip, false, 0.8);
		this.setTimerString('3');
		
		cc.tween(this.timer.node)
		.call(()=>{
			
		})
			.to(0.5, {scale: 1.2},{ easing: 'quadInOut' })
			
			.to(0.5, {scale: 0.8},{ easing: 'quadInOut' })
			.call(()=>{
				
				this.setTimerString('2');
			})
			.to(0.5, {scale: 1.2},{ easing: 'quadInOut' })
			.to(0.5, {scale: 0.8},{ easing: 'quadInOut' })
			.call(()=>{
				this.setTimerString('1');
			})
			.to(0.5, {scale: 1.2},{ easing: 'quadInOut' })
			.to(0.5, {scale: 1},{ easing: 'quadInOut' })
			.call(()=>{
				this.timer.node.active = false;
				cb && cb();
			})
			.start();
	},
	initBg(){
		let that = this;
		
		cc.tween(this.bg03)
			// .delay(35)
			.to(50, {x :this.bg03.width+this.bg00.width/2,y :this.bg03.height+this.bg00.height/2}, { easing: 'sineOut' })
			.call(() => {
				that.bg03.x=that.bg00.width/-2;
				that.bg03.y=that.bg00.height/-2;
			})
			.delay(45)
			
			.union()
			.repeatForever()
			.start();

			cc.tween(this.bg02)
			.delay(45)
			.to(50, {x :0-this.bg02.width-this.bg00.width/2}, { easing: 'sineOut' })
			.call(() => {
				that.bg02.x=that.bg00.width/2;
			})
			.union()
			.repeatForever()
			.start();
			let g1 = 13;
			cc.tween(this.bubble1)
			.delay(0)
			.call(() => {
				playDragonBoneAnimation(this.bubble1, 'normal', 1, ()=>{
				});
			})
			.delay(g1)
			.call(() => {
				playDragonBoneAnimation(this.bubble2, 'normal', 1, ()=>{
				});
			})
			.delay(g1)
			.call(() => {
				playDragonBoneAnimation(this.bubble3, 'normal', 1, ()=>{
				});
			})
			.delay(g1)
			.union()
			.repeatForever()
			.start();
			let g2 = 11;
			cc.tween(this.bubble11)
			.delay(g2)
			.call(() => {
				playDragonBoneAnimation(this.bubble13, 'normal', 1, ()=>{
				});
			})
			.delay(g2)
			.call(() => {
				playDragonBoneAnimation(this.bubble11, 'normal', 1, ()=>{
				});
			})
			.delay(g2)
			.call(() => {
				playDragonBoneAnimation(this.bubble12, 'normal', 1, ()=>{
				});
			})
			.union()
			.repeatForever()
			.start();

			let g3 = 17;
			cc.tween(this.bubble21)
			.delay(g3)
			.call(() => {
				playDragonBoneAnimation(this.bubble22, 'normal', 1, ()=>{
					
				});
			})
			.delay(g3)
			.call(() => {
				playDragonBoneAnimation(this.bubble23, 'normal', 1, ()=>{
					
				});
			})
			.delay(g3)
			.call(() => {
				playDragonBoneAnimation(this.bubble21, 'normal', 1, ()=>{
				});
			})
			.union()
			.repeatForever()
			.start();
			
	},
	initTimerRight(){
		this.timerRight.on(cc.Node.EventType.TOUCH_START, () => {
			playAudioByUrl(this._mission_audio_url);
		});
	},
	startRightTime(){
		if (this._time_ani){
			this._time_ani.stop();
			this._time_ani = null;
		}
		if(!this.timerRight._x0){
			this.timerRight._x0 = this.bg00.width/2 + 280;
			this.timerRight._x1 = this.bg00.width/2 - 120;
		}
		this.timerRight.x = this.timerRight._x0;
		this.timerRight.active = true;
		
		this.timerRight2.height = 270;
		cc.tween(this.timerRight)
			// .to(0.5, {x :this.timerRight._x0+160}, { easing: 'bounceInOut' })
			.to(1, {x :this.timerRight._x1}, { easing: 'bounceInOut' })
			.call(() => {
				playAudioByUrl(this._mission_audio_url);
				this._cantouch = true;
				this.doTiming();
			})
			.start();
		

	},
	doTiming(){
		let that = this;
		this._time_ani = cc.tween(this.timerRight2)
		
		.to(this.data.time, {height :0}, { easing: 'smooth' })
		.call(() => {
			if(that._cantouch){
				for(let i = 0; i < 6; i++){
					let node = that.missionOptions[i];
					cc.tween(that.missionOptions[i])
						.to(RandomInt(20,12)/12, {y :node._y0}, { easing: 'quadInOut' })
						
						.start();
				}
				cc.tween(that.timerRight)
					.to(1.5, {x :that.timerRight._x0}, { easing: 'quadInOut' })
					
					.call(() => {
						if(window.courseware){
								// window.courseware.sendAnswer(that.aiexerciseid,"",false,new Date().getTime());
						}
						that.nextMission();
						
					})
					.start();
				
				
			}
			
			
		})
		.start();
	},
	updateFlag(){
		
		this._score++;
		
		let area = cc.find('Canvas/flag_area');
		
		let flag = area.children[area.children.length - this._curMission].getComponent(cc.Sprite);
		flag.enabled = false;

		let flag1 = flag.node.children[2];
		flag1.getComponent(cc.Sprite).enabled = true;
		
			cc.tween(flag1)
			.to(0.1, {scale: 1.3},{ easing: 'quadIn' })
			.to(0.2, {scale: 0.8},{ easing: 'quadOut' })
			.to(0.1, {scale: 1},{ easing: 'quadIn' })
			
			.start();
		
		
	},
	initMissionOptions(){
		let that = this;
		for(let ii = 0; ii < 6; ii++){
			
				this.missionOptions[ii]._y0 = this.missionOptions[ii].y+cc.winSize.height;
				this.missionOptions[ii]._y1 = this.missionOptions[ii].y;
				this.missionOptions[ii]._y2 = this.missionOptions[ii].y-cc.winSize.height;
				this.missionOptionTitles[ii].node._y0 = this.missionOptionTitles[ii].node.y;
				
			
			(function (i) {
				
				that.missionOptions[i].on(cc.Node.EventType.TOUCH_START, (event) => {
					
					if(!that._cantouch){
						return;
					}
					that._cantouch = false;
					let node = that.missionOptions[i];

					if(!node.isResult){
						that._cantouch = true;
						cc.audioEngine.play(that.audioFail.clip, false, 0.8);
						cc.tween(node)
						.by(0.1, {x :30}, { easing: 'bounceInOut' })
						.by(0.2, {x :-60}, { easing: 'bounceInOut' })
						.by(0.1, {x :30}, { easing: 'bounceInOut' })
						.call(() => {
							
						})
						.start();

						if(window.courseware){
							// window.courseware.sendAnswer(that.aiexerciseid,that.missionOptions[i].word,false,new Date().getTime());
						}

					}else{
						for(let j = 0; j < 6; j++){
							if(that.missionOptions[j]!= node){
								cc.tween(that.missionOptions[j])
									.to(RandomInt(20,12)/12, {y :node._y0}, { easing: 'quadInOut' })
									.call(() => {
										// that._cantouch = true;
									})
									.start();

							}else{
								if (that._time_ani){
									that._time_ani.stop();
									that._time_ani = null;
								}
								node.getComponent(cc.Sprite).enabled= false;
								that.ballani.x = node.x;
								that.ballani.y = node.y;
								playDragonBoneAnimation(that.ballani, 'normal', 1, ()=>{
									that.ballani.active = false;
								});
								that.updateFlag();
								cc.audioEngine.play(that.audioRight.clip, false, 0.8);
								cc.tween(that.timerRight)
									.to(1, {x :that.timerRight._x0}, { easing: 'quadInOut' })
									.call(() => {
										// playAudioByUrl(this._mission_audio_url);
										
									})
									.start();
								cc.tween(that.missionOptionTitles[j].node)
									.to(1, {scale :that.missionOptionTitles[j].node.scaleX*2}, { easing: 'backInOut ' })
									.call(() => {
										
										cc.tween(that.missionOptionTitles[j].node)
											.by(0.3, {y :20}, { easing: 'quadInOut' })
											.to(1, {y :0-cc.winSize.height}, { easing: 'quadInOut' })
										.call(() => {
											that.nextMission();
										})
											
											.start();
									})
									
									.start();

									if(window.courseware){
										// window.courseware.sendAnswer(that.aiexerciseid,that.missionOptions[j].word,true,new Date().getTime());
									}

							}
						}
	
					}
				})
			})(ii);
		}

		
	},

	onHomeworkFinish() {
		// TODO 回收成绩

		window.courseware.nextPage();
	},
	
	nextMission(){
		this._mission_audio_url = "";
		this._cantouch = false;
		this._curMission += 1;

		let area = cc.find('Canvas/flag_area');
		if(this._curMission >= 2){
			let flag = area.children[area.children.length - this._curMission + 1].getComponent(cc.Sprite);
			// flag.enabled = false;
			let flag1 = flag.node.children[1].getComponent(cc.Sprite);
			let flag2 = flag.node.children[2].getComponent(cc.Sprite);
			if(!flag2.enabled){
				flag1.enabled = true;
			}
		}

		if(this._curMission > this.data.missions.length){
			for(let i = 0; i < 6; i++){
				this.missionOptions[i].active = false;
			}
			
			if(this._score*100.0/this.data.missions.length >= 60){
				cc.audioEngine.play(this.audioEnd.clip, false, 0.8);
				playDragonBoneAnimation(this.bubble0, 'normal', 1, ()=>{
					this.bubble0.active = false;
				});
			}else{
				cc.audioEngine.play(this.audioEnd2.clip, false, 0.8);
				
				playDragonBoneAnimation(this.comeon, 'newAnimation', 1, ()=>{
					this.comeon.active = false;
				});
			}

			this.onHomeworkFinish();
			return;
		}else{
			
			if(this._curMission >= 1){
				let flag = area.children[area.children.length - this._curMission].getComponent(cc.Sprite);

				let flag0 = flag.node.children[0];
				flag0.getComponent(cc.Sprite).enabled = true;
			}
			
		}
		let mission = this.data.missions[this._curMission - 1];
		this.aiexerciseid = mission.aiexerciseid;
		let maxMissonOption = 0;
		setTimeout(() => {
			cc.audioEngine.play(this.audioNewMission.clip, false, 0.8);
		}, 500);
		
		for(let i = 0; i < 6; i++){
			this.missionOptions[i].getComponent(cc.Sprite).enabled= true;
			this.missionOptions[i].y = this.missionOptions[i]._y2;
			this.missionOptionTitles[i].node.y = this.missionOptionTitles[i].node._y0;
			
			this.missionOptions[i].active = true;
			this.missionOptionTitles[i].string = "";
			this.missionOptionTitles[i].node.scale = 1;
			if(mission.missionOptions.length > i){
				for(let j=0;j<mission.missionOptions[i].wordColors.length;j++){
					if(mission.missionOptions[i].wordColors[j].color === "2"){
						
						this.missionOptionTitles[i].string += `<color=#ce4418 >${mission.missionOptions[i].word.charAt(j)}</c>`;
					}else{
						this.missionOptionTitles[i].string += `<color=#1f4b8e >${mission.missionOptions[i].word.charAt(j)}</c>`;
					}
				}
				
				var titleLen = this.missionOptionTitles[i].node.width;
				if(maxMissonOption < titleLen){
					maxMissonOption = titleLen;
				}
				this.missionOptions[i].isResult = mission.missionOptions[i].isResult;
                this.missionOptions[i].word = mission.missionOptions[i].word;
			}else{
				this.missionOptions[i].isResult = false;
                this.missionOptions[i].word = "";
			}
		}
		if(maxMissonOption > 0){
			maxMissonOption = 120/maxMissonOption;
		}else{
			maxMissonOption = 1;
		}
		if(maxMissonOption > 1){
            maxMissonOption = 1;
		}
		
		for(let i = 0; i < 6; i++){
			this.missionOptionTitles[i].node.scale = maxMissonOption;
			if(!this.missionOptionTitles[i].string){
				this.missionOptions[i].active = false;
				
					
				
			}else{
				if (mission.missionOptions.length > i && mission.missionOptions[i].isResult ){
					this._mission_audio_url = mission.missionOptions[i].audio_url;
					
				}
				this.missionOptions[i].active = true;
				

				cc.tween(this.missionOptions[i])
				.to(RandomInt(20,12)/12, {y :this.missionOptions[i]._y1}, { easing: 'quadInOut' })
				.call(() => {
					
				})
				.start();
				
			}
			
			
		}
		this.startRightTime();
		
	},
	
	Between(a, b, c) {
        return [a, b, c].sort()[1];
	},




















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

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

});
