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

cc.Class({

	extends: cc.Component,

	properties: {
		flys:{
			default:[],
			type: cc.Node
		},

		flyPositions:{
			default:[],
			type: cc.Node
		},

		flyVirus:{
			default:[],
			type: cc.Node
		},

		virusOks:{
			default:[],
			type: cc.Node
		},

		fallVirus:{
			default:[],
			type: cc.Node
		},

		titleText:{
			default:null,
			type: cc.Label
		}
	},

	// 生命周期 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()
		});

		this.preView();
	},

	preView(){

		for(let i = 0; i < 2; i ++){
			this.setTextVar(this.flyVirus[i]);
			this.setTextVar(this.virusOks[i]);
			this.setTextVar(this.fallVirus[i]);
		}

		this._area = cc.find('Canvas/bg/flag_area');
		this._area.removeAllChildren();

		let btn = cc.find('Canvas/bg/sound_button');
		console.log(btn);
		
		btn._sprite = btn.children[0];
		console.log(btn._sprite);
		
		btn._sprite.active = false;
		btn.on('click', async ()=>{
			if (this._sound_button.active == false)
				return;

			await this.playAudioSync(this.data[this._index].audio_url);
		});
		this._sound_button = btn;

		this._flower = cc.find('Canvas/flower');
		this._flower.active = false;

		this._comeon = cc.find('Canvas/comeon');
		this._comeon.active = false;

		this.cleanFlys();
		
		this._cup = cc.find('Canvas/bg/cup');
		this._bad_water = this._cup.getChildByName('bad_water');
		this._bad_water.active = false;

		this._flyswatter = cc.find('Canvas/flyswatter');
		this.setOrignPos(this._flyswatter);

		let node = cc.find('Canvas/timer');
		this._time_text = node.getComponent(cc.Label);
		this._time_text.sub = node.children[0].getComponent(cc.Label);
	},

	cleanFlys(){
		for(let i = 0; i < 2; i++){
			this.flys[i].x = this.flys[i]._x + this._frameSize.width * 1.5;
			this.flys[i].y = this.flys[i]._y;
			this.virusOks[i].active = false;
		}
	},

	setTextVar(node){
		node._text = node.getChildByName('word').getComponent(cc.Label);
	},

	setOrignPos(node){
		node._x = node.x;
		node._y = node.y;
	},

	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() {


	},

	addPreloadAudio() {

	},

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


	initView() {
		this._time_node = cc.find('res/time');
		this._index = 0;
		this._time = this.data.time;
		this.titleText.string = this.data.title;
		let audio_url = this.data.audio_url;

		let data = this.shuffle(this.data.sitems);
		this.data = data;

		let bg = cc.find('Canvas/bg');
		for(let i = 0; i < 2; i ++){
			let pos = this.flyPositions[i].convertToWorldSpaceAR(cc.v2(0,0));
			let pos1 = bg.convertToNodeSpaceAR(cc.v2(pos.x, pos.y))
			this.flys[i]._x = pos1.x;
			this.flys[i]._y = pos1.y;
		}
		this.cleanFlys();

		this.updateArea();
		this.updateItem();
		this._cup._y = this._cup.y;

        this._start = cc.find('Canvas/start');
        this._start.on('click',()=>{
			this._start.active = false;
			// let audio_url = this.data.audio_url;
			// if (audio_url && audio_url!=""){
			// 	playAudioByUrl(audio_url, ()=>{
			// 		this.playGame();
			// 	});
			// }
			// else{
				this.playGame();
			// }	
		});

		this.node.on(cc.Node.EventType.TOUCH_START, (event)=>{
			if (this._touched == true)
				return;
			
			if (this._can_hitted == false)
				return;

			let canvas = cc.find('Canvas');
			let pos = canvas.convertToNodeSpaceAR(cc.v2(event.touch._point.x, event.touch._point.y))

			let item;
			for(let i = 0; i < 2; i++){
				item = this.flys[i];
				if (cc.rect(item.getBoundingBoxToWorld()).contains(event.touch._point)){
					this.playAudioByName('dizzy');
					this.playAudioByName('fall');
					this.cleanTimer();
					this._flyswatter.x = pos.x;
					this._flyswatter.y = pos.y;
					this._touched = false;
					playDragonBoneAnimation(this._flyswatter.children[0], 'normal');
					let astr = this.flyVirus[i]._text.string;

					item._dizzy_ani = cc.tween(this._flyswatter)
					//.delay(0.2)
					.call(()=>{
						this.cleanTimer();
						if (item._recount_timer){
							item._recount_timer.stop();
							item._recount_timer = null;
						}
						if (i != this._correct_index){
							console.log('hit err');
							this.sendAnswer(astr);
							
							playDragonBoneAnimation(item, 'dizzy', 1, ()=>{
								playDragonBoneAnimation(item, 'normal', -1);
							});

							item._recount_timer = cc.tween(this._time_node)
							.delay(1)
							.call(()=>{
								this.setTimer();
							})
							.start();
						}
						else{
							console.log('hit ok');
							this.sendAnswer(astr, true);

							this._can_hitted = false;

							this.fallCare();
						}
					})
					.delay(0.1)
					.call(()=>{
						this._flyswatter.y = -10000;
						// cc.tween(this._flyswatter)
						// .to(0.2, {x: this._frameSize.width * 2, y: this._frameSize.height*4})
						// .start();
					})
					.start();
					
					return;
				}
			}

		}, this);
	},

	playGame(){
		//this.playTimer(()=>{
			this.startItem();
		//});
	},

	startItem(){
		if (this._finished == true){
			return;
		}
		
		this._sound_button._sprite.active = true;
		let item = this.data[this._index];

		cc.tween(this._time_node)
		.delay(0.8)
		.call(async ()=>{
			await this.playAudioSync(item.audio_url);
		})
		.start();
		this.flyIn(()=>{
			this.setTimer();
		});
	},

	playTimer(cb){
		this.playAudioByName('time321');
		this._time_text.node.active = true;
		this.setTimerString('3');
		cc.tween(this._time_text.node)
			.to(0.25, {scale: 1.2},{ easing: 'quadIn' })
			.to(0.5, {scale: 0.8},{ easing: 'quadOut' })
			.to(0.25, {scale: 1},{ easing: 'quadIn' })
			.call(()=>{
				this.setTimerString(2);
			})
			.to(0.25, {scale: 1.2},{ easing: 'quadIn' })
			.to(0.5, {scale: 0.8},{ easing: 'quadOut' })
			.to(0.25, {scale: 1},{ easing: 'quadIn' })
			.call(()=>{
				this.setTimerString(1);
			})
			.to(0.25, {scale: 1.2},{ easing: 'quadIn' })
			.to(0.5, {scale: 0.8},{ easing: 'quadOut' })
			.to(0.25, {scale: 1},{ easing: 'quadIn' })
			.call(()=>{
				this._time_text.node.active = false;
				cb && cb();
			})
			.start();
	},

	setTimerString(str){
		this._time_text.string = str;
		this._time_text.sub.string = str;
	},

	setTimer(){
		console.log('time');
		
		this._can_hitted = true;
		this._current_time = this._time_node.x;
		this._timer_ani = cc.tween(this._time_node)
			.to(this._current_time, {x: 0})
			.call(()=>{
				this.flyOut();
				this.sendAnswer();
			})
			.start();

		for(let i = 0; i < 2; i++){
			this.flys[i]._move_to_cup = cc.tween(this.flys[i])
			.to(this._current_time, {y: this.flys[i]._y -110})
			.start();
		}
	},

	cleanTimer(){
		console.log('clean');
		
		if (this._timer_ani){
			this._timer_ani.stop();
			this._timer_ani = null;
		}
		for(let i = 0; i < 2; i++){
			if (this.flys[i]._move_to_cup){
				this.flys[i]._move_to_cup.stop();
				this.flys[i]._move_to_cup = null;
			}
		}
	},

	updateArea(){
		let area = this._area;
		area.removeAllChildren();
		let node = cc.find('res/img/flyswatter');
		let data = this.data;

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

		let item, len = data.length;
		for(let i = 0; i < len; i++){
			item = cc.instantiate(node);
			area.addChild(item);
			item.y = 0;
			item.scale = this.between(0.5, (width/len - padding_x)/item.width, 1);
			item.children[0].active = false;
		}
		this._index = 0;
	},

	getTime(){
		var date = new Date();
		return date.getTime();
	},

	updateItem(){
		this._startTime = this.getTime();
		console.log(this._startTime);
		
		this._tapped = false;
		this._time_node.x = this._time;

		let info = this.data[this._index];
		this._aiexerciseid = info.aiexerciseid;
		// info.correct.length = Math.min(info.correct.length, 3);
		// info.incorrect.length = Math.min(info.incorrect.length, 3);

		this._correct_index = 0;
		let idxs = [info.correct, info.incorrect];
		if (RandomInt(2) == 0){
			idxs = [info.incorrect, info.correct]
			this._correct_index = 1;
		}

		for(let i = 0; i < 2; i++){
			this.flyVirus[i]._text.string = idxs[i];
			this.flyVirus[i]._text.fontSize = 64;
			this.virusOks[i]._text.string = idxs[i];
			this.virusOks[i]._text.fontSize = 64;
			this.fallVirus[i]._text.string = idxs[i];
			this.fallVirus[i]._text.fontSize = 64;
		}
	},

	unitedFontSize(arr, width, size){
		let len = arr.length;
		let maxw = 0;

		for(let i = 0; i < len; i++){
			maxw = Math.max(arr[i]._text.node.width, maxw);
		}

		maxw = Math.max(width, maxw);
		
		let nsize = size * (width/maxw);
		
		for(let i = 0; i < len; i++){
			arr[i]._text.fontSize = nsize;
		}
		return nsize;
	},

	updateFlag(){
		if (this._index >= this.data.length)
			return;
		
		let idx = this.data.length - this._index - 1;
		let area = this._area
		let flag = area.children[idx].getComponent(cc.Sprite);
		flag.enabled = false;

		let flag1 = flag.node.children[0];
		flag1.active = true;
		cc.tween(flag1)
			.to(0.1, {scale: 1.2},{ easing: 'quadIn' })
			.to(0.2, {scale: 0.8},{ easing: 'quadOut' })
			.to(0.1, {scale: 1},{ easing: 'quadIn' })
			.start();
	},

	tryFinish(){
		if (this._finished == true)
			return;

		if (this._timer_ani){
			this._timer_ani.stop();
			this._timer_ani = null;
		}

		this._index ++;
		console.log(this._index,'try');
		
		if (this._index >= this.data.length){
			this._finished = true;

			if (this.allWrong() == true){
				this.playAudioByName('lose');
				this._comeon.active = true;
				playDragonBoneAnimation(this._comeon, 'newAnimation', 1, ()=>{
					this._comeon.active = false;
					this.gameEnd();
				});
			}
			else{
				this.playAudioByName('victory');
				this._flower.active = true;
				playDragonBoneAnimation(this._flower, 'normal', 1, this.gameEnd);
			}
			return;
		}

		this.cupMoveUp();
		this.cleanFlys();
		this.updateItem();
	},

	gameEnd(){
		if (window && window.courseware) {
			window.courseware.gameEnd();
		}
	},

	sendAnswer(answer="", isRight = false){
		console.log(this._aiexerciseid, answer, isRight, this._startTime);
		
		if (window && window.courseware) {
			window.courseware.sendAnswer(this._aiexerciseid, answer, isRight, this._startTime);
		}
	},

	flyIn(cb){
		this.flyVirus[0].active = true;
		this.flyVirus[1].active = true;

		this.unitedFontSize(this.flyVirus, 240, 64);
		for(let i = 0; i < 2; i++){
			if (this.flys[i]._fall_ani != null){
				this.flys[i]._fall_ani.stop();
				this.flys[i]._fall_ani = null;
			}
			this.flys[i].x = this.flys[i]._x + this._frameSize.width * 1.5;
			this.flys[i].y = this.flys[i]._y;
			this.virusOks[i].active = true;
			this.unitedFontSize(this.virusOks, 240, 64);
			this.virusOks[i].active = false;
			this.fallVirus[i].active = true;
			this.unitedFontSize(this.fallVirus, 240, 64);
			this.fallVirus[i].active = false;
		}

		cc.tween(this.flys[0])
			.to(0.8, {x: this.flys[0]._x})
			.start();

		cc.tween(this.flys[1])
			.to(0.8, {x: this.flys[1]._x})
			.call(()=>{
				cb && cb();
			})
			.start();
		
	},

	flyOut(){
		this._sound_button._sprite.active = false;
		this._can_hitted = false;
		this.cleanTimer();

		for(let i = 0; i < 2; i++){
			this.flyVirus[i].active = false;
			this.fallVirus[i].active = true;

			let pos = this.flyVirus[i].convertToWorldSpaceAR(cc.v2(0,0));
			pos.y = pos.y - 23;
			let pos1 = this.fallVirus[i].parent.convertToNodeSpaceAR(cc.v2(pos.x, pos.y));
			this.fallVirus[i].x = pos1.x;
			this.fallVirus[i].y = pos1.y;
			this.fallVirus[i].opacity = 255;

			pos = this.virusOks[i].convertToWorldSpaceAR(cc.v2(0,0));
			pos1 = this.fallVirus[i].parent.convertToNodeSpaceAR(cc.v2(pos.x, pos.y));

			cc.tween(this.fallVirus[i])
			.to(0.2, {x: pos1.x, y: pos1.y, scaleX: 0.811, scaleY: 0.8})
			.to(0.1, {opacity:53.55})
			.call(()=>{
				this.virusOks[i].active = true;
				this.fallVirus[i].active = false;
			})
			.start();

			//y-23
			//move oks scale opacity
			playDragonBoneAnimation(this.flys[i], 'laugh', 1, ()=>{
				playDragonBoneAnimation(this.flys[i], 'normal', -1);
				cc.tween(this.flys[i])
				.to(0.8, {x: this.flys[i]._x - this._frameSize.width * 1.5})
				.start();					
			});
		}
	
		this._bad_water.active = true;
		this._bad_water.opacity = 0;
		cc.tween(this._bad_water)
			.delay(0.2)
			.to(0.1, {opacity: 255})
			.call(()=>{
			})
			.delay(0.5)
			.call(()=>{
				this.cupMoveDown();
			})
			.start();

	},

	fallCare(){
		this.cleanTimer();
		this._can_hitted = false;
		this.updateFlag();
		let fly;
		for(let i = 0; i < 2; i++){
			
			fly = this.flys[i];
			if (fly._recount_timer){
				fly._recount_timer.stop();
				fly._recount_timer = null;
			}

			if (i == this._correct_index){
				playDragonBoneAnimation(fly, 'dizzy', -1);
				fly._fall_ani = cc.tween(fly)
				.to(1, {y: fly._x - this._frameSize.height*1.5})
				.call(()=>{
					fly.x = fly._x + this._frameSize.height*1.5;
					fly.y = fly._y;
				})
				.start();
				continue;
			}

			
			playDragonBoneAnimation(fly, 'scare', -1);
			cc.tween(fly)
			.to(1, {x: fly._x - this._frameSize.width * 1.5})
			.start();
		}

		cc.tween(this._time_node)
		.delay(1)
		.call(()=>{

			for(let i = 0; i < 2; i++){
				this.flys[i].x = this.flys[i]._x + this._frameSize.width * 1.5;
				playDragonBoneAnimation(this.flys[i], 'normal', -1);
			}
			this.tryFinish();
		})
		.start();
	},

	cupMoveUp(){
		this.virusOks[0].active = false;
		this.virusOks[1].active = false;
		this._bad_water.active = false;
		cc.tween(this._cup)
			.to(0.8, {y: this._cup._y}, { easing: 'quadOut' })
			.call(()=>{
				this.startItem();
			})
			.start();
	},

	cupMoveDown(){
		cc.tween(this._cup)
			.delay(1)
			.to(0.8, {y: this._cup._y - 200}, { easing: 'quadIn' })
			.call(()=>{
				this.tryFinish();
			})
			.start();
	},

	allWrong(){
		let item, len = this._area.childrenCount;
		for(let i = 0; i <len; i++){
			item = this._area.children[i];
			if (item.children[0].active == true)
				return false;
		}
		return true;
	},


    async playAudioSync(audio_url){
        if (audio_url && audio_url!=""){
            this.soundAnimationPlay();
            await playAudioByUrlSync(audio_url);
            this.soundAnimationStop();
        }
	},
	
	soundAnimationPlay(){
		this._sound_button.getComponent(cc.Animation).play();
	},

	soundAnimationStop(){
		let btn = this._sound_button;
        btn.getComponent(cc.Animation).stop();
		btn.children[1].active = true;
		btn.children[0].active = false;
	},


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


	// ------------------------------------------
	shuffle(arr) {
		for (let i=arr.length-1; i>=0; i--) {
			let rIndex = Math.floor(Math.random()*(i+1));
			let temp = arr[rIndex];
			arr[rIndex] = arr[i];
			arr[i] = temp;
		}
		return arr;
	},

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

	between(a, b, c) {
        return [a, b, c].sort()[1];
	},
});
