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

cc.Class({

	extends: cc.Component,

	properties: {
		paint: {
			default: null,
			type: cc.Node
		},

		paint2: {
			default: null,
			type: cc.Node
		},

		color_paint: {
			default: null,
			type: cc.Node
		},

		color_selector: {
			default: null,
			type: cc.Node
		},

		coolcat: {
			default: null,
			type: cc.Node
		},

		btn_submit: {
			default: null,
			type: cc.Button
		},

		btn_next: {
			default: null,
			type: cc.Button
		},

		btn_return: {
			default: null,
			type: cc.Button
		},

		color_buttons: {
			default: [],
			type: cc.Button
		}

	},

	ctor() {
		cc.macro.CLEANUP_IMAGE_CACHE = false;
	},

	// 生命周期 onLoad
	onLoad() {
		this._timeoutIds = [];
		this._intervalIds = [];
		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) => {
			this.log('get data:' + data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem();
			this.preView();
		})
	},

	preView() {
		this.coolcat.active = false;
		this._can_tap = false;
		this._submitted = false;

		let item, len = this.color_buttons.length;
		for (let i = 0; i < len; i++) {
			item = this.color_buttons[i];
			this.bindColorButton(item);
		}


		// this._alligator = this.bindAlligator(this.paint);
		// this._alligator2 = this.bindAlligator(this.paint2);
		this._alligator = this.paint.getChildByName("alligator");//children[0];//this.bindAlligator(this.paint);
		this._alligator2 = this.paint2.getChildByName("alligator");;//children[0];//this.bindAlligator(this.paint2);

		// this.bindAlligatorButton(this._alligator);

		this.btn_submit.node.on('click', () => {

			this.submitBtnClick();

			
			// this.playAudioByName('finish', () => {
			// 	playDragonBoneAnimation(this.coolcat, 'normal');
			// 	this._can_tap = true;
			// 	this._submitted = true;
			// });
		});

		if (this.btn_next != null) {
			this.btn_next.node.on('click', () => {
				if (this._can_tap != true)
					return;
				if (this._submitted != true)
					return;
				this._can_tap = false;
				this.playAudioByName('click');
				this.updateItem();
			});
		}

		if (this.btn_return != null) {
			this.btn_return.node.on('click', () => {
				this.playAudioByName('click');
			});
		}
		
		this.paint.on("click",async ()=>{
			// await asyncDelay(0.5);
			cc.log("btnCoolCat");
			if (this._can_tap != true)
			return;
			if (this.isGameEnd) {
				return;
			}
			this._can_tap=false;
			cc.log("paint 点击");
			playDragonBoneAnimation(this.coolcat, 'wrong', -1);
			this.playAudioByUrl(this.data.wrongAudio,()=>{
				playDragonBoneAnimation(this.coolcat, 'normal', -1);
				this._can_tap = true;

			})	
			// this.paintTimeID = setTimeout(() => {
			// }, 500);
		})

		this.paint.active = false;
		this.paint2.active = false;
		this.color_paint.active = false;
		this.coolcat.active = false;
		this.btn_submit.node.active = false;
	},

	submitBtnClick() {
		if (this._can_tap != true)
		return;

		this._can_tap = false;
		if (this.incomplete()) {
			playDragonBoneAnimation(this.coolcat, 'wrong', -1);
			this.playAudioByName('lack', () => {
				playDragonBoneAnimation(this.coolcat, 'normal', -1);
				this._can_tap = true;
			});
			return;
		}

		this.showResult();
		playDragonBoneAnimation(this.coolcat, 'finish', -1);
		this.playAudioByName('click');

		this.playAudioByUrl(this.data.endAudio, () => {
			playDragonBoneAnimation(this.coolcat, 'normal', -1);
			this._can_tap = true;
			this._submitted = true;
			this.showRestartBtn();
		});
	},

	showResult() {
		this.copyColor();
		this.paint.active = false;
		this.paint2.active = true;
		this.color_paint.active = false;
		this.btn_submit.node.active = false;		
	},

	cleanColor() {
		this.color_paint.active = true;
		this.color_selector.active = false;
		this._color = cc.Color.WHITE;
		//this.initAlligator(this._alligator);
		//this.initAlligator(this._alligator2);
		this.paint.active = true;
		this.paint2.active = false;
		this.btn_submit.node.active = false;
	},

	// copyColor() {
	// 	let a1 = this._alligator;
	// 	let a2 = this._alligator2;
	// 	let len = a1.teeth.length;
	// 	for (let i = 0; i < len; i++) {
	// 		a2.teeth[i].color = a1.teeth[i].color;
	// 		a2.teeth[i].word.node.color = a1.teeth[i].word.node.color;
	// 		a2.teeth[i].word.string = a1.teeth[i].word.string;
	// 	}
	// },

	copyColor() {
		let a1 = this._alligator;
		let a2 = this._alligator2;
		let len = a1.teeth.length;
		for (let i = 0; i < len; i++) {			
			let node=cc.instantiate(a1.teeth[i]);
			a2.addChild(node);
			// a2.teeth[i].color = a1.teeth[i].color;
			// a2.teeth[i].word.node.color = a1.teeth[i].word.node.color;
			// a2.teeth[i].word.string = a1.teeth[i].word.string;
		}
	},

	async initAlligator(parent) {
		for(let i=0;i<this.data.images.length;i++){
			let image=this.data.images[i];
			let tooth=await this.getSprNodeByUrl(image.img);
			parent.addChild(tooth);
			// tooth.color = cc.Color.WHITE;
			tooth.painted = null;
		}
		// let tooth, len = node.teeth.length;
		// for (let i = 0; i < len; i++) {
		// 	tooth = node.teeth[i];
		// 	tooth.color = cc.Color.WHITE;
		// 	tooth.word.node.color = cc.Color.BLACK;
		// 	tooth.painted = null;
		// 	tooth.word.string = words[i];
		// }
	},


	// async initAlligator(parent) {
	// 	for(let i=0;i<this.data.images.length;i++){
	// 		let image=this.data.images[i];
	// 		let tooth=await this.getSprNodeByUrl(image.img);
	// 		parent.addChild(tooth);
	// 		// tooth.color = cc.Color.WHITE;
	// 		tooth.painted = null;
	// 	}
	// },

	bindAlligator(parent) {
		let node = parent.children[0];

		let teeth = [];
		let len = node.children.length;
		for (let i = 0; i < len; i++) {
			teeth[i] = node.children[i];
			// teeth[i].word = teeth[i].children[0].getComponent(cc.Label);
		}

		node.teeth = teeth;
		return node;
	},

	bindAlligatorButton(node) {
		let len = node.teeth.length;
		for (let i = 0; i < len; i++) {
			node.teeth[i].t_idx = i;
			this.bindTeethHit(node.teeth[i]);
		}
	},

	bindColorButton(button) {
		var clickEventHandler = new cc.Component.EventHandler();
		clickEventHandler.target = this.node;
		clickEventHandler.component = "Coloring";
		clickEventHandler.handler = "moveSelector";
		clickEventHandler.customEventData = button.node;

		button.clickEvents.push(clickEventHandler);
	},

	moveSelector(event, customEventData) {
		if (this._can_tap != true)
			return;

		this.color_selector.active = true;
		this.color_selector.x = customEventData.x;
		this.color_selector.y = customEventData.y;
		this._color = this.getColor(customEventData.name);
		this.playAudioByName('click');
		playDragonBoneAnimation(this.coolcat, 'normal', -1);
	},

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


	preload() {

		const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

			if (window.air) {
				window.air.onCourseInScreen = (next) => {
					this.loadEnd();
					next();
				}
			} else {
				this.loadEnd();
			}

			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}

			cc.debug.setDisplayStats(false);
		});
	},


	loadEnd() {
		console.log(' in loadEnd');
		this.initView();
	},


	initView() {
		this._textureIdMapDataContainer = {};

		this._index = 0;

		this.updateItem();
		// this._start = cc.find('Canvas/start');
		// this._start.on('click',()=>{
		// 	this._start.active = false;
		// 	this.updateItem();
		// });

		const btnCoolCat = cc.find('Canvas/bg/bottom_area/BtnCoolCat');
		btnCoolCat.off("click");
		btnCoolCat.on('click', () => {
			if(!this._can_tap){
				return;
			}
			this._can_tap=false;
			const btn = cc.find('Canvas/bg/btnReplay');
			cc.audioEngine.stop();
			if (btn.active) {
				playDragonBoneAnimation(this.coolcat, 'finish', -1);
				this.playAudioByUrl(this.data.finishAudio, () => {
					playDragonBoneAnimation(this.coolcat, 'normal', -1);
					this._can_tap=true;
				});
			} else {
				playDragonBoneAnimation(this.coolcat, 'begin', -1);
				this.playAudioByUrl(this.data.startAudio, () => {
					playDragonBoneAnimation(this.coolcat, 'normal', -1);
					this._can_tap=true;
				});
			}
		});
	},

	async updateItem() {
		this._submitted = false;
		this.cleanColor();
		this.coolcat.active = true;

				
		this.color_selector.active = true;
		// this.color_selector.x = this.color_buttons[0].x;
		// this.color_selector.y = this.color_buttons[0].y;
		this._color = this.getColor("f8ed21");

		let spriteFrame=await this.getSpriteFrimeByUrl(this.data.bg);
		let bg1=this.paint.getChildByName("bg_img");
		// this.log("bg:"+bg1.name);
		bg1.getComponent(cc.Sprite).spriteFrame=spriteFrame;

		let bg2=this.paint2.getChildByName("bg_img");
		bg2.getComponent(cc.Sprite).spriteFrame=spriteFrame;

		this._alligator.destroyAllChildren();
		this._alligator2.destroyAllChildren();
		// this._timeoutIds.push(setTimeout(() => {
			await this.initAlligator(this._alligator);
		// }, 1));

		this._alligator = this.bindAlligator(this.paint);
		this._alligator2 = this.bindAlligator(this.paint2);

		this.bindAlligatorButton(this._alligator);

		// console.log(words, answers);
		this._ids=[];
		for(let i=0;i<this.data.images.length;i++){
			this._ids[i]=i;
		}
		// this._ids = answers;
		this._id_count = this._ids.length;


		console.log(' coolcat play ')
		playDragonBoneAnimation(this.coolcat, 'begin', -1);

		console.log(' coolcat play end')

		this.playAudioByUrl(this.data.startAudio, () => {
			playDragonBoneAnimation(this.coolcat, 'normal', -1);
			this._can_tap = true;
		})

		// this.playAudioByName('demo', () => {
		// 	playDragonBoneAnimation(this.coolcat, 'normal');
		// 	this._can_tap = true;
		// });
	},
	
	showRestartBtn() {
		// return;
		const btn = cc.find('Canvas/bg/btnReplay');
		if (btn.canClick) {
		 return;
		}
	  
		btn.active = true;
		btn.canClick = true;
		btn.on('click', () => {
			console.log('汪汪汪');
			cc.director.loadScene('Coloring');
		});
		const circle = cc.find('Canvas/bg/btnReplay/bg_circle');
		cc.tween(circle)
		 .set({ scale: 0.8, opacity: 255 })
		 .to(2, { scale: 1.2, opacity: 0 })
		 .union()
		 .repeatForever()
		 .start();
	   },
	  
	   hideRestartBtn() {
		console.log('hideRestartBtn');
		const btn = cc.find('Canvas/bg/btnReplay');
		if (!btn.canClick) {
		 return;
		}
		btn.canClick = false;
		btn.active = false;
	  
		const circle = cc.find('Canvas/bg/btnReplay/bg_circle');
		circle.stopAllActions();
		circle.scale = 0.8;
		circle.opacity = 255;
	   },
	// showRestartBtn() {
	// 	const btn = cc.find('Canvas/bg/btnReplay');
	// 	btn.active = true;
	// 	btn.off('click');
	// 	btn.on('click', () => {
	// 		console.log('汪汪汪');
	// 		cc.director.loadScene('OP10');
	// 	});

	// 	const circle = cc.find('Canvas/bg/btnReplay/bg_circle');
	// 	cc.tween(circle)
	// 		.set({ scale: 0.8, opacity: 255 })
	// 		.to(2, { scale: 1.2, opacity: 0 })
	// 		.union()
	// 		.repeatForever()
	// 		.start();
	// },

	// hideRestartBtn() {
	// 	console.log('hideRestartBtn');
	// 	const btn = cc.find('Canvas/bg/btnReplay');
	// 	btn.active = false;

	// 	const circle = cc.find('Canvas/bg/btnReplay/bg_circle');
	// 	circle.stopAllActions();
	// 	circle.scale = 0.8;
	// 	circle.opacity = 255;
	// },


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


	async getSpriteFrimeByUrl(url, cb) {
		return new Promise((resolve)=>{
			cc.loader.load({ url }, (err, img) => {
				const spriteFrame = new cc.SpriteFrame(img)
				resolve(spriteFrame);
				// if (cb) {
				// 	cb(spriteFrame);
				// }
			})	
		});
	},

	async getSprNodeByUrl(url) {
		const node = new cc.Node();
		const spr = node.addComponent(cc.Sprite);
		spr.spriteFrame=await this.getSpriteFrimeByUrl(url);
		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) {
			cb && cb();
			return;
		}
		cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
			const audioId = cc.audioEngine.play(audioClip, false, 0.8);
			cc.audioEngine.setFinishCallback(audioId, () => {
				cb && cb();
			});
		});
	},

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

	getColor(hstr) {
		var color = new cc.Color();
		color.fromHEX(hstr);
		return color;
	},

	tryFinish() {
		const isCanFinish = this._ids.every((value) => {
			return value == -1
		})
		console.log('isCanFinish:', isCanFinish);

		if (isCanFinish) {
			this.isGameEnd = true;
			
			this.playAudioByUrl(this.data.finishAudio,()=>{
				this.showRestartBtn();
				onHomeworkFinish();
			});
			this.submitBtnClick();
		}
	},

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

	incomplete() {
		let len = this._ids.length;
		for (let i = 0; i < len; i++) {
			if (this._ids[i] >= 0) {
				return true;
			}
		}
		return false;
	},

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

	bindTeethHit(tooth) {

		let sprite = tooth;
		sprite.on(cc.Node.EventType.TOUCH_START, (e) => {

			if (this.isGameEnd) {
				return;
			}
			console.log('this.isGameEnd: ', this.isGameEnd);

			e.stopPropagation();

			if (this._can_tap != true)
				return;

			if (sprite.painted == true)
				return;

			if (this.color_selector.active == false)
				return;

			this._can_tap = false;
			cc.log("btn teeth");
			// clearTimeout(this.paintTimeID);
			//correct
			playDragonBoneAnimation(this.coolcat, 'right', -1);
			this.playAudioByUrl(this.data.rightAudio,()=>{
				playDragonBoneAnimation(this.coolcat, 'normal', -1);
				this._can_tap = true;

			})
			// this.playAudioByName('correct', () => {
			// 	playDragonBoneAnimation(this.coolcat, 'normal', -1);
			// 	this._can_tap = true;
			// });
			this.playAudioByName('painted');
			this._ids[tooth.t_idx]=-1;
			sprite.painted = true;
			sprite.color = this._color;
			// sprite.word.node.color = cc.Color.WHITE;
			
			this.tryFinish();

			// // console.log('area:' + sprite.t_idx);
			// let find_id = this._ids.indexOf(sprite.t_idx + '');
			// if (find_id >= 0) {
			// 	this._ids[find_id] = -1;
			// 	// if (this.btn_submit.node.active == false) {
			// 	// 	this.btn_submit.node.active = true;
			// 	// }

			// 	//correct
			// 	playDragonBoneAnimation(this.coolcat, 'right', -1);
			// 	this.playAudioByName('correct', () => {
			// 		playDragonBoneAnimation(this.coolcat, 'normal', -1);
			// 		this._can_tap = true;
			// 	});
			// 	this.playAudioByName('painted');
			// }
			// else {
			// 	//incorrect
			// 	this._can_tap = false;
			// 	playDragonBoneAnimation(this.coolcat, 'wrong', -1);
			// 	this.playAudioByName('incorrect', () => {
			// 		playDragonBoneAnimation(this.coolcat, 'normal', -1);
			// 		this._can_tap = true;
			// 	});
			// 	return;
			// }

			// this._ids[tooth.t_idx]=-1;

			// sprite.painted = true;
			// sprite.color = this._color;
			// // sprite.word.node.color = cc.Color.WHITE;
			
			// this.tryFinish();
		});

		sprite._hitTest = this._hitTest.bind(this);
	},

	log(str) {
		const node = cc.find('middleLayer');
		if (node) {
			node.getComponent('middleLayer').log(str);
		} else {
			cc.log(str);
		}
	},

	_hitTest(location, listener) {
		const sprite = listener.owner;

		let spriteFrame = sprite.getComponent(cc.Sprite).spriteFrame;
		if (spriteFrame == null) {
			return false;
		}
		let posInNode = sprite.convertToNodeSpaceAR(location);
		let rect = spriteFrame.getRect();
		let offset = spriteFrame.getOffset();
		if ((posInNode.x < offset.x - (rect.width * sprite.anchorX))
			|| (posInNode.y < offset.y - (rect.height * sprite.anchorY))
			|| (posInNode.x > (offset.x + (rect.width * (1 - sprite.anchorX))))
			|| (posInNode.y > (offset.y + (rect.height * (1 - sprite.anchorY))))) {
			return false;
		}

		if (!this.camera) {
			const checkCameraNode = cc.find('Canvas/CheckCamera');
			if (!checkCameraNode) {
				throw '找不到[Canvas/CheckCamera]。';
			}
			this.camera = checkCameraNode.getComponent(cc.Camera);
		}
		if (this.camera.cullingMask != -2) {
			console.warn(`[${this.camera.cullingMask}]: 检查CheckCamera的cullingMask值，应该只选择camera`);
		}
		this.camera.node.active = true;
		let posInRect = cc.v2(
			parseInt(posInNode.x - offset.x + rect.width * sprite.anchorX),
			parseInt(posInNode.y - offset.y + rect.height * sprite.anchorY)
		);
		let tex = spriteFrame.getTexture();
		this.camera.enable = true;
		let rt;
		let destory = false;
		if (tex instanceof cc.RenderTexture) {
			rt = tex;
		} else {
			rt = new cc.RenderTexture()
			rt.initWithSize(tex.width, tex.height, cc.gfx.RB_FMT_S8);
			rt.drawTextureAt(tex, 0, 0);
			destory = true;
		}
		// data就是这个texture的rgba值数组
		this.camera.targetTexture = rt;
		this.camera.render(undefined);
		let data;
		//图集里的图片可能会旋转
		if (spriteFrame.isRotated()) {
			data = rt.readPixels(null, rect.x + posInRect.y, rect.y + posInRect.x, 1, 1);
		} else {
			data = rt.readPixels(null, rect.x + posInRect.x, rect.y + rect.height - posInRect.y, 1, 1);
		}
		this.camera.targetTexture = null;
		this.camera.enable = false;
		this.camera.node.active = false;

		if (destory) {
			rt.destroy();
		}

		if (data[3] > 0) {
			return true;
		} else {
			return false;
		}
	},

	_timeoutIds: null,
	_intervalIds: null,
	// 生命周期
	onDestroy() {
		cc.macro.CLEANUP_IMAGE_CACHE = true;
		this._timeoutIds.forEach(id => {
			clearTimeout(id);
		});
		this._intervalIds.forEach(id => {
			clearInterval(id);
		});
	},
});
