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

cc.Class({

	extends: cc.Component,

	properties: {
	},

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

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


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

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

			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
	},

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

		if (this.data.exercises) {
			// this._imageResList.push({ url: this.data.picUrl });
		}
	},

	addPreloadAudio() {


		if (this.data) {
			this._audioResList.push({ url: this.data.write_big_0_audio_url || '' });
			this._audioResList.push({ url: this.data.write_big_1_audio_url || '' });
			this._audioResList.push({ url: this.data.write_big_2_audio_url || '' });
			this._audioResList.push({ url: this.data.write_small_0_audio_url || '' });
			this._audioResList.push({ url: this.data.write_small_1_audio_url || '' });
			this._audioResList.push({ url: this.data.write_small_2_audio_url || '' });
			this._audioResList.push({ url: this.data.finish_audio_url || '' });
			this._audioResList.push({ url: this.data.tip_audio_url || '' });
		}

		


	},

	addPreloadAnima() {

	},

	preload() {

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

			this.addServerListener();


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

	addServerListener() {

		if (window && window["air"]) {


			// cc.find('Canvas').opacity = 0;
			window.air.onCourseInScreen = (next) => {
				//  cc.find('Canvas').opacity = 255;
				this.loadEnd();
				next();
			}
			window.air.hideAirClassLoading();
		} else {
			this.loadEnd();
		}


		if (window.air) {
			window.air.osmoHandwritingCallback = (data) => {

				if (!data) {
					console.log('data is not exist!!!');
					return;
				}

				console.log('osmoHandwritingCallback data: ', data);

				if (typeof (data) == 'string') {
					console.log('data is string ');
					const dataObj = JSON.parse(data);

					this.photoEnd(dataObj);
					return;
				}

				// 哲学逻辑
				this.photoEnd(data);

			}
		}

	},

	loadEnd() {

		console.log('loadEnd')

		this.initData();
		this.initAudio();
		this.initView();

		// this.initListener();
	},


	step: null,
	canTouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		this.canTouch = false;
		this.step = 1;
	},

	audioBtn: null,
	audioBegin: null,
	audioTipArea: null,
	audioTipLetter: null,
	audioTipIcon: null,
	audioTipSuccess: null,

	audioTipError: null,
	audioTipNotFill: null,
	audioTipFillWrong: null,
	audioOsmoTip: null,
	audioRight: null,
	initAudio() {
		const audioNode = cc.find('Canvas/res/audio');

		const getAudioByResName = (resName) => {
			return audioNode.getChildByName(resName).getComponent(cc.AudioSource);
		}

		this.audioBtn = getAudioByResName('btn');

		this.audioBegin = getAudioByResName('begin');



		this.audioTip1 = getAudioByResName('tip_1');
		this.audioTip2 = getAudioByResName('tip_2');
		this.audioTip3 = getAudioByResName('tip_3');

		this.audioOsmoTip = getAudioByResName('osmo_tip');
		this.audioRight = getAudioByResName('right');

		this.audioDefault = getAudioByResName('default');


	},



	//调起检测
	startTesting() {

		// this.getPhotoData((data) => {
		// 	this.photoEnd(data);
		// });     
		// return;

		const cw = window.courseware;
		if (!cw || !cw.openOsmoHandwriting) {

			console.log('cw.openOsmoHandwriting not exist');
			return;
		}

		const para = {
			'page_id': 5,
			'book_id': 'opw_1',
			'part_name': 'c',
			'is_hand_writing': true,
			'is_line_link': false,
		}
		cw.openOsmoHandwriting(para);


	},

	//结束检测
	endTesting() {
		const cw = window.courseware;
		if (!cw || !cw.closeOsmoHandwriting) {

			return;
		}
		cw.closeOsmoHandwriting();
		// this.isTesting = false;
	},

	isTesting: null,
	initTestingListener() {

		if (window.air) {
			window.air.osmoCallback = (res) => {
				// 哲学逻辑
				console.log('initTestingListener res: ', res);
				this.photoEnd(res);
			}
		}

	},


	initView() {

		this.initBg();

		this.initLetterItem();



		this.initWriteArea(false);
		this.initWriteArea(true);

		this.initDebugLayer();


		this.initCatListener();

		this.gameStart();





	},



	initCatListener() {
		const catBox = cc.find("Canvas/content/catFrame/catBox")
		catBox.on('touchstart', () => {
			if (this.isPlayTip) {
				return;
			}

			if (!this.canTouch) {
				return;
			}


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


			this.isPlayTip = true;

			this.playAni('begin', 0)
			//播放引导音频1
	
			playAudioByUrl(this.data.tip_audio_url, () => {
	
				this.isPlayTip = false;
				this.playAni('normal', 0);
	
			})

		})
	},


	writeNodeArr: null,
	initWriteArea(isSmall) {

		let writeBg;
		if (isSmall) {
			writeBg = this.itemBgSmall;
		} else {
			writeBg = this.itemBgBig;
		}


		const num = 7;

		const edge = 0.05;
		const baseW = 132
		const baseX = 250;
		const baseH = writeBg.height * 0.9;

		
		const writeNodeArr = [];

		for (let i = 0; i < num; i++) {

			const writeNode = new cc.Node();
			writeNode.x = baseX + baseW * i;
			// writeNode.y = -baseH / 2;
			writeNode.width = baseW;
			writeNode.height = baseH;
			writeBg.addChild(writeNode);

			writeNode.hitCount = 0;



			writeNodeArr.push(writeNode);
		}

		if (isSmall) {
			this.writeNodeArr2 = writeNodeArr;
		} else {
			this.writeNodeArr1 = writeNodeArr;
		}
	},



	maskNode: null,
	initMask() {

		const maskNode = new cc.Node();
		maskNode.width = this.canvas.width;
		maskNode.height = this.canvas.height;
		maskNode.anchorX = 0.5;
		maskNode.anchorY = 0.5;
		const mask = maskNode.addComponent(cc.Graphics);
		mask.fillColor = cc.Color.BLACK.setA(100);
		mask.fillRect(-this.canvas.width / 2, -this.canvas.height / 2, this.canvas.width, this.canvas.height);
		this.canvas.addChild(maskNode, 9);

		maskNode.addComponent(cc.BlockInputEvents);
		maskNode.active = false;
		this.maskNode = maskNode;
	},

	addDefaultMusic() {
		// console.log(' in ')
		// playAudio(this.audioDefault.clip, () => {
		// 	console.log(' wusheng end');
		// })
		cc.audioEngine.play(this.audioDefault.clip, true, 0.8);

	},


	initBg() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;

		const canvas = cc.find('Canvas');
		bgNode.scale = Math.max((canvas.width / bgNode.width), (canvas.height / bgNode.height));
		
	},


	letterItemArr: null,
	initLetterItem() {

		this.addLetterItemBig();
		this.addLetterItemSmall();
	
		
	},

	addLetterItemBig() {
		const letterS = this.data.letter.toLowerCase();

		const itemLetterBig = getSprNode('letter/' + letterS + '_1_1');
		// itemLetterBig.x = -this.canvas.width / 2 + 70 * this._mapScaleMin;
		// itemLetterBig.y = 200 * this._mapScaleMin;
		itemLetterBig.scale = this._mapScaleMin;
		itemLetterBig.anchorY = 0.28
		this.canvas.addChild(itemLetterBig);

		const itemBgBig = getSprNode('item_bg');
		itemBgBig.scale = this._mapScaleMin;
		// itemBgBig.x = itemLetterBig.x + 70 * this._mapScaleMin;
		// itemBgBig.y = itemLetterBig.y;
		itemBgBig.anchorX = 0;
		this.canvas.addChild(itemBgBig);
		this.itemBgBig = itemBgBig;

			
		const letterW = 50 * this._mapScaleMin;
		itemBgBig.x = -itemBgBig.width / 2 * itemBgBig.scaleX + letterW;
		itemBgBig.y =  200 * this._mapScaleMin;
		itemLetterBig.x = itemBgBig.x - letterW;
		itemLetterBig.y = itemBgBig.y;



		const letterAnim0 = this.getLetterAnimBig0(letterS.toUpperCase());
		letterAnim0.x = 100;
		this.letterAnimBig = letterAnim0;
		// letterAnim0.y = 30;
		itemBgBig.addChild(letterAnim0);

		const baseX = letterAnim0.x + 150;
		const baseY = letterAnim0.y + 32;
		const disW = 132;
		for (let i=0; i<7; i++) {
			const letterAnim1 = this.getLetterAnimBig1(letterS);
			letterAnim1.x = baseX + i * disW;
			letterAnim1.y = baseY;
			itemBgBig.addChild(letterAnim1);

			if (i < 2) {
				letterAnim1.opacity = 255 * 0.5;
			} else {
				letterAnim1.active = false;
			}
		}
	},

	addLetterItemSmall() {
		const letterS = this.data.letter.toLowerCase();

		const itemLetterSmall = getSprNode('letter/' + letterS + '_0_1');
		// itemLetterSmall.x = -this.canvas.width / 2 + 70 * this._mapScaleMin;
		// itemLetterSmall.y = -30 * this._mapScaleMin;
		itemLetterSmall.scale = this._mapScaleMin;
		this.canvas.addChild(itemLetterSmall);

		const itemBgSmall = getSprNode('item_bg');
		itemBgSmall.scale = this._mapScaleMin;
		// itemBgSmall.x = itemLetterSmall.x + 70 * this._mapScaleMin;
		// itemBgSmall.y = itemLetterSmall.y;
		itemBgSmall.anchorX = 0;
		this.canvas.addChild(itemBgSmall);
		this.itemBgSmall = itemBgSmall;


		const letterW = 50 * this._mapScaleMin;
		itemBgSmall.x = -itemBgSmall.width / 2 * itemBgSmall.scaleX + letterW;
		itemBgSmall.y =  -30 * this._mapScaleMin;
		itemLetterSmall.x = itemBgSmall.x - letterW;
		itemLetterSmall.y = itemBgSmall.y;


		const letterAnim0 = this.getLetterAnimSmall0(letterS.toLowerCase());
		letterAnim0.x = 100;
		letterAnim0.y = 7;
		letterAnim0.opacity = 160;
		this.letterAnimSmall = letterAnim0;

		itemBgSmall.addChild(letterAnim0);

		const baseX = letterAnim0.x + 150;
		const baseY = 4;
		const disW = 132;
		for (let i=0; i<7; i++) {
			const letterAnim1 = this.getLetterAnimSmall1(letterS);
			letterAnim1.x = baseX + i * disW;
			letterAnim1.y = baseY;

			if (i < 2) {
				letterAnim1.opacity = 255 * 0.5;
			} else {
				letterAnim1.active = false;
			}

			itemBgSmall.addChild(letterAnim1);
		}
	},

	getLetterAnimBig0(resName) {

		const anim = cc.find("Canvas/res/anim/" + resName + "_0")
		const letter = cc.instantiate(anim);
		// letter.scale *= 0.588;
		letter.name = resName;

		letter.on('touchstart', ()=> {

			if (!this.canTouch) {
				return;
			}
			this.canTouch = false;
			const letterAnim = letter.getComponent(cc.Animation);
			letterAnim.play('anim_A_0');

			const cb = () => {
				this.canTouch = true;
				letterAnim.off('finished', cb)
			}
			letterAnim.on('finished', cb);

		})


		return letter;

		// const sprNode = getSprNode('letter/' + letter + '_1_0');
		// return sprNode;
	},

	getLetterAnimBig1(letter) {
		const sprNode = getSprNode('letter/' + letter + '_1_1');
		return sprNode;
	},

	getLetterAnimSmall0(resName) {

		const anim = cc.find("Canvas/res/anim/" + resName + "_0")
		const letter = cc.instantiate(anim);
		// letter.scale *= 0.588;
		letter.name = resName;


		letter.on('touchstart', ()=> {

			if (!this.canTouch) {
				return;
			}
			this.canTouch = false;
			const letterAnim = letter.getComponent(cc.Animation);
			letterAnim.play('anim_a_0');

			const cb = () => {
				this.canTouch = true;
				letterAnim.off('finished', cb)
			}
			letterAnim.on('finished', cb);

		})


		return letter;

		// const sprNode = getSprNode('letter/' + letter + '_0_0');
		// return sprNode;
	},

	getLetterAnimSmall1(letter) {
		const sprNode = getSprNode('letter/' + letter + '_0_1');
		return sprNode;
	},





	debugLayer: null,
	initDebugLayer() {
		const layer = new cc.Node();
		layer.x = -this.canvas.width / 2 + 10;
		layer.y = this.canvas.height / 2 - 10;
		// layer.active = false;

		const sample = getSprNode('sample');
		sample.anchorX = 0;
		sample.anchorY = 1;
		this.sample = sample;
		sample.scale = 0.7;
		layer.addChild(sample);

		const topLeftRect = [
			{x1: 0.28, y1:0.127},
			{x2: 0.373, y2:0.127},
			{x3: 0.373, y3:0.215},
			{x4: 0.28, y4:0.215},
		]

		this.dotArr1 = [];

		const disW = 0.093;// * sample.width;
		// const disH = 0.13;// * sample.height;
		// let row = 0;
		let col = 0;
		for (let i=0; i<7; i++) {

			const posArr = JSON.parse(JSON.stringify(topLeftRect))
			posArr[0].x1 += col * disW;
			posArr[1].x2 += col * disW;
			posArr[2].x3 += col * disW;
			posArr[3].x4 += col * disW;


			let color = 'blue';
			if (i % 2 == 0) {
				color = 'yellow'
			}

			const colorRect = this.getColorRectByPos(posArr, color)

			sample.addChild(colorRect);

			this.dotArr1.push(colorRect);

			col ++;

		}




		const topLeftRect2 = [

			{x1: 0.28, y1:0.227},
			{x2: 0.373, y2:0.227},
			{x3: 0.373, y3:0.315},
			{x4: 0.28, y4:0.315},
		]

		this.dotArr2 = [];

		// const disW = 0.093;// * sample.width;
		// const disH = 0.13;// * sample.height;
		// let row = 0;
		col = 0;
		for (let i=0; i<7; i++) {

			const posArr = JSON.parse(JSON.stringify(topLeftRect2))
			posArr[0].x1 += col * disW;
			posArr[1].x2 += col * disW;
			posArr[2].x3 += col * disW;
			posArr[3].x4 += col * disW;


			let color = 'yellow';
			if (i % 2 == 0) {
				color = 'blue'
			}

			const colorRect = this.getColorRectByPos(posArr, color)

			sample.addChild(colorRect);

			this.dotArr2.push(colorRect);

			col ++;

		}





		this.canvas.addChild(layer)
		this.debugLayer = layer;
	},


	getColorRectByPos(posArr, color='red') {
		const topLeft = posArr[0];
		const bottomRight = posArr[2];

		const sample = this.sample;
		const x = topLeft.x1 * sample.width;
		const y = topLeft.y1 * sample.height;
		const width = (bottomRight.x3 - topLeft.x1) * sample.width;
		const height = (bottomRight.y3 - topLeft.y1) * sample.height;
		const rect = {x, y: -y - height, width, height};

		// console.log('rect ', rect);
		const colorRect = this.getColorRect(rect, color);
		colorRect.opacity = 100;
		return colorRect;
	},


	gameStart() {

		this.beginShowAudio();
	},

	beginShowAudio() {


		this.canTouch = false;

		const playEnd = () => {

			this.isPlayTip = false;
			this.playAni('normal', 0);
			// this.startTesting();

			this.showBigLetterAnim();
		}


		if (!this.data.write_big_0_audio_url) {
			playEnd();
			return;
		}

		this.isPlayTip = true;
		this.playAni('begin', 0)
		//播放引导音频1
		playAudioByUrl(this.data.write_big_0_audio_url, () => {
			playEnd();
		})
	},

	showBigLetterAnim() {
		console.log(' in showBigLetterAnim')
		const anim = this.letterAnimBig.getComponent(cc.Animation);

		anim.play('anim_A_0');
		const cb = () => {
			console.log('in finished');
			this.showBigLetter1Audio();
			anim.off('finished', cb)
		}

		anim.on('finished', cb);
	},

	showBigLetter1Audio() {

		const playEnd = () => {

			this.playAni('normal', 0);
			this.canTouch = true;
			this.startTesting();

			// this.showBigLetterAnim();
		}


		if (!this.data.write_big_1_audio_url) {
			playEnd();
			return;
		}

		this.playAni('begin', 0)
		//播放引导音频1
		playAudioByUrl(this.data.write_big_1_audio_url, () => {
			playEnd();
		})
	},






	showSecondLetter() {
		this.showLetter(1, () => {

			playAudio(this.audioTip3.clip, () => {

				// })
				//播放引导音频3
				// this.playAudioByUrl(this.data.guideAudioUrl3, () => {

				// state.stop();

				// this.playAni('normal', 0);

				// this.showPhotoBtn();

				this.showAllSound();
				this.showPhotoBtn();

				this.playAni('normal', 0);

			});

		})
	},

	showLetter(index, cb, isSmall) {


		let writeRect;

		if (isSmall) {
			writeRect = this.writeNodeArr2[Number(index)];
		} else {
			writeRect = this.writeNodeArr1[Number(index)];
		}

		writeRect.hitCount++;
		if (writeRect.hitCount < 1) {
			return;
		}

		if (writeRect.isShowEnd) {
			return;
		}
		writeRect.isShowEnd = true;

		const letterAnim = this.getLetterAnim(isSmall);

		letterAnim.parent = writeRect;

		// letterAnim.x = writeRect.width / 2;
		// letterAnim.y = writeRect.height / 2;

		this.showItemAniNew(letterAnim, () => {

			if (!this.isGameEnd) {
				this.checkGameEnd();

			}
		})

		playAudio(this.audioRight.clip);

	},

	checkGameEnd() {
		return;
		const writeNodeArr = this.writeNodeArr;
		const isEnd = writeNodeArr.every(node => {
			return node.isShowEnd;
		})

		if (isEnd) {
			this.gameEnd();
		} else {


			this.endTesting();

			setTimeout(() => {
				this.startTesting();
			}, 8000);

		}
	},

	isGameEnd: null,
	gameEnd() {

		this.isGameEnd = true;
		console.log('in gameEnd');
		this.endTesting();
	},

	getLetterAnim(isSmall) {

		let resName;
		if (isSmall) {
			resName = this.data.letter.toLowerCase();
		} else {
			resName = this.data.letter.toUpperCase();
		}
		const anim = cc.find("Canvas/res/anim/" + resName)
		const letter = cc.instantiate(anim);
		letter.scale *= 0.588;
		letter.name = resName;

		if (!isSmall) {
			letter.anchorY = 0.28
		}

		return letter;
	},

	showItemAniNew(item, cb) {
		if (item.isShow) {
			return;
		}
		item.isShow = true;
		item.active = true;

		const anim = item.getComponent(cc.Animation);
		console.log(' showItemAniNew  item: ', item);

		anim.play(item.name);
		anim.on('finished', () => {
			console.log('in finished');
			if (cb) {
				cb();
			}
		});

	},

	showItemAni(item, cb) {
		if (item.isShow) {
			return;
		}
		item.isShow = true;

		item.opacity = 0;
		item.active = true;
		cc.tween(item)
			.to(1, { opacity: 255 })
			.call(() => {
				if (cb) {
					cb();
				}
			})
			.start();
	},

	showAllSound() {
		const letterItemArr = this.letterItemArr;
		for (let i = 0; i < letterItemArr.length; i++) {
			const item = letterItemArr[i];
			this.showItemAni(item.btnSound);
		}
	},




	playAni(name, times = 1) {

		const cat = cc.find('Canvas/content/catFrame/cat');

		var dragonDisplay = cat.getComponent(dragonBones.ArmatureDisplay);

		const state = dragonDisplay.playAnimation(name, times);
		return state;
	},

	playTipAni(name, times = 1, cb = null) {

		const tip = cc.find('Canvas/tipFrame/tip');
		tip.parent.zIndex = 10;
		tip.active = true;

		var dragonDisplay = tip.getComponent(dragonBones.ArmatureDisplay);

		const state = dragonDisplay.playAnimation(name, times);

		dragonDisplay.on(dragonBones.EventObject.COMPLETE, () => {
			tip.active = false;
			if (cb) {
				cb();
			}
		})

		return state;
	},

	moveHand(index, callback = null) {

		let textNode = cc.find("Canvas/content/bg_green/bg_word-background/text");

		let wordNodeArr = textNode.wordNodeArr

		let wordNode = wordNodeArr[2 * index];

		if (!wordNode) {

			if (callback) {
				callback();
			}
			return;
		}

		let handNode = cc.find("Canvas/content/bg_green/bg_word-background/text/icon_hand");
		handNode.x = wordNode.x;

		this.handAni();

		if (callback) {
			callback();
		}
	},

	/**
	 * 播放文本音频
	 * @param {*} callback 
	 */
	playTextAutio(callback = null) {

		this.playAudioByUrl(this.data.exercises.audioUrl, () => {

			//停止监听动画
			this._stopAni = true;

			if (callback) {
				callback();
			}
		}, (audioId) => {

			//显示完成，不再播放动画
			if (this._shown) {
				return;
			}

			//设置可播放动画
			this._stopAni = false;

			//隐藏手指
			let handNode = cc.find("Canvas/content/bg_green/bg_word-background/text/icon_hand");
			handNode.opacity = 0;

			let lyrics = this.data.exercises.lrcData.lyrics;

			//临时音频打点数组
			let arr = JSON.parse(JSON.stringify(lyrics));
			console.log(arr);

			this.monitor(audioId, arr);
		})
	},

	/**
	 * 重新设置文字位置
	 */
	resetTextPosition() {

		let textNode = cc.find("Canvas/content/bg_green/bg_word-background/text");

		let wordNodeArr = textNode.wordNodeArr;

		//间隔
		let space = 40;

		let tW = 0;

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

			let wordNode = wordNodeArr[i];
			wordNode.removeFromParent();
			wordNode.parent = textNode;
			tW += wordNode.width;

			let widget = wordNode.getComponent(cc.Widget);
			widget.bottom = - wordNode.getComponent(cc.Label).fontSize / 2;
			widget.updateAlignment();

			wordNode.initScale = wordNode.scale;
		}

		tW += (this.data.exercises.wordArr.length - 1) * space;

		let startX = -  tW / 2;

		for (let i = 0; i < wordNodeArr.length; ++i) {
			let width = wordNodeArr[i].width;
			wordNodeArr[i].x = startX + width / 2;
			startX += width;

			if (wordNodeArr[i].isInitial) {
				continue;
			}
			startX += space;
		}

		if (tW > textNode.width) {
			const sx = textNode.width / tW;

			textNode.scale = Math.round(sx * 1000) / 1000;

			textNode.initScale = textNode.scale;
		}
	},


	/**
	 * 显示结束
	 */
	_shown: null,
	showEnd() {

		console.log(' in showEnd');

		if (this._curIndex < this.data.exercises.wordArr.length) {
			return;
		}

		if (this._shown) {
			return;
		}

		this._shown = true;

		let handNode = cc.find("Canvas/content/bg_green/bg_word-background/text/icon_hand");
		handNode.opacity = 0;
		this._stop = true;

		//播放动画
		const state = this.playAni('finish', 0);

		//播放引导音频2
		this.playAudioByUrl(this.data.guideAudioUrl2, () => {

			state.stop();

			this.playAni('normal', 0);

			this.showPhotoBtn();
		});


	},

	_stop: null,
	_tween: null,
	handAni() {

		let handNode = cc.find("Canvas/content/bg_green/bg_word-background/text/icon_hand");

		handNode.opacity = 255;
		handNode.y = handNode.initY;
		const move = () => {
			this._tween = cc.tween(handNode)
				.to(0.5, { y: handNode.initY + 50 })
				.to(0.5, { y: handNode.initY })
				.call(() => {

					if (!this._stop) {
						move()
					}
				})
				.start();
		}

		this._stop = false;

		move();
	},

	_stopAni: null,
	monitor(audioId, arr) {

		if (this._stopAni) {
			return;
		}

		this._stopAni = false;

		let currentTime = cc.audioEngine.getCurrentTime(audioId);

		let len = arr.length;

		for (let i = len - 1; i >= 0; --i) {

			let time = arr[i].time;

			time = Math.round(time * 1000) / 1000;

			currentTime = Math.round(currentTime * 1000) / 1000;

			if (time < currentTime) {

				//如果是最后一个匹配，则播放内容动画
				if (len == 1) {
					this.contentAni();
				}
				else {
					this.textAni();
				}

				//移除匹配上的元素
				arr.splice(i, 1);

				break;
			}

		}

		requestAnimationFrame(() => {

			this.monitor(audioId, arr);
		})
	},

	/**
	 * 文本动画
	 */
	_playText: null,
	textAni() {

		if (this._playText) {
			return;
		}

		this._playText = true;

		this.canTouch = false;

		const twinkle = (node) => {
			cc.tween(node)
				.to(0.3, { scale: node.initScale * 1.5 })
				.to(0.3, { scale: node.initScale })
				.call(() => {
					this._playText = false;
				})
				.start();
		};

		let textNode = cc.find("Canvas/content/bg_green/bg_word-background/text");

		let wordNodeArr = textNode.wordNodeArr;

		for (let i = 0; i < wordNodeArr.length; ++i) {
			let wordNode = wordNodeArr[i];

			//如果是首字母，则执行动画
			if (wordNode.isInitial) {
				twinkle(wordNode);
			}
		}

	},


	/**
	 * 内容动画
	 */
	contentAni() {

		let handNode = cc.find("Canvas/content/bg_green/bg_word-background/text/icon_hand");
		handNode.opacity = 0;

		const twinkle = (node) => {
			cc.tween(node)
				.to(0.5, { scale: node.initScale * 1.1 })
				.to(0.5, { scale: node.initScale })
				.to(0.5, { scale: node.initScale * 1.1 })
				.to(0.5, { scale: node.initScale })
				.call(() => {
					this.canTouch = true;
				})
				.start();
		};

		let textNode = cc.find("Canvas/content/bg_green/bg_word-background/text");

		twinkle(textNode);
	},



	photoBtn: null,
	initPhotoBtn() {

		const canvas = cc.find('Canvas');

		const photoBtn = this.getSprNode('btn_photo');
		photoBtn.active = false;
		canvas.addChild(photoBtn);
		photoBtn.scale = this._mapScaleMin;
		// photoBtn.x = 100;
		photoBtn.y = -canvas.height / 2 + photoBtn.height / 2 * photoBtn.scaleY;
		photoBtn.addComponent(cc.Button);
		photoBtn.on('click', () => {
			this.showPhotoTip();
		})

		this.photoBtn = photoBtn;
	},

	showPhotoBtn() {
		if (!this.photoBtn) {
			this.initPhotoBtn();
		}
		this.photoBtn.active = true;
	},

	hidePhotoBtn() {
		if (!this.photoBtn) {
			return;
		}
		this.photoBtn.active = false;
	},

	showPhotoTip() {

		this.maskNode.active = true;
		playAudio(this.audioOsmoTip.clip);
		this.playAni('begin', 0)
		this.playTipAni('normal', 1, () => {
			console.log('play ani end');

			this.playAni('normal', 0)


			this.photoBtnClick();

		})


	},

	isOpenPhotoCheck: null,
	openPhotoData() {
		this.isOpenPhotoCheck = true;
	},

	closePhotoData() {
		this.isOpenPhotoCheck = true;
	},


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

		if (!window || !window.courseware) {
			console.log('window.courseware not found')
			return;
		}


		// window.courseware.openRecognitionCamera = this.getPhotoData.bind(this);

		const openRecognitionCamera = window.courseware.openRecognitionCamera;
		if (!openRecognitionCamera) {
			console.log('openRecognitionCamera not found')
			return;
		}
		openRecognitionCamera((data) => {
			console.log('openRecognitionCamera data: ', data)

			this._timeoutIds.push(setTimeout(() => {

				if (typeof data == 'string') {
					data = JSON.parse(data);
				}

				const { result } = data;
				this.photoEnd(result);

				this.maskNode.active = false;
			}, 100));



		})

	},

	photoEnd(data) {

		console.log(' this.photo end');

		// const result = data.result;
		// for (let i=0; i<result.length; i++) {
		// 	result[i].top *= 400;
		// 	result[i].bottom *= 400;
		// 	result[i].left *= 400;
		// 	result[i].right *= 400;
		// }

			
		// this.topTitleData = null;
		// this.bottomTitleData = null;


		// const isRightArea1 = this.checkIsRightArea(data, false);
		// const isRightArea2 = this.checkIsRightArea(data, true);
		// if (!isRightArea1 && !isRightArea2) {
		// 	// playAudio(this.audioTipArea.clip)
		// 	console.log('没有检测到此题的区域')
		// 	return;
		// }


		// this.debugLayer.removeAllChildren();

		this.sample.removeAllChildren();
		for (let i=0; i<this.dotArr1.length; i++) {
			this.dotArr1[i].parent = this.sample;
		}
		for (let i=0; i<this.dotArr2.length; i++) {
			this.dotArr2[i].parent = this.sample;
		}
		
		// this.colorRectTop = null;


		const answerData1 = this.getAnswerDataNew(data, false);
		const answerData2 = this.getAnswerDataNew(data, true);



		this.showUserRight(answerData1, false);
		this.showUserRight(answerData2, true);


		const oldStep = this.step;
		this.checkShowStepAudio();
		if (oldStep != this.step) {
			this.showStepAudio();
		}

		// const isFillAll = this.checkIsFillAll(answerData);
		// if (!isFillAll) {
		// 	// playAudio(this.audioTipNotFill.clip)
		// 	// playAudio(this.audioTipFillWrong.clip)

		// 	// console.log('这道题还有空没填哦')
		// 	return;
		// }

		// // const isFillWrong = this.checkIsFillWrong(answerData);
		// // if (!isFillWrong) {
		// // 	playAudio(this.audioTipFillWrong.clip)

		// // 	console.log('这道题有空填错了哦')
		// // 	return;
		// // }

		// this.showPhotoSuccess();

	},

	showStepAudio() {

		switch(this.step) {
			case 2:
				this.playAudioStep2();
				break;
			case 3:
				this.playAudioStep3();
				break;
			case 4:
				this.playAudioStep4();
				break;
			case 5:
				this.playAudioStep5();
				break;
		}

	
	},

	playAudioStep2() {
		playAudioByUrl(this.data.write_big_2_audio_url, () => {
			this.canTouch = true;
		});
	},

	playAudioStep3() {
		this.beginShowAudioSmall();
	},

	playAudioStep4() {
		playAudioByUrl(this.data.write_small_2_audio_url, () => {
			this.canTouch = true;
		});
	},

	playAudioStep5() {
		playAudioByUrl(this.data.finish_audio_url, () => {
			// this.canTouch = true;
		});
	},


	checkShowStepAudio() {

		this.canTouch = false;

		switch(this.step) {
			case 1:
				this.checkStep1();
				break;
			case 2:
				this.checkStep2();
				break;
			case 3:
				this.checkStep3();
				break;			
			case 4:
				this.checkStep4();
				break;

			case 5:
				break;

			case 6:
				break;
		}
	},

	checkStep1() {
		let writeNodeArr = this.writeNodeArr1;

		let isShowEnd = true;
		for (let i = 0; i < 2; i++) {

			if (!writeNodeArr[i].isShowEnd) {
				isShowEnd = false;
				break;
			}
		}

		if (isShowEnd) {
			this.step ++;
			this.checkShowStepAudio();
		} 
	},

	checkStep2() {
		let writeNodeArr = this.writeNodeArr1;

		let isShowEnd = true;
		for (let i = 2; i < 7; i++) {

			if (!writeNodeArr[i].isShowEnd) {
				isShowEnd = false;
				break;
			}
		}

		if (isShowEnd) {
			this.step ++;
			this.checkShowStepAudio();
		} 
	},

	checkStep3() {
		let writeNodeArr = this.writeNodeArr2;

		let isShowEnd = true;
		for (let i = 0; i < 2; i++) {

			if (!writeNodeArr[i].isShowEnd) {
				isShowEnd = false;
				break;
			}
		}

		if (isShowEnd) {
			this.step ++;
			this.checkShowStepAudio();
		} 
	},

	checkStep4() {
		let writeNodeArr = this.writeNodeArr2;

		let isShowEnd = true;
		for (let i = 2; i < 7; i++) {

			if (!writeNodeArr[i].isShowEnd) {
				isShowEnd = false;
				break;
			}
		}

		if (isShowEnd) {
			this.step ++;
			this.checkShowStepAudio();
		} 
	},



	beginShowAudioSmall() {
		const playEnd = () => {
			this.playAni('normal', 0);
			this.showSmallLetterAnim();
		}

		if (!this.data.write_small_0_audio_url) {
			playEnd();
			return;
		}

		this.playAni('begin', 0)
		playAudioByUrl(this.data.write_small_0_audio_url, () => {
			playEnd();
		})
	},

	showSmallLetterAnim() {
		console.log(' in showSmallLetterAnim')
		const anim = this.letterAnimSmall.getComponent(cc.Animation);

		anim.play('anim_a_0');
		const cb = () => {
			console.log('in finished');
			this.showSmallLetter1Audio();
			anim.off('finished', cb)
		}

		anim.on('finished', cb);
	},

	showSmallLetter1Audio() {
		const playEnd = () => {

			this.playAni('normal', 0);
			this.canTouch = true;
			// this.startTesting();

		}


		if (!this.data.write_small_1_audio_url) {
			playEnd();
			return;
		}

		this.playAni('begin', 0)
		//播放引导音频1
		playAudioByUrl(this.data.write_small_1_audio_url, () => {
			playEnd();
		})
	},







	showUserRight(answerData, isSmall) {

		console.log('answerData: ', answerData);

		if (!answerData || Object.keys(answerData) == 0) {
			return;
		}

		let writeNodeArr;
		if (isSmall) {
			writeNodeArr = this.writeNodeArr2
		} else {
			writeNodeArr = this.writeNodeArr1
		}

		for (let i = 0; i < 7; i++) {
			const key = i.toString();
			if (answerData[key]) {
				this.showLetter(i, null, isSmall);

			} else {
				let writeRect = writeNodeArr[i];
				writeRect.hitCount = 0;
			}
		}
	},

	checkIsFillAll(answerData) {

		const letterArr = this.data.letter_arr;
		for (let i = 0; i < letterArr.length; i++) {
			const key = i.toString();
			const letterData = letterArr[i];

			const item = this.letterItemArr[i];
			if (!item.isShow) {
				if (letterData.is_right && !answerData[key]) {
					console.log("没有看到第" + (i + 1) + "个空的答案哦")
					return false;
				}
			}



		}

		return true;

	},


	checkIsFillWrong(answerData) {

		const letterArr = this.data.letter_arr;
		for (let i = 0; i < letterArr.length; i++) {
			const key = i.toString();
			const letterData = letterArr[i];

			const item = this.letterItemArr[i];
			if (!item.isShow) {
				if (!letterData.is_right && answerData[key]) {
					console.log("第" + (i + 1) + "个空填错了哦")
					return false;
				}
			}


		}

		return true;

	},

	getTopLeftLetter(text, block, topLabelData, bottomLabelData) {

		// const titleTopLeft = topLabelData.location.top_left;
		// const titleRightBottom = topLabelData.location.right_bottom;
		// const checkX = titleTopLeft.x + (titleRightBottom.x - titleTopLeft.x) / 3;
		// const checkY = titleRightBottom.y;

		console.log('topLabelData:', topLabelData);
		console.log('bottomLabelData:', bottomLabelData);

		const topY = -topLabelData.word[0].location.top;
		const bottomY = -bottomLabelData.word[0].location.bottom;


		text = text.trim();

		let topLeftLetter;

		for (let j = 0; j < block.length; j++) {

			const line = block[j].line;
			if (!line) {
				continue;
			}


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

				// const {word, location} = line[i];
				const word = line[i].word;
				const location = line[i].word[0].location;

				const curTop = -location.top;
				if (curTop >= topY || curTop <= bottomY) {
					continue;
				}

				console.log(' center line: ', line[i]);


				let sentence = ''
				word.forEach(item => {
					sentence += item.content + ' ';
				});

				sentence.trim();

				line[i].sentence = sentence;
				console.log('sentence: ', sentence);
				if (sentence.indexOf(text) != -1) {

					line[i].tmpLen = this.getToZeroLen(location)
					if (!topLeftLetter) {
						topLeftLetter = line[i];
					} else {
						if (topLeftLetter.tmpLen > line[i].tmpLen) {
							topLeftLetter = line[i];
						}
					}
				}
			}
		}

		return topLeftLetter;
	},

	getToZeroLen(location) {
		const { top, left } = location;
		const len = Math.sqrt(Math.pow(left, 2) + Math.pow(top, 2));
		return len;
	},

	getPhotoLabelData(textArr, block) {

		// text = text.trim();


		for (let j = 0; j < block.length; j++) {

			const line = block[j].line;
			if (!line) {
				continue;
			}

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

				const word = line[i].word;
				let sentence = ''
				word.forEach(item => {
					sentence += item.content + ' ';
				});

				sentence.trim();
				sentence = sentence.toLowerCase();

				line[i].sentence = sentence;

				if (this.checkIsInsert(textArr, sentence)) {
					return line[i];
				}
				// if (sentence.indexOf(text) != -1 ) {
				// 	return line[i];
				// }
			}
		}

		return false;
	},

	checkIsInsert(textArr, sentence) {
		console.log('textArr: ', textArr);
		console.log('sentence: ', sentence);

		let index = -1;
		for (let i = 0; i < textArr.length; i++) {
			index = sentence.indexOf(textArr[i], index);
			console.log('index: ', index);
			if (index == -1) {
				return false;
			}
		}

		return true;
	},

	getPhotoWordArr(identifier, data, topLabelData, bottomLabelData) {


		const identifierArr = this.getIdentifierArr(data, identifier)

		const wordArr = [];
		const topY = -topLabelData.top
		const bottomY = -bottomLabelData.bottom;
		for (let i = 0; i < identifierArr.length; i++) {

			const curTop = -identifierArr[i].top;
			if (curTop >= topY || curTop <= bottomY) {
				continue;
			}

			wordArr.push(identifierArr[i]);
		}

		return wordArr;




		// const wordArr = [];
		// const maxLen = 10;

		// text = text.trim();

		// const topY = -topLabelData.word[0].location.top;
		// const bottomY = -bottomLabelData.word[0].location.top;

		// for(let j=0; j<block.length; j++) {

		// 	const line = block[j].line;
		// 	if (!line) {
		// 		continue;
		// 	}


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


		// 		const location = line[i].word[0].location;

		// 		const curTop = -location.top;
		// 		if (curTop >= topY || curTop <= bottomY) {
		// 			continue;
		// 		}


		// 		let word = line[i].word;
		// 		let sentence = ''

		// 		if (word.length > maxLen) {
		// 			console.log('continue ', word.length);
		// 			continue;
		// 		}

		// 		line[i].word = word = this.checkCutWordData(word);
		// 		// console.log('word1~ ', word);


		// 		word.forEach(item => {
		// 			sentence += item.content + ' ';
		// 		});

		// 		sentence.trim();

		// 		line[i].sentence = sentence;
		// 		console.log('sentence: ', sentence);
		// 		console.log('text: ', text);

		// 		console.log('index: ', sentence.indexOf(text));
		// 		if (sentence.indexOf(text) != -1 ) {
		// 			wordArr.push( line[i] );
		// 		}
		// 	}
		// }

		// return wordArr;
	},

	checkCutWordData(wordArr) {

		let newWordArr = [];
		for (let i = 0; i < wordArr.length; i++) {

			let wordObj = wordArr[i];

			wordObj.content = wordObj.content.trim();

			if (wordObj.content.length > 1) {

				const tmpArr = [];
				const w = wordObj.location.right - wordObj.location.left
				const subW = w / wordObj.content.length;
				for (let j = 0; j < wordObj.content.length; j++) {

					const subWordObj = {};
					subWordObj.content = wordObj.content[j];
					subWordObj.location = {
						top: wordObj.location.top,
						bottom: wordObj.location.bottom,
						left: wordObj.location.left + subW * j,
						right: wordObj.location.left + subW * (j + 1)
					}

					tmpArr.push(subWordObj);
				}
				newWordArr = newWordArr.concat(tmpArr)


			} else {
				newWordArr.push(wordObj)
			}

		}

		console.log('newWordArr: ', newWordArr);
		return newWordArr;
	},


	topLabelData: null,
	bottomLabelData: null,
	topLeftLetter: null,
	checkIsRightArea(data, isSmall) {


		let letter = this.data.letter || 'a';
		letter = letter.toUpperCase();
		let checkLetter;
		if (isSmall) {
			checkLetter = 'x' + letter + '1'
		} else {
			checkLetter = letter + '1'
		}

		
		if (!this.topTitleData) {
			const topTitleData = this.getIdentifierArr(data, 'originC')[0];
			if (!topTitleData) {
				return false;
			}
			this.topTitleData = topTitleData;
		}
	
		if (!this.bottomTitleData) {
			const bottomTitleData = this.getIdentifierArr(data, 'originD')[0];
			if (!bottomTitleData) {
				return;
			}
			this.bottomTitleData = bottomTitleData;
		}



		const topLeftLetterData = this.getTopLeftLetterData(data, checkLetter, this.topTitleData, this.bottomTitleData);
		if (!topLeftLetterData) {
			return;
		}

		

		if (isSmall) {
			this.topLeftLetterData2 = topLeftLetterData;
		} else {
			this.topLeftLetterData1 = topLeftLetterData;
		}

		console.log('topTitleData:', this.topTitleData);
		console.log('bottomTitleData:', this.bottomTitleData);
		console.log('topLeftLetterData:', topLeftLetterData);

		return this.topTitleData && this.bottomTitleData && topLeftLetterData;

		// const block = result?.block
		// if (!block) {
		// 	return false;
		// }

		// const letter = this.data.letter || 'a';



		// const topLabelData = this.getPhotoLabelData(['tr', 'e', 'wri', 'e'], block);
		// if (!topLabelData) {
		// 	console.log(' !topLabelData ')
		// 	return false;
		// }

		// const bottomLabelData = this.getPhotoLabelData(['or', 'cross', 't', 'out'], block);
		// if (!bottomLabelData) {
		// 	console.log(' !bottomLabelData ')
		// 	return false;
		// }

		// let topLeftLetter = this.getTopLeftLetter(letter, block, topLabelData, bottomLabelData);
		// if (!topLeftLetter) {
		// 	console.log(' !topLeftLetter ')
		// 	return false;
		// }

		// this.topLabelData = topLabelData;
		// this.bottomLabelData = bottomLabelData;
		// this.topLeftLetter = topLeftLetter;

		// // console.log('topLabelData: ', topLabelData);
		// // console.log('topLeftLetter: ', topLeftLetter);

		// return topLabelData && bottomLabelData && topLeftLetter;
	},

	getTopLeftLetterData(result, identifier, topTitleData, bottomTitleData) {
		
		const identifierArr = this.getIdentifierArr(result, identifier);

		identifierArr.forEach(item => {
			const len = Math.sqrt(Math.pow(item.left, 2) + Math.pow(item.top, 2));
			item.minLen = len;
		})

		identifierArr.sort((a, b) => {
			return a.minLen - b.minLen
		})

		const topLeftLetter = identifierArr[0];
		if (-topLeftLetter.bottom > -topTitleData.bottom || -topLeftLetter.bottom < -bottomTitleData.bottom ) {
			return;
		}

		const unit = bottomTitleData.bottom - bottomTitleData.top;
		const targetX = bottomTitleData.left + unit * 1;
		if (topLeftLetter.left > targetX) {
			return;
		}

		return topLeftLetter;
	},

	getIdentifierArr(data, identifier) {

		const result = data.result;

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

			const data = result[i];
			const { classIdentifier } = data;

			if (classIdentifier == identifier) {
				identifierArr.push(data)
			}
		}
		return identifierArr;
	},

	getAnswerDataNew(data, isSmall) {


		let letter = this.data.letter || 'a';

		let checkLetter, dotArr;
		if (isSmall) {
			checkLetter = letter.toLowerCase();
			dotArr = this.dotArr2;
		} else {
			checkLetter = letter.toUpperCase();
			dotArr = this.dotArr1;
		}






		const answerData = {};

		const resultTextArr = data.result.text;
		for (let i=0; i<resultTextArr.length; i++) {

			const wordData = resultTextArr[i];

			if (wordData.content != checkLetter) {
				continue;
			}

			const colorRect =	this.getColorRectByPos(wordData.bbox)
			colorRect.data = wordData;

			this.sample.addChild(colorRect);

			this.setOneAnswerDataNew(colorRect, dotArr, answerData);

	
		}

		return answerData;
	},


	getAnswerData(data, isSmall) {


		let letter = this.data.letter || 'a';
		letter = letter.toUpperCase();
		let checkLetter;
		if (isSmall) {
			checkLetter = 'x' + letter + '1'
		} else {
			checkLetter = letter + '1'
		}



		const topTitleData = this.topTitleData;
		const bottomTitleData = this.bottomTitleData;
		let topLeftLetterData;
		if (isSmall) {
			topLeftLetterData = this.topLeftLetterData2;
		} else {
			topLeftLetterData = this.topLeftLetterData1;
		}


		const wordDataArr = this.getPhotoWordArr(checkLetter, data, topTitleData, bottomTitleData);

		const dotArr = this.setTestRectDot(topTitleData, bottomTitleData, topLeftLetterData, wordDataArr);


		const answerData = {};

		console.log('~~wordDataArr:', wordDataArr);

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

			const wordData = wordDataArr[i];
			const rect = {
				x: wordData.left,
				y: -wordData.top,
				width: Math.abs(wordData.left - wordData.right),
				height: Math.abs(wordData.top - wordData.bottom),
			}
			const colorRect = this.getColorRect(rect);
			this.debugLayer.addChild(colorRect);

			this.setOneAnswerData(colorRect, dotArr, answerData);

		}



		if (this.colorRectTop) {
			return answerData;
		}
		const rectTop = {
			x: topTitleData.left, 
			y: -topTitleData.top,
			width: Math.abs( topTitleData.left - topTitleData.right ), 
			height: Math.abs( topTitleData.top - topTitleData.bottom ), 
		}

	
		const colorRectTop = this.getColorRect(rectTop, 'green');
		this.debugLayer.addChild(colorRectTop);
		this.colorRectTop = colorRectTop;


		const rectBottom = {
			x: bottomTitleData.left, 
			y: -bottomTitleData.top,
			width: Math.abs( bottomTitleData.left - bottomTitleData.right ), 
			height: Math.abs( bottomTitleData.top - bottomTitleData.bottom ), 
		}

	
		const colorRectBottom = this.getColorRect(rectBottom, 'green');
		this.debugLayer.addChild(colorRectBottom);


		return answerData;






		// console.log(' in getAnswerData');
		// const block = result?.block
		// if (!block) {
		// 	return false;
		// }


		// const letter = this.data.letter || 'a';


		// const topLabelData = this.topLabelData;//this.getPhotoLabelData(['tr', 'ce', 'wri', 'e'], block);

		// const bottomLabelData = this.bottomLabelData;//this.getPhotoLabelData(['or', 'cross', 'it', 'out'], block);

		// let topLeftLetter = this.topLeftLetter; //this.getTopLeftLetter(letter, block, topLabelData, bottomLabelData);

		// const wordDataArr = this.getPhotoWordArr(letter, block, topLabelData, bottomLabelData);

		// console.log('!!!wordDataArr: ', wordDataArr);


		// this.setTestLabel(topLabelData);
		// this.setTestLabel(bottomLabelData);
		// this.setTestLabel(topLeftLetter);


		// // const dotArr = this.setTestRectDot(topLabelData, bottomLabelData, wordDataArr);
		// const dotArr = this.setTestRectDot(topLabelData, bottomLabelData, topLeftLetter, wordDataArr);

		// 	// return;
		// const answerData = {};

		// console.log('~~wordDataArr:', wordDataArr);

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

		// 	const wordArr = wordDataArr[i].word;
		// 	for (let j=0; j<wordArr.length; j++) {
		// 		const location = wordArr[j].location;
		// 		const rect = {
		// 			x: location.left, 
		// 			y: -location.top,
		// 			width: Math.abs( location.left - location.right ), 
		// 			height: Math.abs( location.top - location.bottom ), 
		// 		}
		// 		const colorRect = this.getColorRect(rect);
		// 		this.debugLayer.addChild(colorRect);

		// 		this.setOneAnswerData(colorRect, dotArr, answerData);

		// 	}


		// }

		// return answerData;

	},

	setTestLabel(labelData) {

		if (!this.debugLayer.parent || !this.debugLayer.active) {
			return;
		}

		console.log('labelData: ', labelData)
		const location = labelData.word[0].location;
		const label = this.getLabel(labelData.sentence);
		label.anchorX = 0;
		// label.anchorY = 1;
		label.x = location.left;
		label.y = -location.top
		label.zIndex = 50;


		// const rect = {};
		// rect.width = location.right - location.left;
		// rect.height = location.bottom - location.top;
		// rect.x = location.left;
		// rect.y = -location.top;
		// const colorRect = this.getColorRect(rect, cc.Color.YELLOW);
		// this.debugLayer.addChild(colorRect);

		this.debugLayer.addChild(label);
	},

	setTestRectDot(topLabelData, bottomLabelData, topLeftLetter, wordDataArr) {


		const topLeftPosX = topLeftLetter.left;
		const topLeftPosY = topLeftLetter.top;

		const totalH = -topLabelData.top + bottomLabelData.top;
	
		const unitH = -topLabelData.top + bottomLabelData.bottom;
		const rate = 0.26;

		console.log('unitH: ', unitH);


		let rectH;
		let rectW;
		let disW;

		let unit;
		if (-topLeftPosY > -topLabelData.top - totalH / 3) {

			unit = topLeftLetter.bottom - topLabelData.bottom;
			console.log('unit: ', unit);

			// 50

			rectH = 0.88 *rate * unitH; //44  
			rectW = 0.5 *rate * unitH; //27;
			disW = 0.66 *rate * unitH; //55;
		
		} else {

			unit = bottomLabelData.top - topLeftLetter.top;
			// 50

			rectH = 0.5 *rate * unitH; //25  
			rectW = 0.54 *rate * unitH; //27;
			disW = 0.6 *rate * unitH; //46;

			console.log('unit: ', unit);


		}



		const baseX = topLeftPosX + rectW / 2;
		let baseY = -(topLeftPosY - rectH / 2);


		let col = 0;

		const dotArr = [];
		for (let i = 0; i < 9; i++) {
			const x = baseX + col * disW;
			const y = baseY;
			const dot = this.getColorDot(x, y, rectW * 0.1);
			this.debugLayer.addChild(dot,5);
			dotArr.push(dot);
			col++;


		}

		return dotArr;







		// const topLeftPosX = topLeftLetter.word[0].location.left;
		// const topLeftPosY = topLeftLetter.word[0].location.top;

		// const totalH = -topLabelData.word[0].location.top + bottomLabelData.word[0].location.top;


		// const unitH = -topLeftLetter.word[0].location.top + topLeftLetter.word[0].location.bottom;


		// console.log('unitH: ', unitH);



		// let rectH = 1 * unitH; //21  
		// let rectW = 1.476 * unitH; //31;
		// let disW = 2.08 * unitH; //45;


		// const letterLocation = topLeftLetter.word[0].location;
		// const bottomLocation = bottomLabelData.word[0].location;
		// const topLocation = topLabelData.word[0].location;
		// let unit;
		// if (-topLeftPosY > -topLabelData.word[0].location.top - totalH / 3 ) {

		// 	unit = letterLocation.bottom - topLocation.bottom;
		// 	// 50

		// 	rectH = 0.88 * unit; //44  
		// 	rectW = 0.54 * unit; //27;
		// 	disW = 1.07 * unit; //55;

		// } else {

		// 	unit = bottomLocation.top - letterLocation.top;
		// 	// 50

		// 	rectH = 0.5 * unit; //25  
		// 	rectW = 0.54 * unit; //27;
		// 	disW = 1.13 * unit; //46;

		// }





		// const baseX = topLeftPosX + rectW / 2;
		// let baseY = -(topLeftPosY - rectH / 2 );


		// let col = 0;

		// const dotArr = [];
		// for (let i=0; i<9; i++) {
		// 	const x = baseX + col * disW;
		// 	const y = baseY;
		// 	const dot = this.getColorDot(x, y, rectW * 0.6);
		// 	this.debugLayer.addChild(dot,5);
		// 	dotArr.push(dot);
		// 	col ++;


		// }

		// return dotArr;

	},

	setOneAnswerDataNew(colorRect, dotArr, answerData) {

		console.log(' in setOneAnswerDataNew')
		const rect = colorRect.ccRect;
		const x = rect.x + rect.width / 2;
		const y = rect.y +rect.height / 2;
		const checkPoint = cc.v2(x, y);

		const checkDot = this.getColorDot(x, y, 5);

		console.log(' checkPoint:' , checkPoint)

		this.sample.addChild(checkDot);

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

			const dotRect = dotArr[i];
			const checkRect = dotRect.ccRect;


			if (checkRect.contains(checkPoint)) {

				answerData[i.toString()] = colorRect;
				return;
			} 

		}

	},

	setOneAnswerData(colorRect, dotArr, answerData) {

		// console.log(' in setOneAnswerData')
		// console.log('colorRect: ', colorRect)
		// console.log('dotArr: ', dotArr)
		// console.log('answerData: ', answerData)


		const rect = colorRect.ccRect;

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

			const { dotRect } = dotArr[i];
			// const {pos} = dotArr[i];
			// if (rect.contains(pos)) {
			if (rect.intersects(dotRect)) {
				answerData[i.toString()] = colorRect;
				return;
			}

		}

	},

	getLabel(text) {
		const labelNode = new cc.Node();
		const label = labelNode.addComponent(cc.Label);
		label.string = text;
		labelNode.color = cc.Color.BLACK;
		label.fontSize = 20;
		return labelNode;
	},

	getColorRect(rect, color='red') {

		// const node = new cc.Node();
		// const colorRect = node.addComponent(cc.Graphics);
		// if (!color) {
		// 	color = cc.Color.RED;
		// }
		// colorRect.fillColor = color
		// node.opacity = 0.5;
		// colorRect.fillRect(rect.x, rect.y, rect.width, rect.height);

		// node.ccRect = new cc.Rect(rect.x, rect.y, rect.width, rect.height);


		const node = this.getSprNode(color);
		node.anchorX = 0;
		node.anchorY = 0;
		node.x = rect.x;
		node.y = rect.y;
		node.scaleX = rect.width / node.width;
		node.scaleY = rect.height / node.height;

		node.ccRect = new cc.Rect(rect.x, rect.y, rect.width, rect.height);

		return node;
	},

	getColorDot(x, y, r = 10) {
		const node = new cc.Node();

		if (this.debugLayer.parent && this.debugLayer.active) {
			// const colorDot = node.addComponent(cc.Graphics);
			// colorDot.fillColor = cc.Color.BLUE;
			// colorDot.fillRect( - r/2, - r/ 2, r, r);


			const rect = {
				x:- r/2,
				y: - r/ 2, 
				width:r, 
				height:r
			}
			// const colorDot = this.getColorRect(rect,'blue');
			// colorDot.fillColor = cc.Color.BLUE;
			// colorDot.fillRect( - r/2, - r/ 2, r, r);

			const colorDot = this.getSprNode('blue');

			
			colorDot.anchorX = 0;
			colorDot.anchorY = 0;
			colorDot.x = rect.x;
			colorDot.y = rect.y;
			colorDot.scaleX = rect.width / colorDot.width;
			colorDot.scaleY = rect.height / colorDot.height;
			node.addChild(colorDot);

			
		}

		node.x = x;
		node.y = y;
		// node.pos = new cc.Vec2(x, y);

		// node.opacity = 0.5;

		const rect = new cc.Rect(node.x - r / 2, node.y - r / 2, r, r);
		node.dotRect = rect;
		return node;
	},

	checkIsRightLetter(result) {
		const block = result?.data?.block
		if (!block) {
			return false;
		}
		return false;

		const letter = this.data.letter;
		const letterLabelData = this.getPhotoLabelData(letter, block);

		return letterLabelData;
	},

	checkIsRightPos(result) {
		const block = result?.data?.block
		if (!block) {
			return false;
		}

		return false;

		const iconLabelData = this.getPhotoLabelData('I like', block);
		const topLabelData = this.getPhotoLabelData('n and repeat', block);
		const bottomLabelData = this.getPhotoLabelData('n, point, and repeat', block);
		if (!iconLabelData) {
			return false;
		}

		const topY = topLabelData.location.top_left.y;
		const bottomY = bottomLabelData.location.top_left.y;
		const iconY = iconLabelData.location.top_left.y;
		if (bottomY <= iconY <= topY) {
			return true;
		}
	},

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

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

		playAudio(this.data.finish_audio_url)

	},

	getPhotoData(cb) {

		const tmpData = 
		{
			"code": 200000,
			"message": "success",
			"result": {
				"support_results": [
					[
						[
							0.49317359924316406,
							0.25097235652010197,
							0.5522325038909912,
							0.288081715131967,
							"a",
							0.990108072757721
						]
					],
					[
						[
							0.7815923094749451,
							0.2423561773522615,
							0.8420042395591736,
							0.2829396176165032,
							"a",
							0.9900233745574951
						]
					],
					[
						[
							0.5897714495658875,
							0.24693736438131567,
							0.6457504034042358,
							0.2819446122459721,
							"a",
							0.9894896745681763
						]
					],
					[
						[
							0.2031928449869156,
							0.25154209940460914,
							0.26929566264152527,
							0.29193248868186233,
							"a",
							0.983356773853302
						]
					],
					[
						[
							0.39285269379615784,
							0.24877103711543316,
							0.45319148898124695,
							0.2872285145969844,
							"a",
							0.9817916750907898
						]
					],
					[
						[
							0.30443957448005676,
							0.2532131404780602,
							0.3565950095653534,
							0.2885934469473862,
							"a",
							0.9796608090400696
						]
					],
					[
						[
							0.8672714233398438,
							0.24161506162136312,
							0.9294711947441101,
							0.2848689417255425,
							"a",
							0.9749398231506348
						]
					],
					[
						[
							0.680833101272583,
							0.24406777752747533,
							0.7436296343803406,
							0.28508718252948045,
							"a",
							0.9576545357704163
						]
					],
					[
						[
							0.48491987586021423,
							0.12172665519367754,
							0.5459403395652771,
							0.19091845712618705,
							"A",
							0.9131966829299927
						]
					],
					[
						[
							0.5817452669143677,
							0.12464039263645885,
							0.6427905559539795,
							0.18670312292435287,
							"A",
							0.8777841925621033
						]
					],
					[
						[
							0.6734722256660461,
							0.12392509000705718,
							0.7303305864334106,
							0.18485528186833022,
							"A",
							0.8367360234260559
						]
					],
					[
						[
							0.8564218282699585,
							0.1192738632772547,
							0.9225841164588928,
							0.19054701754113432,
							"A",
							0.7801001071929932
						]
					],
					[
						[
							0.7687476277351379,
							0.12338259301840243,
							0.8205023407936096,
							0.18305307740282176,
							"A",
							0.6130796670913696
						]
					],
					[
						[
							0.3863550126552582,
							0.1285817704766488,
							0.4408574104309082,
							0.18449943199799176,
							"A",
							0.5841907858848572
						]
					]
				],
				"text": [
					{
						"bbox": [
							{
								"x1": 0.49317359924316406,
								"y1": 0.25097235652010197
							},
							{
								"x2": 0.5522325038909912,
								"y2": 0.25097235652010197
							},
							{
								"x3": 0.5522325038909912,
								"y3": 0.288081715131967
							},
							{
								"x4": 0.49317359924316406,
								"y4": 0.288081715131967
							}
						],
						"content": "a",
						"score": 0.990108072757721
					},
					{
						"bbox": [
							{
								"x1": 0.7815923094749451,
								"y1": 0.2423561773522615
							},
							{
								"x2": 0.8420042395591736,
								"y2": 0.2423561773522615
							},
							{
								"x3": 0.8420042395591736,
								"y3": 0.2829396176165032
							},
							{
								"x4": 0.7815923094749451,
								"y4": 0.2829396176165032
							}
						],
						"content": "a",
						"score": 0.9900233745574951
					},
					{
						"bbox": [
							{
								"x1": 0.5897714495658875,
								"y1": 0.24693736438131567
							},
							{
								"x2": 0.6457504034042358,
								"y2": 0.24693736438131567
							},
							{
								"x3": 0.6457504034042358,
								"y3": 0.2819446122459721
							},
							{
								"x4": 0.5897714495658875,
								"y4": 0.2819446122459721
							}
						],
						"content": "a",
						"score": 0.9894896745681763
					},
					{
						"bbox": [
							{
								"x1": 0.2031928449869156,
								"y1": 0.25154209940460914
							},
							{
								"x2": 0.26929566264152527,
								"y2": 0.25154209940460914
							},
							{
								"x3": 0.26929566264152527,
								"y3": 0.29193248868186233
							},
							{
								"x4": 0.2031928449869156,
								"y4": 0.29193248868186233
							}
						],
						"content": "a",
						"score": 0.983356773853302
					},
					{
						"bbox": [
							{
								"x1": 0.39285269379615784,
								"y1": 0.24877103711543316
							},
							{
								"x2": 0.45319148898124695,
								"y2": 0.24877103711543316
							},
							{
								"x3": 0.45319148898124695,
								"y3": 0.2872285145969844
							},
							{
								"x4": 0.39285269379615784,
								"y4": 0.2872285145969844
							}
						],
						"content": "a",
						"score": 0.9817916750907898
					},
					{
						"bbox": [
							{
								"x1": 0.30443957448005676,
								"y1": 0.2532131404780602
							},
							{
								"x2": 0.3565950095653534,
								"y2": 0.2532131404780602
							},
							{
								"x3": 0.3565950095653534,
								"y3": 0.2885934469473862
							},
							{
								"x4": 0.30443957448005676,
								"y4": 0.2885934469473862
							}
						],
						"content": "a",
						"score": 0.9796608090400696
					},
					{
						"bbox": [
							{
								"x1": 0.8672714233398438,
								"y1": 0.24161506162136312
							},
							{
								"x2": 0.9294711947441101,
								"y2": 0.24161506162136312
							},
							{
								"x3": 0.9294711947441101,
								"y3": 0.2848689417255425
							},
							{
								"x4": 0.8672714233398438,
								"y4": 0.2848689417255425
							}
						],
						"content": "a",
						"score": 0.9749398231506348
					},
					{
						"bbox": [
							{
								"x1": 0.680833101272583,
								"y1": 0.24406777752747533
							},
							{
								"x2": 0.7436296343803406,
								"y2": 0.24406777752747533
							},
							{
								"x3": 0.7436296343803406,
								"y3": 0.28508718252948045
							},
							{
								"x4": 0.680833101272583,
								"y4": 0.28508718252948045
							}
						],
						"content": "a",
						"score": 0.9576545357704163
					},
					{
						"bbox": [
							{
								"x1": 0.48491987586021423,
								"y1": 0.12172665519367754
							},
							{
								"x2": 0.5459403395652771,
								"y2": 0.12172665519367754
							},
							{
								"x3": 0.5459403395652771,
								"y3": 0.19091845712618705
							},
							{
								"x4": 0.48491987586021423,
								"y4": 0.19091845712618705
							}
						],
						"content": "A",
						"score": 0.9131966829299927
					},
					{
						"bbox": [
							{
								"x1": 0.5817452669143677,
								"y1": 0.12464039263645885
							},
							{
								"x2": 0.6427905559539795,
								"y2": 0.12464039263645885
							},
							{
								"x3": 0.6427905559539795,
								"y3": 0.18670312292435287
							},
							{
								"x4": 0.5817452669143677,
								"y4": 0.18670312292435287
							}
						],
						"content": "A",
						"score": 0.8777841925621033
					},
					{
						"bbox": [
							{
								"x1": 0.6734722256660461,
								"y1": 0.12392509000705718
							},
							{
								"x2": 0.7303305864334106,
								"y2": 0.12392509000705718
							},
							{
								"x3": 0.7303305864334106,
								"y3": 0.18485528186833022
							},
							{
								"x4": 0.6734722256660461,
								"y4": 0.18485528186833022
							}
						],
						"content": "A",
						"score": 0.8367360234260559
					},
					{
						"bbox": [
							{
								"x1": 0.8564218282699585,
								"y1": 0.1192738632772547
							},
							{
								"x2": 0.9225841164588928,
								"y2": 0.1192738632772547
							},
							{
								"x3": 0.9225841164588928,
								"y3": 0.19054701754113432
							},
							{
								"x4": 0.8564218282699585,
								"y4": 0.19054701754113432
							}
						],
						"content": "A",
						"score": 0.7801001071929932
					},
					{
						"bbox": [
							{
								"x1": 0.7687476277351379,
								"y1": 0.12338259301840243
							},
							{
								"x2": 0.8205023407936096,
								"y2": 0.12338259301840243
							},
							{
								"x3": 0.8205023407936096,
								"y3": 0.18305307740282176
							},
							{
								"x4": 0.7687476277351379,
								"y4": 0.18305307740282176
							}
						],
						"content": "A",
						"score": 0.6130796670913696
					},
					{
						"bbox": [
							{
								"x1": 0.3863550126552582,
								"y1": 0.1285817704766488
							},
							{
								"x2": 0.4408574104309082,
								"y2": 0.1285817704766488
							},
							{
								"x3": 0.4408574104309082,
								"y3": 0.18449943199799176
							},
							{
								"x4": 0.3863550126552582,
								"y4": 0.18449943199799176
							}
						],
						"content": "A",
						"score": 0.5841907858848572
					}
				]
			}
		}

		cb(tmpData);
	},


	photoCheckStart() {
		this.getPhotoData((data) => {
			this.photoEnd(data);
		})
	},


	updatePhotoCheck() {
		if (this.isOpenPhotoCheck) {

			this.photoCheckStart();

			this.isOpenPhotoCheck = false;
		}
	},


	update() {
		this.updatePhotoCheck();
	},


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

	_audioId: null,
	playAudioByUrl(audio_url, cb = null, loadcb = null, loop = false) {

		if (this._audioId) {
			cc.audioEngine.pause(this._audioId);
		}

		let audioId;

		if (audio_url) {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {

				audioId = cc.audioEngine.play(audioClip, loop, 0.8);
				this._audioId = audioId;

				if (cb) {
					cc.audioEngine.setFinishCallback(audioId, () => {
						cb();
					});
				}

				if (loadcb) {
					loadcb(audioId);
				}

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


	onDestroy() {

		clearTimeout(this.timer_1);
	}

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

});

