import { onHomeworkFinish, RandomInt, playAudio, playAudioByUrl, playDragonBoneAnimation } 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
		},

		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._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', ()=>{
			if (this._sound_button.active == false)
				return;
			let item = this.data[this._index];
			if (item.audio_url && item.audio_url!=""){
				playAudioByUrl(item.audio_url);
			}
		});
		this._sound_button = btn;

		this._flower = cc.find('Canvas/flower');
		this._flower.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);
	},

	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))
			console.log(pos);
			console.log(pos1);
			
			
			this.flys[i]._x = pos1.x;
			this.flys[i]._y = pos1.y;
		}
		this.cleanFlys();

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

        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;

			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._flyswatter.x = pos.x;
					this._flyswatter.y = pos.y;
					this._touched = false;
					cc.tween(this._flyswatter)
					.delay(0.5)
					.call(()=>{
						this._flyswatter.y = -10000;
					})
					.start();
					
					this.cleanTimer();
					if (i != this._correct_index){
						playDragonBoneAnimation(item, 'dizzy', 1, ()=>{
							this.setTimer();
							playDragonBoneAnimation(item, 'nomral', -1);
						});
					}
					else{
						this.fallCare();						
					}
					return;
				}
			}

		}, this);
	},

	playGame(){
		this._sound_button._sprite.active = true;
		let item = this.data[this._index];
		if (item.audio_url && item.audio_url!=""){
			playAudioByUrl(item.audio_url);
		}
		this.flyIn(()=>{
			this.setTimer();
		});
	},

	setTimer(){
		this._current_time = this._time_node.x;
		this._timer_ani = cc.tween(this._time_node)
			.to(this._current_time, {x: 0})
			.call(()=>{
				this.flyOut();
			})
			.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 -120})
			.start();
		}
	},

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

	updateItem(){
		this._tapped = false;
		this._time_node.x = this._time;

		let info = this.data[this._index];
		// 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.virusOks[i]._text.string = idxs[i];
		}
	},

	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._timer_ani){
			this._timer_ani.stop();
			this._timer_ani = null;
		}

		this._index ++;
		if (this._index >= this.data.length){
			//this.playAudioByName('victory');
			this._flower.active = true;
			playDragonBoneAnimation(this._flower, 'normal');
			return;
		}

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

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

		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;

		for(let i = 0; i < 2; i++){
			this.flyVirus[i].active = false;
			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();					
			});
		}
	
		cc.tween(this.node)
			.delay(0.2)
			.call(()=>{
				this.virusOks[0].active = true;
				this.virusOks[1].active = true;
				this._bad_water.active = true;
			})
			.delay(0.5)
			.call(()=>{
				this.cupMoveDown();
			})
			.start();

	},

	fallCare(){
		this.updateFlag();
		let fly;
		for(let i = 0; i < 2; i++){
			fly = this.flys[i];
			if (i == this._correct_index){
				playDragonBoneAnimation(fly, 'dizzy', -1);
				cc.tween(fly)
				.to(1, {y: fly._x - this._frameSize.height*1.5})
				.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(()=>{
			playDragonBoneAnimation(this.flys[0], 'normal', -1);
			playDragonBoneAnimation(this.flys[1], 'normal', -1);
			this.cupMoveDown();
		})
		.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.playGame();
			})
			.start();
	},

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

	



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


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