// import { getSprNode } from "./util";
import { getSprNode, playAudioByUrl, getRect, delayCall, randomSortByArr, playAudio, showTrebleFirework, RandomInt, asyncDelay, exchangeNodePos, onHomeworkFinish, getSprNodeByUrl, removeItemFromArr, showSRResultByAllRight, addSRAudioDuration } from "./util_demo_jj_game_05";

cc.Class({
	extends: cc.Component,

	properties: {
		baseWidth: 1280,
		baseHeight: 720
	},

	onLoad() {
		cc.debug.setDisplayStats(false);
		this.initSceneData();
		this.initSize();
	},

	initSceneData() {
		this._imageResList = [];
		this._audioResList = [];
		this._animaResList = [];
	},


	_designSize: null,
	_frameSize: null,
	_mapScaleMin: null,
	_mapScaleMax: null,
	_cocosScale: null,
	canvas: null,
	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;

		this.canvas = cc.find('Canvas');
	},

	start() {
		this.getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			this.preloadItem()
		})
	},

	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		// this.addPreloadAnima();
		this.preload();
	},

	getData(func) {
		if (window && window.courseware) {
			window.courseware.getData(func, 'Z_05_nxuan1');
			return;
		}

		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.getData(func);
			return;
		}

		func(this.getDefaultData());
	},

	getDefaultData() {
		const dataJson = '{"groupArr":[{"ques":"","optionArr":[{"text":"AAaa","isEmpty":true,"audio_url":"http://staging-teach.cdn.ireadabc.com/c42408cda175ea4b754b47bba6eeb692.mp3"},{"text":"bbb"},{"text":"ccc","isEmpty":true,"audio_url":"http://staging-teach.cdn.ireadabc.com/3c070a33d021725219ab7eec9e60cb39.mp3"},{"text":"ddddd"},{"text":"ee"},{"text":"fff"}],"wrongArr":[{"text":"zzz"},{"text":"yyyyy"},{"text":"ccc"},{"text":"vvv"},{"text":"bbb"},{"text":"nnnnnn"}],"audio_url":"http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","word_audio_url":"http://staging-teach.cdn.ireadabc.com/85cff126986f5cc11b05e95181da5869.mp3"},{"ques":"","optionArr":[{"text":"aa"},{"text":"cc","isEmpty":true,"audio_url":"http://staging-teach.cdn.ireadabc.com/baae6b4c92d8a95e184d6d18542e0d21.mp3"},{"text":"d"},{"text":"bbbb","isEmpty":true,"audio_url":"http://staging-teach.cdn.ireadabc.com/79a67cfeb1fee086076bc7f46e1524f1.mp3"}],"wrongArr":[{"text":"b2"},{"text":"eee"},{"text":"fff"},{"text":"ggg"},{"text":"hhh"},{"text":"ggg"},{"text":"ccc"}],"pic_url":"http://staging-teach.cdn.ireadabc.com/f6f4bbef497409fef3c8f1d375893829.png","audio_url":"http://staging-teach.cdn.ireadabc.com/440cf9d57752b30691d90ed565e8c924.mp3","word_audio_url":"http://staging-teach.cdn.ireadabc.com/5285e1e88a26a08783757e9c43a8653f.mp3"},{"ques":"","optionArr":[{"text":"wwwwwwwwwww"},{"text":"cc","isEmpty":true}],"wrongArr":[{"text":"v"},{"text":"v"},{"text":"x"},{"text":"z"}],"audio_url":"http://staging-teach.cdn.ireadabc.com/a5fa20e0c6024421b0d9a7007c303503.mp3","word_audio_url":"http://staging-teach.cdn.ireadabc.com/5285e1e88a26a08783757e9c43a8653f.mp3"}],"isHideShadow":true}';
		const data1 = JSON.parse(dataJson);
		return data1;
	},

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

	addPreloadImage() {

		const groupArr = this.data.groupArr;
		if (groupArr) {
			for (let i = 0; i < groupArr.length; i++) {
				this._imageResList.push({ url: groupArr[i].pic_url || '' });
			}
		}
	},

	addPreloadAudio() {

		const groupArr = this.data.groupArr;
		if (groupArr) {
			for (let i = 0; i < groupArr.length; i++) {

				const optionArr = groupArr[i].optionArr;
				for (let j = 0; j < optionArr.length; j++) {
					this._audioResList.push({ url: optionArr[j].audio_url || '' });
				}

				this._audioResList.push({ url: groupArr[i].audio_url || '' });
				this._audioResList.push({ url: groupArr[i].word_audio_url || '' });
			}
		}

	},

	addPreloadAnima() {
		// if (!this.data.hotZoneItemArr) {
		// 	return;
		// }
		// this.data.hotZoneItemArr.forEach((item) => {
		// 	if (item.skeJsonData) {
		// 		this._animaResList.push({ url: item.skeJsonData.url || '' });
		// 		this._animaResList.push({ url: item.texJsonData.url || ''});
		// 		this._animaResList.push({ url: item.texPngData.url || ''});
		// 	}
		// })
	},

	loadEnd() {
		this.initData();
		this.initView();
		this.initListener();
		// this.initMusic();
	},

	initMusic() {
		cc.assetManager.loadRemote(this.data.bg_audio_url, (err, clip) => {
			cc.audioEngine.setMusicVolume(0.3);
			const audioID = cc.audioEngine.playMusic(clip, true);
		});
	},


	groupIndex: null,
	wordDisWidth: null,
	_curShowItem: null,
	emptyGroupArr: null,
	initData() {

		this.groupIndex = 0;
		this.wordDisWidth = 10;

		this.initCurGroup();
		this.initAudioEffect();
	},



	rightClip: null,
	wrongClip: null,
	bigStarClip: null,
	nextClip: null,
	endClip: null,
	initAudioEffect() {
	
		this.rightClip = cc.find('Canvas/res/audio/right').getComponent(cc.AudioSource).clip;
		this.wrongClip = cc.find('Canvas/res/audio/wrong').getComponent(cc.AudioSource).clip;
		this.bigStarClip = cc.find('Canvas/res/audio/big_star').getComponent(cc.AudioSource).clip;
		this.nextClip = cc.find('Canvas/res/audio/next').getComponent(cc.AudioSource).clip;
		this.endClip = cc.find('Canvas/res/audio/end').getComponent(cc.AudioSource).clip;

	},


	curGroup: null,
	initCurGroup() {

		this.curGroup = JSON.parse(JSON.stringify(this.data.groupArr[this.groupIndex]));
	},





	initListener() {

		const canvas = cc.find('Canvas');
		
		let downFlag = false;

		const touchMove = (e) => {
			this.canvasTouchMove(e);
			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_MOVE)) {
				canvas.off(cc.Node.EventType.MOUSE_MOVE, mouseMove)
			}
		}

		const mouseMove = (e) => {
			if (!downFlag) {
				return;
			}
			this.canvasTouchMove(e);
			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
				canvas.off(cc.Node.EventType.TOUCH_MOVE, touchMove)
				this.removeHtmlCanvasListener('touchmove');
			}
		}

		const touchEnd = (e) => {
		
			downFlag = false;
			this.canvasTouchEnd(e);

			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_UP)) {
				canvas.off(cc.Node.EventType.MOUSE_UP, mouseUp)
			}
			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_LEAVE)) {
				canvas.off(cc.Node.EventType.MOUSE_LEAVE, mouseUp)
			}
			this.removeHtmlTouchEnd();
		}

		const mouseUp = (e) => {
	
			downFlag = false;

			this.canvasTouchEnd(e);

			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_END)) {
				canvas.off(cc.Node.EventType.TOUCH_END, touchEnd)
			}
			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_CANCEL)) {
				canvas.off(cc.Node.EventType.TOUCH_CANCEL, touchEnd)
			}
		}
		

		canvas.on(cc.Node.EventType.TOUCH_MOVE, touchMove)
		canvas.on(cc.Node.EventType.MOUSE_MOVE, mouseMove)

		canvas.on(cc.Node.EventType.TOUCH_END, touchEnd)
		canvas.on(cc.Node.EventType.TOUCH_CANCEL, touchEnd)
		canvas.on(cc.Node.EventType.MOUSE_UP, mouseUp)

	},

	removeHtmlCanvasListener(type) {
		const canvasHtml = document.querySelector('canvas');
		canvasHtml.addEventListener(type, (e) => {})
	},	
	removeHtmlTouchEnd() {
		const canvasHtml = document.querySelector('canvas');
		canvasHtml.removeEventListener('touchend', this.htmlCanvasTouchendFunc, this);
	},

	canvasTouchMove(e) {

		if (!this._curShowItem) {
			return;
		}
		const pos = e.getLocation();
		this._curShowItem.x = pos.x - e.currentTarget.width / 2;
		this._curShowItem.y = pos.y - e.currentTarget.height / 2;
	},

	canvasTouchEnd(e) {

		if (!this._curShowItem) {
			return;
		}
		this.checkOnEmptyLetter();
		this._curShowItem = null;
	},






	initView() {

		this.initQuestion();
		this.initAnswerGroup();
		this.initStar();

	},


	bigStarArr: null,
	initStar() {
		const gArr = this.data.groupArr;
		if (gArr.length <= 1) {
			return;
		}

		this.bigStarArr = [];

		let baseX = this.canvas.width / 2 - 80 * this._mapScaleMin;
		let baseY = this.canvas.height / 2 - 80 * this._mapScaleMin;
		let disH = 80 * this._mapScaleMin;
		let disScale = 1;
		if (gArr.length > 5) {
			disH = (400 / gArr.length) * this._mapScaleMin;
			disScale = 5 / gArr.length;
		}
		for (let i = 0; i < gArr.length; i++) {
			const starBg = getSprNode('star_bg');
			this.canvas.addChild(starBg, 2);
			starBg.x = baseX;
			starBg.y = baseY - i * disH;
			starBg.scale = disScale;

			const starTop = getSprNode('star');
			starBg.addChild(starTop);
			starTop.active = false;
			starBg.star = starTop;

			const starBig = getSprNode('icon_bigstar');
			starTop.addChild(starBig);
			starBig.angle = -90;
			starBg.starBig = starBig;

			this.bigStarArr.push(starBg);
		}
	},

	initQuestion() {
		
		this.initQuestionPanel();
		this.initQuestionLabel();
		this.initQuestionSound();

		this.refreshCurPic();

	},

	panel: null,
	soundPanel: null,
	initQuestionPanel() {

		const panel = getSprNode('panel');
		panel.scale = this._mapScaleMin;
		panel.x = 0;
		panel.y = 170 * this._mapScaleMin;
		this.canvas.addChild(panel);
		this.panel = panel;


		this.soundPanel = cc.find('Canvas/sound_bg')
		this.soundPanel.y = panel.y;
		this.soundPanel.scale = this._mapScaleMin;

	},

	refreshCurPic() {



		if (!this.curGroup.pic_url) {
			
				this.panel.active = false;
				// this.panel.x = -this.canvas.width;
				this.soundPanel.active = true;

		}  else {

			this.panel.active = true;
			// this.panel.x = 0;
			this.soundPanel.active = false;
	
		}


		getSprNodeByUrl(this.curGroup.pic_url, (spr) => {

			const oldPic = this.panel.pic;

			const showNewPic = () => {
				cc.tween(spr.node)
					.to(0.3, {opacity: 255}, {easing: "sineInOut"})
					.start();

				this.playQuestionSound();

			}

			const maxW = 489;
			const maxH = 290;
			this.panel.addChild(spr.node);
			spr.node.y = 10;
			const scaleX = maxW / spr.node.width;
			const scaleY = maxH / spr.node.height;
			spr.node.scale = Math.min(scaleX, scaleY);

			this.panel.pic = spr.node;

			spr.node.opacity = 0;


			if (oldPic) {

				cc.tween(oldPic)
					.to(0.2, {opacity: 0}, {easing: "sineOut"})
					.call(() => {
						oldPic.removeFromParent();
						showNewPic();
					})
					.start()
					playAudioByUrl(this.nextClip);


			} else {
				showNewPic();
			}

		
		

		
		});

	},


	soundNode: null,
	soundNodeBig: null,
	initQuestionSound() {

		const soundNode = new cc.Node();
		soundNode.x = this.panel.width / 2 - 30;
		soundNode.y = this.panel.height / 2 - 30
		soundNode.parent = this.panel
		soundNode.zIndex = 12;
		this.soundNode = soundNode;

		const soundAnima = cc.find('Canvas/btn_laba');
		soundAnima.parent = soundNode;
		soundAnima.active = false;
		soundAnima.x = 0;
		soundAnima.y = 0;
		soundNode.anima = soundAnima;

		const soundIcon = getSprNode('btn_laba')
		soundNode.addChild(soundIcon, 2);
		soundNode.icon = soundIcon;

		soundIcon.addComponent(cc.Button);
		soundIcon.on('click', () => {
			this.playQuestionSound();
		})



	
		this.soundNodeBig = cc.find('Canvas/sound_bg');

		const soundAnimaBig = cc.find('Canvas/sound_bg/btn_anima');
		soundAnimaBig.active = false;
		this.soundNodeBig.anima = soundAnimaBig;

		const soundIconBig = cc.find('Canvas/sound_bg/btn_icon');
		this.soundNodeBig.icon = soundIconBig;

		soundIconBig.addComponent(cc.Button);
		soundIconBig.on('click', () => {
			this.playQuestionSound();
		})
		
	},

	playQuestionSound() {
		console.log(' in playQuestionSound')

		this.soundNode.icon.active = false;
		this.soundNodeBig.icon.active = false;
		this.soundNode.anima.active = true;
		this.soundNodeBig.anima.active = true;

		console.log('this.soundNode.anima: ', this.soundNode.anima.active)
		console.log('this.soundNode.anima.parent: ', this.soundNode.anima.parent.active)
		console.log('this.soundNode.anima.parent.parent: ', this.soundNode.anima.parent.parent.active)

		const anim = this.soundNode.anima.getComponent(cc.Animation);
		anim.play('laba');

		const animBig = this.soundNodeBig.anima.getComponent(cc.Animation);
		animBig.play();

		console.log('play 1111');

		playAudioByUrl(this.curGroup.audio_url, () => {
			anim.stop();
			animBig.stop();

			console.log('play 1111');

			this.soundNode.icon.active = true;
			this.soundNodeBig.icon.active = true;
			this.soundNode.anima.active = false;
			this.soundNodeBig.anima.active = false;
			// this.soundNode.anima.active = false;
		});
	},

	wordNode: null,
	initQuestionLabel() {
		const wordNode = new cc.Node();
		wordNode.scale = this._mapScaleMin * 0.9;

		this.emptyGroupArr = [];

		const opArr = this.curGroup.optionArr
		for (let i=0; i<opArr.length; i++) {
			const opData = opArr[i];
			
			// const letterGroup = this.getLetterGroup(opData);
			const letterGroup = this.getWordGroup(opData);
			letterGroup.x = wordNode.width + letterGroup.width / 2;
			wordNode.addChild(letterGroup)
			wordNode.width += letterGroup.width;

			if (opData.isEmpty) {
				this.emptyGroupArr.push(letterGroup);
			}
		}

		// wordNode.x = -wordNode.width / 2;
		wordNode.y = this.panel.y - 247 * this._mapScaleMin;
		this.canvas.addChild(wordNode);
		this.wordNode = wordNode;


		// 设置最大宽度 否则缩放
		const maxW = this.canvas.width * 0.95;
		if (wordNode.width > maxW) {
			wordNode.scale = maxW / wordNode.width;
		}
		


		const totalLen = wordNode.width ;
		for (let i=0; i<wordNode.children.length; i++) {
			wordNode.children[i].x -= totalLen / 2;
		}
	},

	refreshQuestionLabel() {
		

		cc.tween(this.wordNode)
			.to(0.2, {opacity: 0}, {easing: "cubicIn"})
			.call(() => {
				this.resetWordNode();
			})
			.to(0.3, {opacity: 255}, {easing: "cubicInOut"})
			.start();
	},

	resetWordNode() {

		const wordNode = this.wordNode;
		wordNode.width = 0;
		wordNode.removeAllChildren()

		this.emptyGroupArr = [];


		wordNode.y = this.panel.y - 247 * this._mapScaleMin;

		const opArr = this.curGroup.optionArr
		for (let i=0; i<opArr.length; i++) {
			const opData = opArr[i];
			
			// const letterGroup = this.getLetterGroup(opData);
			const letterGroup = this.getWordGroup(opData);
			letterGroup.x = wordNode.width + letterGroup.width / 2;
			wordNode.addChild(letterGroup)
			wordNode.width += letterGroup.width;

			if (opData.isEmpty) {
				this.emptyGroupArr.push(letterGroup);
			}
		}

		// wordNode.x = -wordNode.width / 2;
		wordNode.y = this.panel.y - 247 * this._mapScaleMin;
		


		
		// 设置最大宽度 否则缩放
		const maxW = this.canvas.width * 0.95;
		if (wordNode.width > maxW) {
			wordNode.scale = maxW / wordNode.width;
		}
		


		const totalLen = wordNode.width ;
		for (let i=0; i<wordNode.children.length; i++) {
			wordNode.children[i].x -= totalLen / 2;
		}


	},


	getLetterGroup(data, isCheckEmpty = true) {

		const text = data.text;
		const groupNode = new cc.Node();
		groupNode.width =  this.wordDisWidth;
		groupNode.data = data;
		groupNode.emptyArr = [];
		groupNode.letterArr = [];
		
		const isEmpty = isCheckEmpty ? data.isEmpty : false;

		for (let i=0; i<text.length; i++) {

			let resName = this.getLetterResName(text[i], false)
			console.log('resName: ', resName);
			const letterNode = getSprNode(resName);

			groupNode.addChild(letterNode);
			letterNode.x = groupNode.width + letterNode.width / 2;

			groupNode.width += letterNode.width + this.wordDisWidth;
			groupNode.height = letterNode.height;
			groupNode.letterArr.push(letterNode);

		
			if (isEmpty) {

				const resNameEmpty = this.getLetterResName(text[i], isEmpty)
				const letterNodeEmpty = getSprNode(resNameEmpty);

				groupNode.addChild(letterNodeEmpty);
				letterNodeEmpty.x = letterNode.x
				letterNodeEmpty.y = 12;
				// letterNodeEmpty.scale = letterNode.width / letterNodeEmpty.width;

				groupNode.emptyArr.push(letterNodeEmpty);
			} 

		}

		if (isEmpty) {
			this.hideGroupLetter(groupNode);
		}

		const totalLen = groupNode.width ;
		for (let i=0; i<groupNode.children.length; i++) {
			groupNode.children[i].x -= totalLen / 2;
		}

		return groupNode;
	},

	getWordGroup(data, isCheckEmpty = true, isQuestion = true) {
		const text = data.text;
		const groupNode = new cc.Node();
		groupNode.width =  this.wordDisWidth;
		groupNode.data = data;
		groupNode.emptyArr = [];
		groupNode.letterArr = [];
		
		const isEmpty = isCheckEmpty ? data.isEmpty : false;

		// for (let i=0; i<text.length; i++) {

			const wordNode = this.getWordNode(text, null, isQuestion);

			groupNode.addChild(wordNode);
			wordNode.x = groupNode.width + wordNode.width / 2;

			groupNode.width += wordNode.width + this.wordDisWidth;
			groupNode.height = wordNode.height;
			groupNode.letterArr.push(wordNode);

		
			if (isEmpty) {

				const wordEmptyNode = this.getWordNode(text, true, isQuestion);

				// const resNameEmpty = this.getLetterResName(text[i], isEmpty)
				// const letterNodeEmpty = getSprNode(resNameEmpty);

				groupNode.addChild(wordEmptyNode);
				wordEmptyNode.x = wordNode.x
				// wordEmptyNode.y = 12;

				groupNode.emptyArr.push(wordEmptyNode);

				if (this.data.isHideShadow) {
					wordEmptyNode.opacity = 0;

					const quesBg = getSprNode("ques_bg");
					quesBg.x = wordNode.x;
					quesBg.scaleX = wordEmptyNode.width / quesBg.width;
					groupNode.addChild(quesBg);
					wordEmptyNode.bg = quesBg;
				}
			} 

		// }

		if (isEmpty) {
			this.hideGroupLetter(groupNode);
		}

		const totalLen = groupNode.width ;
		for (let i=0; i<groupNode.children.length; i++) {
			groupNode.children[i].x -= totalLen / 2;
		}

		return groupNode;
	},

	getWordNode(text, isEmpty = false, isQuestion = true) {
	
		const labelNode = new cc.Node();
		const label = labelNode.addComponent(cc.Label);
		label.font = cc.find('Canvas/res/font/MMTextBook_Bold').getComponent(cc.Label).font;
		label.fontSize = 90

		label.string = text;

	

		// label.string = `<size=${size}><color=#52529d>${this.data.title_1 || "" }</color> <color=#5664b9>${this.data.title_1 || "" }</color> </size>`

		const outlineColor = new cc.Color();
		const fontColor = new cc.Color();
		if (isEmpty) {
			cc.Color.fromHEX(outlineColor, '#879cd7');
			cc.Color.fromHEX(fontColor, '#52529d');

			const outline = labelNode.addComponent(cc.LabelOutline);
			outline.width = 2;

			outline.color = outlineColor;
			labelNode.color = fontColor;
			
		} else {

			if (isQuestion) {

				cc.Color.fromHEX(fontColor, '#e2f2f8');
				cc.Color.fromHEX(outlineColor, '#5b5b9c');
			} else {

				cc.Color.fromHEX(fontColor, '#f3b63f');
				cc.Color.fromHEX(outlineColor, '#5b5b9c');
			}
		

			const labelShadow = labelNode.addComponent(cc.LabelShadow);
			labelShadow.offset.y = -5;

			labelShadow.color = outlineColor
			labelNode.color = fontColor;

		}
		
		label.lineHeight = label.fontSize;

		label["_forceUpdateRenderData"](true);
			
		// label.maxWidth = 0;
		// labelNode.x = -10;
		// labelNode.y = 8;
		// label.horizontalAlign = cc.macro.TextAlignment.CENTER

		
	
		return labelNode;
	},




	showGroupLetter(letterGroup) {
		console.log('showGroupLetter : ', letterGroup);
		const {letterArr, emptyArr} = letterGroup;
		for (let i=0; i<letterArr.length; i++) {
			letterArr[i].active = true;
		}
		for (let i=0; i<emptyArr.length; i++) {
			emptyArr[i].active = false;
			if (emptyArr[i].bg) {
				emptyArr[i].bg.active = false;
			}
		}
	},

	hideGroupLetter(letterGroup) {
		const {letterArr, emptyArr} = letterGroup;
		for (let i=0; i<letterArr.length; i++) {
			letterArr[i].active = false;
		}
		for (let i=0; i<emptyArr.length; i++) {
			emptyArr[i].active = true;
		}
	},


	getLetterResName(letter, isEmpty) {
		let resName;
		if (isEmpty) {
			if (/[A-Z]/.test(letter)) {
				resName = `letter_big_bg/${letter.toLowerCase()}2_di`
			} else {
				resName = `letter_small_bg/${letter}_di`
			}
		} else {
			if (/[A-Z]/.test(letter)) {
				resName = `letter_big/${letter.toLowerCase()}2`
			} else {
				resName = `letter_small/${letter}`
			}
		}
		return resName;
	},




	answerGroupArr: null,
	answerNode: null,
	initAnswerGroup(isShowAnima = false, scale = 1) {

		let answerNode;

		if (this.answerNode) {

			this.answerNode.removeFromParent();

			// this.answerNode.width = 0;
		} 
		// else {

			answerNode = new cc.Node();
			answerNode.scale = this._mapScaleMin;
			this.answerNode = answerNode;
			this.canvas.addChild(answerNode);
		// }


		answerNode = this.answerNode;

		const answerDisW = 30;
		const answerArr = this.getAnswerArr()
		const childArr = [];


		const maxW = this.canvas.width * 0.96;
	

		let px, py = 0;
		let isChangeLine = false;
		let line = 0;
		let lineArr = [[], []];
		for (let i=0; i<answerArr.length; i++) {
			const opData = answerArr[i];
			const wordGroup = this.getWordGroup(opData, false, false);
			this.addLetterDragListener(wordGroup);
			this.addLetterSound(opData, wordGroup);

			wordGroup.scale = scale;

			px = answerNode.width + wordGroup.width / 2 * wordGroup.scale;

			//没换过行
			if (!isChangeLine) {

				// 换行啦
				if (px + wordGroup.width /2  * wordGroup.scale> maxW) {
					isChangeLine = true;
					answerNode.width = 0;
					px = wordGroup.width / 2  * wordGroup.scale;
					py -= 100;
					line += 1;
				} 
			} 

			wordGroup.x = px;
			wordGroup.y = py;


					//还不能换行
			answerNode.width += wordGroup.width * wordGroup.scale + answerDisW;
			answerNode.addChild(wordGroup)
	
			childArr.push(wordGroup);

			lineArr[line].push(wordGroup);
		}




		//调下偏移量
		if (isChangeLine) {

			if (answerNode.width > maxW && scale == 1) {
				this.initAnswerGroup(isShowAnima, 0.6)
				return;
			}
			answerNode.width = maxW;
			answerNode.y = 40;
		}
		answerNode.x = -answerNode.width / 2 * answerNode.scale;
		answerNode.y += -230 * this._mapScaleMin;

		this.answerGroupArr = childArr;


		const line1 = lineArr[0];
		const line1LastItem = line1[line1.length - 1];
		const totalLine1 = line1LastItem.x + line1LastItem.width / 2;
		const offX1 = (answerNode.width - totalLine1) / 2
		for (let i=0; i<line1.length; i++) {
			line1[i].x += offX1;
		}

		const line2 = lineArr[1];
		const line2LastItem = line2[line2.length - 1];
		if (line2LastItem) {
			const totalLine2 = line2LastItem.x + line2LastItem.width / 2;
			const offX2 = (answerNode.width - totalLine2) / 2
			for (let i=0; i<line2.length; i++) {
				line2[i].x += offX2;
			}
		}
	
		// 拖拽异常 转一下坐标
		for (let i=0; i<childArr.length; i++) {
			const wordNode = childArr[i];
			const pos = this.canvas.convertToNodeSpaceAR(wordNode.parent.convertToWorldSpaceAR(cc.v2(wordNode.x, wordNode.y)));
			wordNode.x = pos.x;
			wordNode.y = pos.y;
			wordNode.parent = this.canvas;
			// wordNode.zIndex = 2;
			wordNode.scale = answerNode.scale * wordNode.scale;
			wordNode.baseX = wordNode.x;
			wordNode.baseY = wordNode.y;
			wordNode.baseS = wordNode.scale;

			if (isShowAnima) {
				wordNode.opacity = 0;
				cc.tween(wordNode)
					.delay(0.2)
					.to(0.3, {opacity: 255}, {easing: "cubicInOut"})
					.start();
			}
		}
	},

	addLetterSound(opData, letterGroup) {
		if (opData.audio_url) {
			cc.assetManager.loadRemote(opData.audio_url, (err, audioClip) => {
				letterGroup.audioClip = audioClip;
			});
		}
	},

	addLetterDragListener(letterGroup) {
		letterGroup.on(cc.Node.EventType.TOUCH_START, () => {
			
			if (letterGroup.data.isEnd) {
				return;
			}

			this._curShowItem = letterGroup;
			letterGroup.zIndex = 3;

			if (letterGroup.tween) {
				letterGroup.tween.stop();
			}
			this.dragCurItem();
		})
	},

	getAnswerArr() {
		const opArr = this.curGroup.optionArr;

		let answerArr = [];
		for (let i=0; i<opArr.length; i++) {
			if (opArr[i].isEmpty) {
				answerArr.push(opArr[i]);
			}
		}

		answerArr = answerArr.concat(this.curGroup.wrongArr);
		answerArr = randomSortByArr(answerArr);

		return answerArr;
	},

	checkOnEmptyLetter() {

		console.log('emptyGroupArr: ',  this.emptyGroupArr);
		for (let i = 0; i < this.emptyGroupArr.length; i++) {

			const letterGroup = this.emptyGroupArr[i];
			console.log('letterGroup.data: ', letterGroup.data)
			console.log('this._curShowItem.data: ', this._curShowItem.data)
			if (letterGroup.data && letterGroup.data.text == this._curShowItem.data.text) {
				console.log('data in ')
				const worldPos = this._curShowItem.parent.convertToWorldSpaceAR(cc.v2(this._curShowItem.x, this._curShowItem.y));
				const worldRect = letterGroup.getBoundingBoxToWorld();
				if (worldRect.contains(worldPos)) {
				
					console.log('rect in ')
					removeItemFromArr(this.emptyGroupArr, letterGroup);
					this.showLetterSuccess(letterGroup);
					this.checkGroupEnd();
					return;
				}
			}
		}

		this.letterBack();
	},

	letterBack() {
		if (!this._curShowItem) {
			return;
		}
		playAudio(this.wrongClip);

		const item = this._curShowItem;
		item.tween = cc.tween(item)
			.to(0.5, {x: item.baseX, y: item.baseY}, {easing: 'elasticOut'})
			.call(() => {
				item.zIndex = 0;
				item.tween = null;
			})
			.start();
	},


	isDrag: null,
	dragCurItem() {

		this.isDrag = true;
		this.playCurItemAudio();
	},


	playCurItemAnima() {
		if (!this._curShowItem) {
			return;
		}

		const item = this._curShowItem;
		if (item.tween) {
			item.tween.stop();
		}

		const baseS = this._curShowItem.baseS;
		const time = 0.15;
		item.tween = cc.tween(item)
			.to(time* 0.5, {scaleX: baseS * 1.22, scaleY: baseS * 0.78}, {easing: "quadOut"})
			.to(time, {scaleX: baseS * 0.95, scaleY: baseS * 1.05}, {easing: "quadInOut"})
			.to(time, {scaleX: baseS * 1.02, scaleY: baseS * 0.98}, {easing: "quadInOut"})
			.to(time, {scaleX: baseS * 1, scaleY: baseS * 1}, {easing: "quadInOut"})
			.call(() => {
				item.tween = null;
			})
			.start()
	},



	playCurItemAudio() {
		if (!this._curShowItem || !this._curShowItem.audioClip) {
			return;
		}

		this.playCurItemAnima();


		let isTimeEnd, isPlayEnd;
		const playContinue = () => {
			if (!isTimeEnd || !isPlayEnd) {
				return;
			}
			this.playCurItemAudio();
		}
		
		delayCall(0.5, () => {
			if (this.isDestroy) {
				return;
			}

			if (this.isDrag) {
				isTimeEnd = true;
				playContinue();
			}
		})

		this.playEffectByAudioClip(this._curShowItem.audioClip, () => {
			if (this.isDrag) {
				isPlayEnd = true;
				playContinue();
			}
		})

	},

	playEffectByAudioClip(audioClip, cb = null) {
		if (audioClip) {
			// cc.audioEngine.stopAllEffects();
			const id = cc.audioEngine.playEffect(audioClip, false, 0.8);
			if (cb) {
				cc.audioEngine.setFinishCallback(id, () => {
					cb();
				})
			}
			const duration = cc.audioEngine.getDuration(id);
			addSRAudioDuration(duration);
		}
	},

	showLetterSuccess(letterGroup) {
		console.log(' in showLetterSuccess')
		this.showGroupLetter(letterGroup);
		this.showDragSuccessAnima(letterGroup);
		// this._curShowItem.data.isEnd = true;
		this._curShowItem.active = false;
	},

	showDragSuccessAnima(node) {
		const resDragonBone = cc.find("Canvas/res/anima/right")
		const d = cc.instantiate(resDragonBone)
		node.addChild(d, 20);

		playAudio(this.rightClip);
	},

	checkGroupEnd() {
		if (this.emptyGroupArr.length == 0) {


			delayCall(0.4, () => {
				if (this.isDestroy) {
					return;
				}
				
				this.showGroupEndAnima();
				this.playWordAudio();
				this.wrongLetterLeave();
			})
		
			delayCall(3, () => {
				if (this.isDestroy) {
					return;
				}
				
				this.showBigStar();
			})
		}
	},

	wrongLetterLeave() {
		const answerGroupArr = this.answerGroupArr
		for (let i=0; i<answerGroupArr.length; i++) {
			if (answerGroupArr[i].active) {
				this.showLetterLeaveAnima(answerGroupArr[i]);
			}
		}
	},

	showLetterLeaveAnima(letterGroup) {
		letterGroup.data.isEnd = true;
		const time = 1.5;
		cc.tween(letterGroup)
			.delay(Math.random() * 1)
			.to(time, {y: letterGroup.y - this.canvas.height, angle: Math.random() * 520 - 260}, {easing: "cubicIn"})
			.start()

	},

	showGroupEndAnima() {

		const baseS = this.wordNode.scale;
		const time = 1;
		cc.tween(this.wordNode)
			// .to(time* 0.3, {scaleX: baseS * 0.95, scaleY: baseS * 0.95}, {easing: "quadOut"})
			.to(time , {scaleX: baseS * 1.3, scaleY: baseS * 1.3}, {easing: "quintOut"})
			// .to(time, {scaleX: baseS * 0.95, scaleY: baseS * 0.95}, {easing: "sineInOut"})
			// .to(time, {scaleX: baseS * 1.01, scaleY: baseS * 1.01}, {easing: "sineInOut"})
			.delay(0.01)
			.to(time * 0.8, {scaleX: baseS * 1, scaleY: baseS * 1, y: this.wordNode.y - 100 * this._mapScaleMin}, {easing: "quintIn"})
			.call(() => {
			
			})
			.start()

		// cc.tween(this.wordNode) 
		// 	.to(time * 2, {y: this.wordNode.y - 100 * this._mapScaleMin})
		// 	.start();
	},

	playWordAudio() {
		if (this.curGroup.word_audio_url)
		playAudioByUrl(this.curGroup.word_audio_url, () => {

		});
	},


	enterNext() {

	},

	checkGameEnd() {
		if (this.isDestroy) {
			return;
		}
		
		this.groupIndex++;

		if (!this.data.groupArr[this.groupIndex]) {
			console.log('this.gameEnd');
			this.gameEnd();
			return;
		}

		this.initCurGroup();

		this.refreshQuestionLabel();
		this.refreshCurPic();
		this.initAnswerGroup(true);

	},



















	


	holeArr: null,
	initHole() {

		this.holeArr = [];

		const edge = 100 * this._mapScaleMin;
		const itemW = 260 * this._mapScaleMin;
		const disW = (this.canvas.width - edge * 2 - itemW * 4) / 3;
		const baseX = -this.canvas.width / 2 + edge + itemW / 2;

		const disH = 200 * this._mapScaleMin;
		const baseY = -this.canvas.height / 2 + 260 * this._mapScaleMin;
		let j = 0;

		for (let i = 0; i < 8; i++) {
			const hole = this.getHole();
			this.canvas.addChild(hole);
			this.holeArr.push(hole);

			hole.x = baseX + i % 4 * (itemW + disW);
			hole.y = baseY - j * disH;

			if (i == 3) {
				j++;
			}
		}
	},

	bigStarArr: null,
	initStar_() {
		const gArr = this.data.groupArr;
		if (gArr.length <= 1) {
			return;
		}

		this.bigStarArr = [];

		let baseX = this.canvas.width / 2 - 80 * this._mapScaleMin;
		let baseY = this.canvas.height / 2 - 80 * this._mapScaleMin;
		let disH = 80 * this._mapScaleMin;
		let disScale = 1;
		if (gArr.length > 5) {
			disH = (400 / gArr.length) * this._mapScaleMin;
			disScale = 5 / gArr.length;
		}
		for (let i = 0; i < gArr.length; i++) {
			const starBg = getSprNode('star_bg');
			this.canvas.addChild(starBg, 2);
			starBg.x = baseX;
			starBg.y = baseY - i * disH;
			starBg.scale = disScale;

			const starTop = getSprNode('star');
			starBg.addChild(starTop);
			starTop.active = false;
			starBg.star = starTop;

			const starBig = getSprNode('icon_bigstar');
			starTop.addChild(starBig);
			starBig.angle = -90;
			starBg.starBig = starBig;

			this.bigStarArr.push(starBg);
		}
	},


	startBtn: null,
	restartBtn: null,
	initBtn() {

		const btn = cc.find('Canvas/btn_start')
		btn.scale = this._mapScaleMin;
		btn.active = true;
		btn.zIndex = 50;
		btn.on(cc.Node.EventType.TOUCH_START, () => {
			console.log(' in click');
			cc.tween(btn)
				.to(0.05, { scale: 0.9 * this._mapScaleMin })
				.to(0.05, { scale: 1 * this._mapScaleMin })
				.call(() => {
					btn.active = false;
					this.startBtnClicked();
					this.addSoundBtnListner();

				})
				.start();
		})

		this.startBtn = btn;


		const restartBtn = cc.find('Canvas/btn_restart');
		restartBtn.zIndex = 50;
		restartBtn.on(cc.Node.EventType.TOUCH_START, () => {
			console.log(' in click');
			cc.tween(restartBtn)
				.to(0.05, { scale: 0.9 * this._mapScaleMin })
				.to(0.05, { scale: 1 * this._mapScaleMin })
				.call(() => {
					restartBtn.active = false;
					this.restartBtnClicked();
				})
				.start();
		})

		this.restartBtn = btn;
	},

	showSoundBtn() {
		const btn = cc.find('Canvas/btn_laba')
		btn.scale = this._mapScaleMin;
		btn.zIndex = 1;
	},

	startBtnClicked() {
		this.showQuestion(() => {
			cc.tween(this)
				.delay(0.3)
				.call(() => {
					this.showPenguin();
				})
				.start();
		});
		playAudio(this.btnClip);
	},

	restartBtnClicked() {
		this.groupIndex = 0;
		this.initCurGroup();
		this.hideBigStar();
		this.startBtnClicked();
	},

	hideBigStar() {
		if (!this.bigStarArr) {
			return;
		}
		for (let i = 0; i < this.bigStarArr.length; i++) {
			cc.tween(this.bigStarArr[i].star)
				.to(0.5, { scale: 0 }, { easing: 'cubicOut' })
				.start();
		}
	},

	soundAnima: null,
	addSoundBtnListner() {
		const btn = cc.find('Canvas/btn_laba')
		btn.addComponent(cc.Button);
		btn.on('click', () => {
			playAudio(this.btnClip, () => {
				this.showQuestion();
			});
		})
	},

	showQuestion(func) {

		var anim = cc.find('Canvas/btn_laba').getComponent(cc.Animation);
		anim.play();

		playAudioByUrl(this.curGroup.audio_url, () => {
			anim.stop();
			if (func && typeof (func) == 'function') {
				func();
			}
		});



		// // 指定播放 test 动画
		// anim.play('test');

		// // 指定从 1s 开始播放 test 动画
		// anim.play('test', 1);

		// // 使用 play 接口播放一个动画时，如果还有其他的动画正在播放，则会先停止其他动画
		// anim.play('test2');

	},


	getHole() {
		const hole = new cc.Node();
		hole.scale = this._mapScaleMin;

		const holeBg = getSprNode('hole_1');
		hole.addChild(holeBg, 1);

		const holeTop = getSprNode('hole_2');
		hole.addChild(holeTop, 10);

		return hole;
	},



	showPenguin() {

		this.showOnePenguin();
	},

	showOnePenguin() {

		if (this.checkIsGroupEnd()) {
			return;
		}

		const hole = this.getFreeHole();
		if (hole) {

			const penguin = this.getPenguin();
			const optionData = this.getOptionData();
			this.addPenguin(hole, penguin, optionData);

		} else {

			cc.tween(this)
				.delay(0.3)
				.call(() => {
					this.showOnePenguin();
				})
				.start();
		}
	},

	getOptionData() {

		const arr = randomSortByArr(this.curGroup.optionArr);
		return arr[0];
	},


	getPenguin() {

		// console.log('this.penguinPool.length: ', this.penguinPool.length);

		if (this.penguinPool.length > 0) {
			return this.penguinPool.shift();
		}

		const node = new cc.Node();

		const id = RandomInt(1, 2)
		const penguin = getSprNode('penguin_' + id);
		node.penguin = penguin;

		this.addPenguinWrong(node, id);
		this.addTextPanel(node);
		this.addPicPanel(node);
		this.addClickNode(node);

		node.textPanel.y = penguin.height / 2 + node.textPanel.height / 2 - 25;
		node.picPanel.y = penguin.height / 2 + node.picPanel.height / 2 - 25;

		node.addChild(node.picPanel);
		node.addChild(node.textPanel);
		node.addChild(penguin);
		node.addChild(node.wrong);

		return node;
	},

	addClickNode(node) {
		const rectNode = new cc.Node();
		rectNode.addComponent(cc.Button);
		rectNode.width = 270;
		rectNode.height = 180;
		rectNode.anchorX = 0;
		rectNode.anchorY = 0;
		// const ctx = rectNode.addComponent(cc.Graphics);
		// ctx.fillColor = '#f9bd03';
		// ctx.fillRect(0, 0, 270, 180);
		// ctx.stroke();		

		rectNode.on('click', () => {

			this.checkPenguinIsRight(node)
		})

		node.addChild(rectNode, 10);
		rectNode.x = -130;
		rectNode.y = 40;

		rectNode.opacity = 50;
	},

	checkPenguinIsRight(node) {

		if (!node.data) {
			return;
		}
		if (this.isRightDuration) {
			return;
		}

		if (node.data.end) {
			return;
		}

		if (node.data.isRight == '1') {
			this.showPenguinRight(node);
			node.data.end = true;
		} else {
			this.showPenguinWrong(node);
		}
	},

	isRightDuration: null,
	showPenguinRight(node) {

		this.isRightDuration = true;

		this.showAnimaStar(node);
		this.stopPenguin(node);
		this.showRightSound(node);
	},

	showPenguinWrong(node) {
		node.penguin.active = false;
		node.wrong.active = true;

		playAudio(this.wrongClip);
	},

	showAnimaStar(node) {

		const resDragonBone = cc.find("Canvas/res/anima/star")
		const d = cc.instantiate(resDragonBone)
		node.addChild(d, 20);

		d.x = 0;
		d.y = node.textPanel.y;


	},

	checkNextStar(node) {

		const data = node.data;

		console.log('this.curGroup: ', this.curGroup);

		const optionArr = this.curGroup.optionArr
		const index = optionArr.indexOf(data);
		if (index != -1) {
			optionArr.splice(index, 1);
		}



		const isEnd = this.checkIsGroupEnd();
		if (isEnd) {
			this.showBigStar();
		} else {
			cc.tween(this)
				.delay(1)
				.call(() => {
					this.showOnePenguin();
				})
				.start();
		}


		this.hideCurPenguin(node);
		this.isRightDuration = false;


	},

	hideCurPenguin(penguin) {


		const { downY, moveTime, panel, hole } = penguin.hideData;

		cc.tween(penguin)
			.call(() => {
				hidePanel();
			})
			.to(moveTime, { y: downY }, { easing: 'quadInOut' })
			.call(() => {
				penguin.active = false;
				penguin.penguin.active = true;
				penguin.wrong.active = false;

				hole.penguin = null;
				this.penguinPool.push(penguin);

				penguin.moveTween = null;
			})
			.start();


		const hidePanel = () => {

			cc.tween(panel)
				.to(moveTime * 0.3, { opacity: 0 })
				.call(() => {
					panel.active = false;
				})
				.start();
		}
	},

	showBigStar() {
		if (!this.bigStarArr || this.bigStarArr.length <= 0) {
			this.checkGameEnd();
			return;
		}
		const bigStarBg = this.bigStarArr[this.groupIndex];

		const starBig = bigStarBg.starBig;
		starBig.scale = 1;
		const star = bigStarBg.star;
		star.active = true;
		star.scaleX = 0.7 / bigStarBg.scale;
		star.scaleY = 1 / bigStarBg.scale;
		star.angle = 90;
		const canvas = cc.find('Canvas');
		const startPos = exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 2));
		const middlePos = exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 4));
		star.x = startPos.x;
		star.y = startPos.y - starBig.height;

		console.log('middlePos = ' + JSON.stringify(middlePos));
		const time = 1;
		cc.tween(star)
			.to(0.3, { y: middlePos.y + 80 }, { easing: 'quadOut' })
			.to(0.1, { y: middlePos.y + 40, scaleX: 1.2 / bigStarBg.scale, scaleY: 0.8 / bigStarBg.scale }, { easing: 'quadOut' })
			.to(0.1, { y: middlePos.y, scaleX: 1 / bigStarBg.scale, scaleY: 1 / bigStarBg.scale }, { easing: 'quadOut' })
			.delay(0.1)
			.to(0.8, { angle: -720, scale: 1 })
			.start();

		cc.tween(star)
			.delay(0.6)
			.to(0.8, { x: 0 }, { easing: 'quadIn' })
			.start();
		cc.tween(star)
			.delay(0.6)
			.to(0.8, { y: 0 }, { easing: 'quadOut' })
			.start();

		cc.tween(starBig)
			.delay(0.6)
			.to(0.8, { scale: 0 }, { easing: 'quadOut' })
			.call(() => {
				this.checkGameEnd();
			})
			.start();

		// cc.tween(star)
		// 	.to(time, { x: 0 }, { easing: 'quadIn' })
		// 	.start();
		// cc.tween(star)
		// 	.to(time, { angle: -720 })
		// 	.start();
		// cc.tween(star)
		// 	.to(time, { y: 0, scale: 1, opacity: 255 }, { easing: 'quadOut' })
		// 	.call(() => {
		// 		this.checkGameEnd();
		// 	})
		// 	.start();

		// cc.tween(starBig)
		// 	.to(time, { x: 0 }, { easing: 'quadIn' })
		// 	.start();
		// cc.tween(starBig)
		// 	.to(time, { angle: -720 - 90 })
		// 	.start();
		// cc.tween(starBig)
		// 	.to(time, { y: 0, scale: 0 }, { easing: 'quadOut' })
		// 	.start();

		playAudio(this.bigStarClip);
	},


	gameEnd() {
		this.playEndEffect();

		cc.tween(this)
			.delay(0.2)
			.call(() => {
				onHomeworkFinish();
				showSRResultByAllRight();
				this.showRestartBtn();
			})
			.start();
	},

	showRestartBtn() {
		const restartBtn = cc.find('Canvas/btn_restart');
		restartBtn.zIndex = 20;
		restartBtn.active = true;
		restartBtn.scale = 0;

		cc.tween(restartBtn)
			.to(1, { scale: this._mapScaleMin }, { easing: 'elasticOut' })
			.start();


	},

	playEndEffect() {
		playAudio(this.endClip);
		const camera = cc.find('Canvas/Main Camera');
		camera.zIndex = 100;

		showTrebleFirework(camera, cc.find('RibbonNodeBase').children);
	},

	checkIsGroupEnd() {

		const optionArr = this.curGroup.optionArr
		for (let i = 0; i < optionArr.length; i++) {
			if (optionArr[i].isRight == '1') {
				return false;
			}
		}
		return true;
	},

	stopPenguin(node) {
		if (node.moveTween) {
			console.log('node.moveTween: ', node.moveTween);
			node.moveTween.stop();
		}
	},

	showRightSound(node) {
		playAudio(this.rightClip, () => {

			if (!node.data.audio_url) {
				this.checkNextStar(node);
				return;
			}
			playAudioByUrl(node.data.audio_url, () => {
				this.checkNextStar(node)
			})
		});
	},


	addPenguinWrong(node, id) {
		const penguinWrong = getSprNode('penguin_' + id + '_wrong');
		penguinWrong.active = false;
		node.wrong = penguinWrong;
	},


	addTextPanel(node) {
		const textPanel = getSprNode('panel_text');
		textPanel.active = false;
		node.textPanel = textPanel;

		const labelNode = new cc.Node();
		const label = labelNode.addComponent(cc.Label)
		textPanel.addChild(labelNode, 5);
		label.fontSize = 54;
		label.lineHeight = 54;

		label.font = cc.find('Canvas/res/font/Berlin Sans FB').getComponent(cc.Label).font;

		const color = new cc.Color();
		cc.Color.fromHEX(color, 'c1431d');
		labelNode.color = color;

		labelNode.y = -2.5;
		textPanel.label = label;


		textPanel.addComponent(cc.Button)
		textPanel.on('click', () => {
			this.checkPenguinIsRight(node);
		})
	},

	addPicPanel(node) {

		const picPanel = getSprNode('panel_pic');
		picPanel.active = false;
		node.picPanel = picPanel;

		const picNode = new cc.Node();
		const spr = picNode.addComponent(cc.Sprite);
		picPanel.addChild(picNode);

		picNode.y = 0;
		picPanel.spr = spr;


		picPanel.addComponent(cc.Button)
		picPanel.on('click', () => {
			this.checkPenguinIsRight(node);
		})

	},

	getFreeHole() {

		const holeArr = randomSortByArr(this.holeArr)
		for (let i = 0; i < holeArr.length; i++) {
			if (!holeArr[i].penguin) {
				return holeArr[i]
			}
		}
		return null;
	},



	addPenguin(hole, penguin, optionData) {
		penguin.active = true;
		penguin.parent = hole;
		penguin.zIndex = 5;
		hole.penguin = penguin;


		const downY = -180;
		penguin.y = downY;


		let panel;
		if (optionData.type == 'text') {
			panel = penguin.textPanel;
		} else {
			panel = penguin.picPanel;
		}
		this.setPanelData(panel, optionData);


		const moveTime = 0.2 + Math.random() * 0.1;
		const standTime = 1 + Math.random() * 2;


		penguin.hideData = {
			downY, moveTime, panel, hole
		}

		penguin.moveTween = cc.tween(penguin)
			.to(moveTime, { y: 0 }, { easing: 'quadInOut' })
			.delay(standTime)
			.call(() => {
				hidePanel();
			})
			.to(moveTime, { y: downY }, { easing: 'quadInOut' })
			.call(() => {
				penguin.active = false;
				penguin.penguin.active = true;
				penguin.wrong.active = false;

				hole.penguin = null;
				this.penguinPool.push(penguin);

				penguin.moveTween = null;
			})
			.start();




		const nextTime = 0.3 + Math.random() * 2;
		cc.tween(this)
			.delay(nextTime)
			.call(() => {

				if (!this.isRightDuration) {
					this.showOnePenguin();
				}
			})
			.start();




		const showPanel = () => {
			panel.active = true;
			panel.opacity = 0;

			cc.tween(panel)
				.to(moveTime * 0.3, { opacity: 255 })
				.start();
		}

		const hidePanel = () => {

			cc.tween(panel)
				.to(moveTime * 0.3, { opacity: 0 })
				.call(() => {
					panel.active = false;
				})
				.start();
		}

		showPanel();


		playAudio(this.appearClip);
	},

	setPanelData(panel, optionData) {
		panel.data = optionData;
		panel.parent.data = optionData;

		if (optionData.type == 'text') {
			this.setTextPanelData(panel, optionData);
		} else {
			this.setPicPanelData(panel, optionData);
		}
	},

	setTextPanelData(panel, optionData) {

		const panelW = 255;

		panel.label.string = optionData.text;
		panel.label["_forceUpdateRenderData"](true);

		if (panel.label.node.width > panelW) {
			panel.label.node.scale = panelW / panel.label.node.width
		} else {
			panel.label.node.scale = 1;
		}

	},

	setPicPanelData(panel, optionData) {
		cc.loader.load({ url: optionData.pic_url }, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			panel.spr.spriteFrame = spriteFrame


			const panelW = 215;
			const panelH = 135;
			const sx = panelW / img.width;
			const sy = panelH / img.height;
			const s = Math.min(sx, sy);
			panel.spr.node.scale = s;

		})
	},













	_cocosScale: null,
	initBg() {
		const frameSize = cc.view.getFrameSize();

		let sx = cc.winSize.width / frameSize.width;
		let sy = cc.winSize.height / frameSize.height;
		let s = Math.min(sx, sy);

		this._cocosScale = s;

		const bgNode = cc.find('Canvas/bg');
		sx = frameSize.width / bgNode.width;
		sy = frameSize.height / bgNode.height;
		bgNode.scale = Math.max(sx, sy) * s;
		bgNode.anchorX = 1;
		bgNode.anchorY = 0;
		bgNode.x = frameSize.width / 2 * s;
		bgNode.y = -frameSize.height / 2 * s;

		const bg = cc.find('Canvas/bg');
		const rectNode = new cc.Node();
		rectNode.x = -bg.x;
		rectNode.y = -bg.y;
		rectNode.scaleX = bg.scaleX;
		rectNode.scaleY = bg.scaleY;
		bg.addChild(rectNode);
		const ctx = rectNode.addComponent(cc.Graphics);
		ctx.fillColor = this.data.bgColor || '#f9bd03';
		ctx.fillRect(-bg.width / 2, -bg.height / 2, bg.width, bg.height);
		ctx.fill();
	},


	initHotZone() {
		this.initHotZoneBg();
	},


	hotZoneBg: null,
	initHotZoneBg() {
		this.hotZoneBg = new cc.Node();
		this.hotZoneBg.name = 'hotZoneBg';
		this.hotZoneBg.parent = cc.find('Canvas');
		// this.hotZoneBg.zIndex = 4;

		const titleH = 107 * this._mapScaleMin + 11 * 2

		if (!this.data.bgItem) {
			return;
		}

		cc.loader.load({ url: this.data.bgItem.url }, (err, img) => {

			this.hotZoneBg.width = img.width;
			this.hotZoneBg.height = img.height;

			// const tmpS = 640 / 720;
			// let subNum = 720 - 640;
			// const frameSize = cc.view.getFrameSize();
			// const winSize = cc.winSize;

			// console.log('this.hotZoneBg.box: ', this.hotZoneBg.getBoundingBox());
			// console.log('let visiSize=cc.director.getVisibleSize();: ', cc.view.getVisibleSize());
			// console.log('lframeSize: ', frameSize);

			// let sx = frameSize.width / this._designSize.width;
			// let sy = frameSize.height / this._designSize.height;
			// const mapS = Math.min(sx, sy);
			// // const sy = canvas.height * tmpS / box.height;



			//  sx = frameSize.width * this._cocosScale / img.width;
			//  sy = (frameSize.height * this._cocosScale - subNum * mapS * this._cocosScale) / img.height;


			const sprNode = new cc.Node();
			sprNode.name = 'bgItemSpr'
			var sf = new cc.SpriteFrame(img);
			// const spr = this.hotZoneBg.addComponent(cc.Sprite);
			const spr = sprNode.addComponent(cc.Sprite);
			spr.spriteFrame = sf
			sprNode.width = this.hotZoneBg.width;
			sprNode.height = this.hotZoneBg.height;
			sprNode.parent = this.hotZoneBg;
			window['bg'] = sprNode


			const sx = this.canvas.width / this.hotZoneBg.width;
			const sy = (this.canvas.height - titleH) / this.hotZoneBg.height;
			const s = Math.min(sx, sy);
			this.hotZoneBg.scale = s;

			// this.hotZoneBg.y = -frameSize.height / 2 * this._cocosScale + this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY + (subNum * mapS * this._cocosScale);
			this.hotZoneBg.y = 0 - titleH / 2;
			// console.log('this.hotZoneBg.y', this.hotZoneBg.y);




			// this.data.bgItem.isShowDebugLine = true;
			this.initHotZoneItem();



		});

	},

	initHotZoneItem() {
		this.data.hotZoneItemArr.forEach((item) => {
			// console.log('item.gIdx: ', item.gIdx);
			if (item.gIdx == '0') {
				this.setOneAnimaSmall(item);
			} else if (item.gIdx == '1') {
				this.setOnePic(item);
			} else if (item.gIdx == '2') {
				this.setOneRect(item)
			} else if (item.gIdx == '3') {
				this.setOneAction(item);
			}
		});
	},

	setOneAction(data) {
		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;
		const rectNode = new cc.Node();
		rectNode.name = 'rect' + data.index;
		this.hotZoneBg.addChild(rectNode);

		const ctx = rectNode.addComponent(cc.Graphics);
		// 红色矩形
		ctx.lineWidth = 4;
		ctx.strokeColor = cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / this.hotZoneBg.scaleY;

		rectNode.width = data.rect.width * scale;
		rectNode.height = data.rect.height * scale;
		rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;
		const { x, y, width, height } = rectNode;
		rectNode.anchorX = rectNode.anchorY = 0;

		if (this.data.bgItem.isShowDebugLine) {
			ctx.rect(0, 0, rectNode.width, rectNode.height);
		}
		ctx.stroke();
		ctx.fill();



		// console.log('setOneAction ~~ data: ', data)
		const actionData = data['actionData_' + data.gIdx];
		if (actionData && actionData.type == 'text') {
			const label = this.setOneActionText(rectNode, actionData);
			label.node.scale = scale * data.fontScale;

			// label.overflow = cc.Label.Overflow.NONE;
			// label.node.setContentSize(new cc.Size(0, lineHeight));
			label["_forceUpdateRenderData"](true);

			// console.log('label.node.width: ', label.node.width * label.node.scale)
			// console.log('label.node.height: ', label.node.height * label.node.scale)
			// console.log('rectNode.width: ', rectNode.width)
			// console.log('rectNode.height: ', rectNode.height)
			// console.log('label.node.scale: ', label.node.scale)
			// rectNode.width = label.node.width;

			// let textWidth = Math.min(label.node.width, designSize.width);
			// textWidth = Math.floor(textWidth / fontSize) * fontSize;

			// const size = label.getContentSize();
			// console.log('label: ', label)
			// console.log('size: ', size)


		}
	},

	setOneActionText(rectNode, actionData) {


		const labelNode = new cc.Node();
		labelNode.parent = rectNode;
		const label = labelNode.addComponent(cc.Label);

		label.font = cc.find('Canvas/res/font/aharoni').getComponent(cc.Label).font;
		label.string = actionData.text;
		// label.string = `<size=${size}><color=#751e00>${this.curGroup.title }</color></size>`
		// label.lineHeight = size;
		// label.horizontalAlign = cc.macro.TextAlignment.LEFT
		// labelNode.anchorX = 0;
		// labelNode.anchorY = 1
		labelNode.color = cc.Color.BLACK;


		const opArr = actionData.changeOption
		// console.log('opArr', opArr);


		const tweenArr = [];

		for (let i = 0; i < opArr.length; i++) {

			const opData = opArr[i];
			console.log('opArr[0]', opArr[i])
			if (opData[0] == 'fontColor') {
				const color = new cc.Color();
				cc.Color.fromHEX(color, opData[1]);
				labelNode.color = color;

			} else if (opData[0] == 'opacity') {
				// console.log('opData: ', opData)
				labelNode.opacity = Number(opData[1] / 100 * 255) + 0.1;
				// console.log(labelNode.opacity);
				tweenArr.push({ item: labelNode, option: `{"${opData[0]}" : ${opData[2] / 100 * 255}}`, optionName: opData[0] },)

			} else {
				label[opData[0]] = opData[1];
				tweenArr.push({ item: label, option: `{"${opData[0]}" : ${opData[2]}}`, optionName: opData[0] })

			}
		}


		if (actionData.audio_url) {
			cc.assetManager.loadRemote(actionData.audio_url, (err, audioClip) => {
				labelNode.audioClip = audioClip;
			});
		}


		label.lineHeight = label.fontSize;

		labelNode.y += rectNode.height / 2;
		labelNode.x += rectNode.width / 2;


		rectNode.addComponent(cc.Button);
		rectNode.on('click', () => {

			if (labelNode.audioClip) {
				cc.audioEngine.stopAllEffects();
				cc.audioEngine.playEffect(labelNode.audioClip, false, 0.8);
			}

			if (labelNode.isClicked) {
				// return;
			}
			labelNode.isClicked = true;

			// const j = JSON.stringify({'fontSize': 500});
			// console.log('j: ', JSON.parse('{"fontSize":500}'));

			for (let i = 0; i < tweenArr.length; i++) {
				const tweenData = tweenArr[i];

				// JSON.parse(tweenData.option)

				// console.log( JSON.parse(tweenData.option) );

				if (tweenData.optionName == 'opacity') {
					console.log('~~~ ', tweenData.item[tweenData.optionName]);
					// tweenData.item[tweenData.optionName] = tweenData.item[tweenData.optionName] + 1

					cc.tween(tweenData.item)
						.to(actionData.changeTime, JSON.parse(tweenData.option))
						.start();
				}


			}

			// cc.tween({})
			// 	.to(5, { scale: (Math.random() - 0.5) + 1})
			// 	.start();

		});

		// labelNode.opacity = 255;

		return label;
	},



	setOneAnimaSmall(data) {


		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const rectNode = new cc.Node();
		rectNode.name = 'rect' + data.index;
		this.hotZoneBg.addChild(rectNode);


		const ctx = rectNode.addComponent(cc.Graphics);
		// 红色矩形
		ctx.lineWidth = 4;
		ctx.strokeColor = cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / this.hotZoneBg.scaleY;

		rectNode.width = data.rect.width * scale;
		rectNode.height = data.rect.height * scale;
		rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;

		rectNode.anchorX = rectNode.anchorY = 0;


		if (this.data.bgItem.isShowDebugLine) {
			ctx.rect(0, 0, rectNode.width, rectNode.height);
		}
		ctx.stroke();
		ctx.fill();




		const animaNode = new cc.Node();
		animaNode.name = 'anima_' + data.index;
		this.hotZoneBg.addChild(animaNode);



		if (data.audio_url) {
			cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
				animaNode.audioClip = audioClip;
			});
		}


		const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);
		if (!data.texPngData) {
			return
		}

		const image = data.texPngData.url//"http://staging-teach.cdn.ireadabc.com/5a0c5af3e952acd0ac83a6e5c6f03ff1.png";
		const ske = data.skeJsonData.url//"http://staging-teach.cdn.ireadabc.com/bd825dcceea298d1146be8067ae3d17f.json";
		const atlas = data.texJsonData.url//"http://staging-teach.cdn.ireadabc.com/246f8991b729fa3e5a7f4802de828efa.json";
		cc.loader.load(image, (error, texture) => {

			cc.loader.load({ url: atlas, type: 'txt' }, (error, atlasJson) => {

				cc.loader.load({ url: ske, type: 'txt' }, (error, dragonBonesJson) => {

					const atlas = new dragonBones.DragonBonesAtlasAsset();
					atlas.atlasJson = atlasJson;
					atlas.texture = texture;

					const asset = new dragonBones.DragonBonesAsset();
					asset.dragonBonesJson = dragonBonesJson;

					dragonDisplay.dragonAtlasAsset = atlas;
					dragonDisplay.dragonAsset = asset;



					let json = JSON.parse(asset.dragonBonesJson);
					let armatures = json["armature"];
					// console.log('armatures: ', armatures);
					let armatureNames = [];
					for (let i = 0; i < armatures.length; i++) {
						armatureNames.push(armatures[i].name);
					}
					// console.log('armatureNames: ', armatureNames);
					if (armatureNames.length > 0) {
						let defaultArmatureName = armatureNames[0];
						dragonDisplay.armatureName = defaultArmatureName;
						// let animationNames = dragonDisplay.getAnimationNames(defaultArmatureName);
						let defaultArmature = armatures[0];
						let animations = defaultArmature.animation;
						let animationNames = [];
						for (let i = 0; i < animations.length; i++) {
							animationNames.push(animations[i].name);
						}

						rectNode.addComponent(cc.Button);
						rectNode.on('click', () => {
							if (rectNode.isClicked) {
								// return;
							}
							rectNode.isClicked = true;
							console.log('clicked');

							if (animaNode.audioClip) {
								cc.audioEngine.stopAllEffects();
								cc.director.emit('STOP_ALL_AUDIO')
								cc.audioEngine.playEffect(animaNode.audioClip, false, 0.8);
							}

							if (animationNames.length > 0) {
								dragonDisplay.playAnimation(animationNames[0], 1);
							}
						});
					}


					animaNode.x = rectNode.x + rectNode.width / 2;
					animaNode.y = rectNode.y + rectNode.height / 2;

					const sx = rectNode.width / animaNode.width;
					const sy = rectNode.height / animaNode.height;
					const scale = Math.min(sx, sy);
					animaNode.scale = scale;

				});
			});
		});

	},


	setOnePic(data) {
		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const picNode = new cc.Node();
		picNode.name = 'pic' + data.index;
		picNode.data = data;
		this.hotZoneBg.addChild(picNode);

		cc.loader.load({ url: data.pic_url }, (err, img) => {

			const spr = picNode.addComponent(cc.Sprite);
			spr.spriteFrame = new cc.SpriteFrame(img)

			const scale = rate / this.hotZoneBg.scaleY;

			picNode.width = data.rect.width * scale;
			picNode.height = data.rect.height * scale;
			picNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
			picNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;

			picNode.anchorX = picNode.anchorY = 0;

			if (data.audio_url) {
				this.addPicAudio(picNode);
			}

		});

	},

	setOneRect(data) {
		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const rectNode = new cc.Node();
		rectNode.name = 'rect' + data.index;
		this.hotZoneBg.addChild(rectNode);


		const ctx = rectNode.addComponent(cc.Graphics);
		// 红色矩形
		ctx.lineWidth = 4;
		ctx.strokeColor = cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / this.hotZoneBg.scaleY;
		// console.log('scale: ', scale);
		// console.log('scale2: ', scale / data.mapScale);


		rectNode.width = data.rect.width * scale;
		rectNode.height = data.rect.height * scale;
		rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;
		// rectNode.scale = 1 / data.mapScale;

		rectNode.anchorX = rectNode.anchorY = 0;


		if (this.data.bgItem.isShowDebugLine) {
			ctx.rect(0, 0, rectNode.width, rectNode.height);
		}
		ctx.stroke();
		ctx.fill();

		// console.log('```data: ', data)


		if (data.audio_url) {
			cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
				rectNode.audioClip = audioClip;
			});
		}

		rectNode.addComponent(cc.Button);
		rectNode.on('click', () => {
			if (rectNode.isClicked) {
				// return;
			}
			rectNode.isClicked = true;
			console.log('clicked');

			if (rectNode.audioClip) {
				cc.audioEngine.stopAllEffects();
				cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
			}
		});


	},

	addPicAudio(picNode) {
		const data = picNode.data;

		cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
			picNode.audioClip = audioClip;
		});

		picNode.addComponent(cc.Button);
		picNode.on('click', () => {
			if (picNode.audioClip) {
				cc.audioEngine.stopAllEffects();
				cc.audioEngine.playEffect(picNode.audioClip, false, 0.8);
			}
		});
	},

	onDestroy() {
		this.isDestroy = true;
	}

});
