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

cc.Class({

	extends: cc.Component,

	properties: {
	},

	// 生命周期 onLoad
	onLoad() {
		this.initSceneData();
		this.initSize();
	},

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

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {
		// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
		let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
		let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
		let f = screen_size >= design_size
		cc.Canvas.instance.fitHeight = f
		cc.Canvas.instance.fitWidth = !f

		const frameSize = cc.view.getFrameSize();
		this._frameSize = frameSize;

		this._designSize = cc.view.getDesignResolutionSize();

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

		sx = frameSize.width / this._designSize.width;
		sy = frameSize.height / this._designSize.height;
		this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
		this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
	},


	// 生命周期 start
	start() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}

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

	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.exercises) {

			this._audioResList.push({ url: this.data.exercises.audioUrl });
		}

		let wordArr = this.data.exercises.wordArr;

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

			if (wordArr[i] && wordArr[i].lrcData) {
				this._audioResList.push({ url: wordArr[i].lrcData.audio_url });
			}

		}

		this._audioResList.push({ url: this.data.guideAudioUrl1 });
		this._audioResList.push({ url: this.data.guideAudioUrl2 });
		this._audioResList.push({ url: this.data.guideAudioUrl3 });
		this._audioResList.push({ url: this.data.audioUrl });
	},

	addPreloadAnima() {

	},

	preload() {

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

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

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


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

	_cantouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		this._cantouch = true;
	},

	audioBtn: null,
	audioBegin: null,
	audioTipArea: null,
	audioTipLetter: null,
	audioTipIcon: null,
	audioTipSuccess: null,
	audioOsmoTip: 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.audioTipArea = getAudioByResName('tip_area');
		this.audioTipLetter = getAudioByResName('tip_letter');
		this.audioTipIcon = getAudioByResName('tip_icon');
		this.audioTipSuccess = getAudioByResName('tip_success');

		this.audioOsmoTip = getAudioByResName('osmo_tip');

		this.audioDefault = getAudioByResName('default');

	},


	initView() {

		this.initBg();

		const content = cc.find("Canvas/content/bg_green");

		// content.scale = this._mapScaleMin
		console.log(content.width, content.height);
		this.initPic();
		this.initBtn();
		this.initMask();

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

		handNode.initY = handNode.y;

		this._cantouch = false;

		const begin = () => {
			this.playAni('normal', 0);
			//移动手指位置
			this.moveHand(this._curIndex, () => {
				this._cantouch = true;
			});

			this._canClickCat = true;
		}

		//如果有引导音频，则播放完引导音频再开始
		if (this.data.guideAudioUrl1) {

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

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

				state.stop();

				begin();
			});
		}
		else {
			begin();
			
		}

		this.addDefaultMusic();

	},

	maskNode: null,
	initMask() {
		this.canvas = cc.find("Canvas");
		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() {

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

	},

	_curIndex: null,
	initPic() {

		let exercises = this.data.exercises;

		this.getSprNodeByUrl(exercises.picUrl, (sprNode) => {

			let pic = cc.find("Canvas/content/bg_green/pic");

			const picNode = sprNode;
			
			setSprNodeMaxLen(picNode, pic.width, pic.height);
			picNode.x = 0;
			picNode.y = 0;
			pic.addChild(picNode);

		});

		let textNode = cc.find("Canvas/content/bg_green/bg_word-background/text");
		textNode.initScale = textNode.scale;
		let wordNodeArr = [];

		let wordArr = this.data.exercises.wordArr;

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

			if (!wordArr[i].val) {
				continue;
			}

			//首字母
			let initial = wordArr[i].val.substr(0, 1);
			let label = this.getWord(wordArr[i], initial, 700, true);
			label.isInitial = true;
			wordNodeArr.push(label);

			//其余字母
			let last = wordArr[i].val.substr(1);
			let lastLabel = this.getWord(wordArr[i], last, 700, false);
			wordNodeArr.push(lastLabel);

		}


		textNode.wordNodeArr = wordNodeArr;

		this.resetTextPosition();

		this._curIndex = 0;
	},

	_canClickCat: null,
	_showStandby: null,
	initBtn() {

		const catBtn = cc.find('Canvas/Main Camera/catFrame/cat/ClickBtn');

		catBtn.addComponent(cc.Button);

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

			console.log(this._canClickCat, this._showStandby);

			if(!this._cantouch){
				return;
			}

			if(!this._canClickCat){
				return;
			}

			if(this._showStandby){
				return;
			}

			this._showStandby = true;


			const clickCat = (audioUrl, aniName) =>{

				console.log(audioUrl, aniName);

				//播放待机音频
				if(audioUrl){

					const state = this.playAni(aniName, 0);

					//播放完成，停止动画
					this.playAudioByUrl(audioUrl, () => {
						state.stop();
						this._showStandby = false;
						this.playAni('normal', 0);
					});
				}
				else{
					this.playAni(aniName, 0, () => {
						this._showStandby = false;
					});
				}
			}

			//如果已经结束，就播放结束音频;其他情况就播放待机音频
			if (this._shown && this.data.guideAudioUrl3) {

				clickCat(this.data.guideAudioUrl3, 'finish');
				
			}
			else{
				clickCat(this.data.guideAudioUrl2, 'begin');
			}
			
		});

		const picNode = cc.find("Canvas/content/bg_green/pic");
		picNode.addComponent(cc.Button);
		picNode.on('click', () => {

			if(!this._cantouch){
				return;
			}

			this._cantouch = false;

			let rotation = picNode.angle;

			let times = 1;

			const rota = () => {
				cc.tween(picNode)
				.to(0.1, { angle: rotation - 15 })
				.to(0.1, { angle: rotation  })
				.to(0.1, { angle: rotation + 15 })
				.to(0.1, { angle: rotation  })
				.call(() => {
					if(times > 2){
						this._cantouch = true;
						this._showStandby = false;
						return;
					}

					times += 1;

					rota();
				})
				.start();
			}

			console.log("click pic...");

			if(this.data.audioUrl){

				const state = this.playAni('begin', 0);

				this.playAudioByUrl(this.data.audioUrl, ()=>{
					state.stop();

					//播放待机
					this.playAni("normal", 0);
				});

			}

			rota();
			
		});
	},

	getWord(word, wordVal, size, isInitial) {

		size /= 2;
		let color = new cc.color();
		color.fromHEX('#000000');
		const labelNode = new cc.Node();
		labelNode.data = word;
		labelNode.color = color;
		const label = labelNode.addComponent(cc.Label);
		label.lineHeight = size;
		label.fontSize = size;
		label.font = cc.find('Canvas/res/font/MuliBold-YzEVy').getComponent(cc.Label).font;
		label.string = wordVal;

		labelNode.x = 0;
		labelNode.y = 0;

		let widget = labelNode.addComponent(cc.Widget);
		widget.isAlignBottom = true;
		widget.bottom = -size / 2;
		widget.updateAlignment();

		labelNode.addComponent(cc.Button);

		labelNode.on('click', () => {
			if (!this._cantouch) {
				return;
			}
			//设置不可点击
			this._cantouch = false;

			let audioUrl = word.lrcData.audio_url;

			if(isInitial){

				this.playTextAutio(labelNode, audioUrl, () => {
					this._cantouch = true;
				})
			}
			else{
				playAudio(this.audioBtn.clip, () => {

					//显示完，则播放音频
					if (this._shown) {
						this.playTextAutio(labelNode, audioUrl, () => {
							this._cantouch = true;
						});
					}
					else {
						this._cantouch = true;
					}
	
				})
			}
		})

		return labelNode;
	},

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


	catAniState: null,
	playAni(name, times = 1, cb = null) {

		if(this.catAniState && this.catAniState.name != name)
		{
			this.catAniState.stop();
		}

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

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

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

		dragonDisplay.on(dragonBones.EventObject.COMPLETE, () => {
			const tip = cc.find('Canvas/tipFrame/tip');
			tip.active = false;
			if (cb) {
				cb();
			}
		})

		this.catAniState = state;

		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;
		handNode.zIndex = 999;

		this.handAni();

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

	/**
	 * @param {*}
	 * @param {*} audioUrl 
	 * @param {*} callback 
	 */
	playTextAutio(labelNode, audioUrl, callback = null) {

		const state = this.playAni('begin', 0);

		this.playAudioByUrl(audioUrl, () => {

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

			state.stop();

			//播放待机动画
			this.playAni('normal', 0);

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

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

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

			let lyrics = labelNode.data.lrcData.lyrics;

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

			this.monitor(labelNode, 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._cantouch = false;

		this._shown = true;

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

		if(this.data.guideAudioUrl3){

			const state = this.playAni('finish', 0);

			this.playAudioByUrl(this.data.guideAudioUrl3, () => {
				this._cantouch = true;
				state.stop();
				this.playAni('normal', 0);
				onHomeworkFinish();
			})
			
		}
		else{
			this._cantouch = true;
		}
	},

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

		if (this._tween) {
			this._tween.stop();
		}

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

					const showNext = () => {

						this.playAni('normal', 0);

						this._cantouch = true;
						if(this._shown){
							return;
						}
						this._curIndex++;

						if(this._curIndex >= this.data.exercises.wordArr.length && !this._times){
							this._times = 1;

							this._curIndex = 0;
				
							console.log("the first time");
						}	

						this.moveHand(this._curIndex, () => {
							this._cantouch = true;

							this.showEnd();
						})
					}

					let duration = cc.audioEngine.getDuration(audioId);
					duration = Math.round(duration * 1000) / 1000;
					console.log('Remaining time:', duration - currentTime);
					//如果超过动画时长，则等音频播放完成后再移动手指
					if(duration - currentTime > 0.6){
						this.textTwinkle(node);
						cc.audioEngine.setFinishCallback(audioId, () => {
							this._showStandby = false;
							showNext();
						});
					}
					else{
						this.textTwinkle(node, () => {
							this._showStandby = false;
							showNext();
						});
					}

					
				}
				else{
					this.textTwinkle(node);
				}

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

				break;
			}

		}

		requestAnimationFrame(() => {

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


	/**
	 * 文本内容动画
	 * @param {*} node 
	 * @param {*} callback 
	 */
	_playText: null,
	textTwinkle(node, callback = null) {

		if (this._playText) {
			return;
		}

		this._playText = true;

		this._cantouch = false;

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

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


	/**
	 * 内容动画
	 */
	 _times:null,
	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;
					
					if(this._shown){
						return;
					}
					this._curIndex++;

					if(this._curIndex >= this.data.exercises.wordArr.length && !this._times){
						this._times = 1;

						this._curIndex = 0;
			
						console.log("the first time");
					}

					this.moveHand(this._curIndex, () => {
						this._cantouch = true;

						this.showEnd();
					})
				})
				.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');
		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.photoBtnClick();
			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();

		})

	},

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

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



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

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

		openRecognitionCamera((data) => {
			console.log('openRecognitionCamera data: ', data)

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

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

			this.maskNode.active = false;

		})

	},

	photoEnd(data) {

		const isRightArea = this.checkIsRightArea(data);

		if (!isRightArea) {
			playAudio(this.audioTipArea.clip)
			console.log('没有检测到此题的区域')
			return;
		}

		const isRightLetter = this.checkIsRightLetter(data);

		if (!isRightLetter) {
			playAudio(this.audioTipLetter.clip)
			console.log('没有检测到此题的字母')
			return;
		}

		const isRightPos = this.checkIsRightPos(data);

		if (!isRightPos) {
			playAudio(this.audioTipIcon.clip)
			console.log('此题的区域内没有检测到标记')
			return;
		}

		playAudio(this.audioTipSuccess.clip)
		this.showPhotoSuccess();
	},

	getPhotoLabelData2(text, block, len) {

		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];
				let sentence = ''
				word.forEach(item => {
					sentence += item.content + ' ';
				});

				sentence.trim();

				const index = sentence.indexOf(text);
				if (index == -1 && sentence.length >= len) {
					return line[i];
				}


			}
		}

		return false;
	},

	getPhotoLabelData(text, block, topY = null, bottomY = null) {

		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];
				let sentence = ''
				word.forEach(item => {
					sentence += item.content + ' ';
				});

				sentence.trim();

				if (sentence.indexOf(text) != -1) {

					if (topY && bottomY) {
						const sentenceY = line[i].location.top_left.y

						console.log('topY: ', topY)
						console.log('bottomY: ', bottomY)
						console.log('sentenceY: ', sentenceY)
						if (bottomY >= sentenceY && sentenceY >= topY) {
							return line[i];
						}
					} else {
						return line[i];
					}
				}
			}
		}

		return false;
	},

	checkIsRightArea(result) {
		const block = result?.data?.block
		if (!block) {
			return false;
		}
		const topLabelData = this.getPhotoLabelData('n and repeat', block);
		// const bottomLabelData = this.getPhotoLabelData('n, point, and repeat', block);
		const bottomLabelData = this.getPhotoLabelData2('n and repeat', block, 25);
		return topLabelData && bottomLabelData
	},

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


		const topLabelData = this.getPhotoLabelData('n and repeat', block);
		const bottomLabelData = this.getPhotoLabelData2('n and repeat', block, 25);

		const topY = topLabelData.location.top_left.y;
		const bottomY = bottomLabelData.location.top_left.y;

		const letter = this.data.letter || 'A';
		const letterLabelData = this.getPhotoLabelData(letter, block, topY, bottomY);


		return letterLabelData;
	},

	checkIsRightPos(result) {
		const block = result?.data?.block
		if (!block) {
			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);	
		const bottomLabelData = this.getPhotoLabelData2('n and repeat', block, 25);
		if (!iconLabelData) {
			return false;
		}

		// console.log('block: ', block);
		// console.log('topLabelData: ', topLabelData);
		// console.log('bottomLabelData: ', bottomLabelData);
		const topY = topLabelData.location.top_left.y;
		const bottomY = bottomLabelData.location.top_left.y;
		const iconY = iconLabelData.location.top_left.y;

		console.log('topY: ', topY);
		console.log('bottomY: ', bottomY);
		console.log('iconY: ', iconY);


		if (bottomY >= iconY && iconY >= topY) {
			return true;
		}
	},

	showPhotoSuccess() {
		console.log(' in showPhotoSuccess')
		this.hidePhotoBtn();
	},

	getPhotoData(cb) {

		const tmpData = { "text": "", "audio": "", "result": { "code": "0", "data": { "block": [{ "type": "text", "line": [{ "confidence": 1, "location": { "top_left": { "x": 112, "y": 63 }, "right_bottom": { "x": 497, "y": 114 } }, "word": [{ "content": "Unit" }, { "content": "1" }, { "content": "Aa" }, { "content": "Bb" }, { "content": "Cc" }] }, { "confidence": 1, "location": { "top_left": { "x": 160, "y": 121 }, "right_bottom": { "x": 401, "y": 162 } }, "word": [{ "content": "A" }, { "content": "Listen" }, { "content": "and" }, { "content": "repeat.03" }] }, { "confidence": 1, "location": { "top_left": { "x": 607, "y": 141 }, "right_bottom": { "x": 657, "y": 184 } }, "word": [{ "content": "V" }] }, { "confidence": 1, "location": { "top_left": { "x": 335, "y": 246 }, "right_bottom": { "x": 417, "y": 277 } }, "word": [{ "content": "I" }, { "content": "like" }] }, { "confidence": 1, "location": { "top_left": { "x": 448, "y": 208 }, "right_bottom": { "x": 640, "y": 306 } }, "word": [{ "content": "Aa" }] }, { "confidence": 1, "location": { "top_left": { "x": 351, "y": 275 }, "right_bottom": { "x": 401, "y": 304 } }, "word": [{ "content": "..." }] }, { "confidence": 1, "location": { "top_left": { "x": 303, "y": 307 }, "right_bottom": { "x": 352, "y": 327 } }, "word": [{ "content": "angry" }, { "content": "to" }] }, { "confidence": 1, "location": { "top_left": { "x": 223, "y": 318 }, "right_bottom": { "x": 449, "y": 364 } }, "word": [{ "content": "Listen.polnt.andrepeat.ou" }] }] }] }, "desc": "success", "sid": "wcr005666b3@dx2d0714d48cc56f2b00" }, "error": "" }

		cb(tmpData);
	},


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

			});
		}
	},

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

});
