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

cc.Class({

	extends: cc.Component,

	properties: {
		mouses:{
			default:[],
			type:cc.Node
		},
		title:{
			default:null,
			type:cc.Label
		},
		timer:{
			default:null,
			type:cc.Label
		},
		timer1:{
			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.adjustMousePosition();
		this._flower = cc.find('Canvas/flower');
		this._flower.active = false;
		this._comeon = cc.find('Canvas/comeon');
		this._comeon.active = false;

	},

	adjustMousePosition(){
		let item, len = this.mouses.length;
		let rx = (this._frameSize.width/ this._frameSize.height)/(this._designSize.width/this._designSize.height);
		rx = Math.max(rx, 1);
		
		for(let i = 0; i < len; i++){
			item = this.mouses[i];
			item.x *= rx;
			//item.active = false;
			item._y0 = item.y;
			item._y1 = item.y - item.height*2;
			item.y = item._y1;
		}
	},

	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() {
		window.WL = this;
		this.shuffle(this.data.mouses);
		
		this._touched = false;

		this._hammer = cc.find('Canvas/hammer');

		this.updateFlagArea();

		this.title.string = this.data.title;


        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)
				return;

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

			let item, len = this.mouses.length;
			for(let i = 0; i < len; i++){
				item = this.mouses[i];
				if (item.active && cc.rect(item.getBoundingBoxToWorld()).contains(event.touch._point)){
					this._hammer.x = pos.x;
					this._hammer.y = pos.y;
					this._touched = false;
					this.playAudioByName('correct', ()=>{
						
					});
					cc.tween(item)
						.delay(0.5)
						.call(()=>{
							this.playAudioByName('dizzy');
						})
						.start();
					playDragonBoneAnimation(this._hammer.children[0], 'normal', 1, ()=>{
						this._hammer.y = -1000;
						this.hitMouse(item);
					});
					return;
				}
			}

			let ground = cc.find('Canvas/ground');
			if (cc.rect(ground.getBoundingBoxToWorld()).contains(event.touch._point)){
				this._hammer.x = pos.x;
				this._hammer.y = pos.y;
				this.playAudioByName('incorrect');

				playDragonBoneAnimation(this._hammer.children[0], 'normal', 1, ()=>{
					this._hammer.y = -1000;
				});	
			}

		}, this);
	},

	setLaughAni(){
		this._laugh = cc.tween(this.title.node)
			.delay(3)
			.call(()=>{
				this.playAudioByName('laugh');
				this.setLaughAni();
			})
			.start();
	},

	playGame(){
		this.updateFlagArea(()=>{
			//this.playAudioByName('time321');
			//this.playTimer(()=>{
				this.nextMouse();
			//})
		});
	},

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

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

		let item, len = mouses.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();
	},



	nextMouse(){
		let item, len = this.mouses.length;
		let mouse_id = RandomInt(len)
		let info = this.data.mouses[this._flag_index];
		if (this._time_ani){
			this._time_ani.stop();
			this._time_ani = null;
		}

		for(let i = 0; i < len; i++){
			item = this.mouses[i];
			item.y = item._y1;
			item.active = false;

			if (mouse_id == i){
				item.active = true;
				let mouse = item.getComponent(cc.js.getClassByName('Mouse'));
				mouse.init();
				mouse.setTitle(info.word);
				mouse.audio = info.audio_url;
				mouse.playAudio();
				this.moveUp(mouse.node, ()=>{
					this.setLaughAni();
					this._time_ani = cc.tween(this.node)
						.delay(this.data.time)
						.call(()=>{
							this.moveDown(mouse.node, ()=>{
								this.tryFinished();
							});
						})
						.start();
				});
			}
		}
	},

	moveUp(node, cb){
		cc.tween(node)
			.to(0.3, {y :node._y0})
			.call(()=>{
				cb && cb();
				this._touched = true;
			})
			.start();
	},

	moveDown(node, cb){
		this._touched = false;
		cc.tween(node)
			.to(0.3, {y :node._y1})
			.call(()=>{
				cb && cb();
			})
			.start();
	},
	
	hitMouse(node){
		if (this._time_ani){
			this._time_ani.stop();
			this._time_ani = null;
		}
		if (this._laugh){
			this._laugh.stop();
			this._laugh = null;
		}
		
		let mouse = node.getComponent(cc.js.getClassByName('Mouse'));
		mouse.hit();

		this.updateFlag();
	},

	afterHit(item){
		this.moveDown(item, ()=>{
			this.tryFinished();
		});
	},

	updateFlag(){
		if (this._flag_index >= this.data.mouses.length)
			return;
		
		let idx = this.data.mouses.length - this._flag_index - 1;
		let area = cc.find('Canvas/flag_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();
	},

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

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

		this._flag_index ++;
		if (this._flag_index >= this.data.mouses.length){
			this._finished = true;

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

		this.nextMouse();
	},

	playTimer(cb){
		this.timer.node.active = true;
		this.setTimerString('3');
		cc.tween(this.timer.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.timer.node.active = false;
				cb && cb();
			})
			.start();
	},

	setTimerString(str){
		this.timer.string = str;
		this.timer1.string = str;
	},

	allWrong(){
		let area = cc.find('Canvas/flag_area');
		let len = area.childrenCount;
		for(let i = 0; i < len; i++){
			if (area.children[i].children[0].active == true)
				return false;
		}
		return true;
	},

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

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

});
