import { getSprNode, onHomeworkFinish, playAudio } 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;

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

		for (let i=0; i<this.data.letter_arr.length; i++) {
			this._audioResList.push({ url: this.data.letter_arr[i].audio_url });
		}

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

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

				// this.log('in osmoHandwritingCallback');
				if (!data) {
					// this.log('data is not exist!!!');
					return;
				}
			
				console.log('osmoHandwritingCallback data: ', data);

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

					this.photoEnd(dataObj);
					return;
				}

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

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


	loadEnd() {

		if (this.isInitEnd) {
			this.log(' isInitEnd ')
			return;
		}
		this.initData();
		this.initAudio();
		this.initView();

		this.isInitEnd = true;


		// this.initListener();
	},


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

	},

	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.audioTipArea = getAudioByResName('tip_area');
		
		this.audioTipError = getAudioByResName('tip_error');
		this.audioTipNotFill = getAudioByResName('tip_not_fill');
		this.audioTipFillWrong = getAudioByResName('tip_fill_wrong');

		this.audioTipLetter = getAudioByResName('tip_letter');
		this.audioTipIcon = getAudioByResName('tip_icon');
		this.audioTipSuccess = getAudioByResName('tip_success');

		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;
			}
			cw.openOsmoHandwriting(0.4);


			// setInterval(() => {
				// this.getPhotoData((data) => {
				// 	this.photoEnd(data);
				// });           
				
			// }, 1000);
		},
	
		//结束检测
		endTesting() {
			const cw = window.courseware;
			if (!cw || !cw.closeOsmoHandwriting) {

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

	initView() {

		this.initBg();

		this.initLetterItem();
		// this.initPhotoBtn();
		// this.initContent();

		// this.initDebugLayer();

		this.gameStart();

		// // this.showPhotoBtn();

		// this.addDefaultMusic();

		// this.initMask();



	},

	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.scale = this._mapScaleMin;
		itemLetterBig.anchorY = 0.28
		this.canvas.addChild(itemLetterBig);

		const itemBgBig = getSprNode('item_bg');
		itemBgBig.scale = this._mapScaleMin;
		itemBgBig.anchorX = 0;
		this.canvas.addChild(itemBgBig);

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

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

		const baseX = letterAnim0.x + 150;
		const baseY = letterAnim0.y;
		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);


		const letterAnim0 = this.getLetterAnimSmall0(letterS);
		letterAnim0.x = 100;
		letterAnim0.y = 0;
		itemBgSmall.addChild(letterAnim0);

		const baseX = letterAnim0.x + 150;
		const baseY = letterAnim0.y;
		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(letter) {

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

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

	getLetterAnimSmall0(letter) {

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

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

	getOneItem(data, index) {
		const item = getSprNode('item_bg');
		item.scale = this._mapScaleMin;

		const id = index + 1;
		const icon = getSprNode('icon_' + id)
		icon.x = -item.width / 2 + 30;
		icon.y = item.height / 2 - 30;
		item.addChild(icon);

		
		let resName = 'letter';

		if (!data.is_right) {
			resName = 'x';
		}

		const anim = cc.find("Canvas/res/anim/" + resName)
		const letter = cc.instantiate(anim)	
		// letter.scale = this._mapScaleMax;
		// const canvas = cc.find('Canvas');
		// canvas.addChild(letter, 100);
		letter.name = resName;


		// const letter = getSprNode(resName);
		item.addChild(letter);
		letter.active = false;
		item.letter = letter;

		const btnSound = getSprNode('btn_sound');
		btnSound.x = item.width / 2 - 30;
		btnSound.y = item.height / 2 - 30;
		item.addChild(btnSound);
		btnSound.active = false;
		item.btnSound = btnSound;
		btnSound.addComponent(cc.Button);
		btnSound.on('click', () => {
			console.log('btnSond click');
			this.playAudioByUrl(data.audio_url, () => {
	
			});
		})

		return item;
	},

	initContent() {

		const content = cc.find('Canvas/content');
		content.zIndex = 10;
	},

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


	
		// const rect = {
		// 	x: 100,
		// 	y: 100,
		// 	width: 1000,
		// 	height: 1000
		// }
		// const colorRect = this.getColorRect(rect, cc.Color.BLACK);
		// layer.addChild(colorRect);


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

 
	gameStart() {


		
		// this.showLetter(0);
		// this.showLetter(1, () => {

		// 	this.showAllSound();

		// 	this.startTesting();

		// });
		// return;



		this.playAni('begin', 0)
		//播放引导音频1

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

			this.playAni('normal', -1)

			// this.playAudioByUrl(this.data.guideAudioUrl1, () => {
			// this.showFirstLetter();

		});
	},


	showFirstLetter() {
	
		this.showLetter(0, () => {

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


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

				this.showSecondLetter();
			});
			
		})
	},

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

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

		

				this.showAllSound();
				// this.showPhotoBt n();
				this.startTesting();

				this.playAni('normal', 0);

			});
	
		})
	},


	showLetter(index, cb, needCheck = false) {

		const item = this.letterItemArr[index];

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

		}
	

		if (item.isShow) {
			return;
		}

		if (needCheck) {
			playAudio(this.audioRight.clip)
		}

		item.isShow = true;

		this.timer_1 = setTimeout(() => {
			
			this.showItemAni(item.btnSound, null);
			this.showItemAniNew(item.letter, () => {
				if (cb) {
					cb();
				}
			});

		}, 100 * Math.random());



	},

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





	photoEnd(data) {

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



		this.debugLayer.removeAllChildren();


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


		// this.log('检测到区域')

		

		const answerData = this.getAnswerData(data);



		this.showUserRight(answerData);


		const isFillAll = this.checkIsFillAll(answerData);
		if (!isFillAll) {

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

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

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

		this.showPhotoSuccess();

		
	},

	showUserRight(answerData) {


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

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


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

			if (answerData[key]) {

				if (letterData.is_right) {
					this.showLetter(i, null, true);
				} else if (!letterData.is_right  && answerData[key].isWrongLetter) {
					this.showLetter(i, null, true);
				}

			} else {

				const item = this.letterItemArr[i];
				item.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) {
				console.log("第" + (i+1) + "题 不对")
				return false;

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

		const titleLocation = topLabelData.word[0].location
		// const checkX = titleLocation.left + (titleLocation.right - titleLocation.left) / 3;

		const unit = titleLocation.bottom - titleLocation.top;


		// 12

		const checkY1 = -titleLocation.bottom;

		console.log('')

		const checkY2 = -titleLocation.bottom - ( unit * 4.08 );

		const checkX = titleLocation.right + ( unit * 8.33 );

		

		text = text.trim();

		let topLeftLetter;

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

		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];
				const location = word[0].location;
			
				let sentence = ''
				word.forEach(item => {
					sentence += item.content + ' ';
				});
	
				sentence.trim();
	
				line[i].sentence = sentence;
				console.log('sentence: ', sentence);
				if (sentence.indexOf(text) != -1 && sentence.length <= 4) {


					if (-location.top >= checkY1 || -location.top <= checkY2) {
						continue;
					}

					if (location.left >= checkX) {
						continue;
					}

					if (location.top == titleLocation.top) {
						continue;
					}

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

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

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

	getPhotoLabelData_(text, 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];
				let sentence = ''
				word.forEach(item => {
					sentence += item.content + ' ';
				});
	
				sentence.trim();
	
				line[i].sentence = sentence;
				if (sentence.indexOf(text) != -1 ) {
					return line[i];
				}
			}
		}

		return false;
	},

	getPhotoWordArr(text, data, topLabelData) {

		const result = data.result;


		// const titleLocation = topLabelData.word[0].location;

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

		// text = text.trim()[0];


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


			const wordData = result[i];
			if (-wordData.top >= -topLabelData.top) {
				continue;
			}

			if (wordData.classIdentifier == text) {
				wordArr.push(wordData)
			}
			
		}

		return wordArr;
	},

	checkCutWordData(wordArr) {


		console.log('wordArr: ', 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;
	},


	checkIsRightArea(data) {


		let letter = this.data.letter || 'Aa';
		let checkLetter;
		if (letter == "Aa") {
			checkLetter = 'A2'
		} 

		const topTitleData = this.getIdentifierArr(data, 'originD')[0];
		if (!topTitleData) {
			return false;
		}
		const topLeftLetterData = this.getTopLeftLetterData(data, checkLetter, topTitleData);
		
		this.topTitleData = topTitleData;
		// this.bottomTitleData = bottomTitleData;
		this.topLeftLetterData = topLeftLetterData;
		
		console.log('topTitleData:', topTitleData);
		// console.log('bottomTitleData:', bottomTitleData);
		console.log('topLeftLetterData:', topLeftLetterData);

		return topTitleData && topLeftLetterData;


	},


	getTopLeftLetterData(result, identifier, topTitleData) {
		
		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) {
			return;
		}
		
		const unit = topTitleData.bottom - topTitleData.top;
		const targetY = -topTitleData.bottom - unit * 1.5;
		const targetX = topTitleData.left + (topTitleData.right - topTitleData.left) / 2;

		if (-topLeftLetter.top < targetY) {
			this.log(' < targetY')
			this.log(' titleY: ' + -topTitleData.bottom);
			this.log(' unit: ' + unit);
			this.log(' letter y: ' + -topLeftLetter.bottom)
			this.log(' targetY : ' + targetY)
			return;
		}
		if ( topLeftLetter.left > targetX) {
			this.log(' > 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;
	},



	getAnswerData(data) {



		const letter = this.data.letter || 'Aa';
		let checkLetter;
		if (letter == "Aa") {
			checkLetter = 'A2'
		}


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


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


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

		const answerData = {};

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

			const wordData = data.result[i];

			if (wordData.classIdentifier != 'fork' && wordData.classIdentifier != checkLetter) {				
				continue;
			}

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


			let color = null;
			if (wordData.classIdentifier == 'fork') {
				color = cc.Color.YELLOW
				color = 'yellow'
			}
			const colorRect = this.getColorRect(rect, color);
			this.debugLayer.addChild(colorRect);

			this.setOneAnswerData(colorRect, dotArr, answerData);

			if (wordData.classIdentifier == 'fork') {
				colorRect.isWrongLetter = true;
			}
	
		}

	



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

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

		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;

	
		this.debugLayer.addChild(label);
	},

	setTestRectDot(topLabelData, topLeftLetter, wordDataArr) {

	
		// const letterLocation = topLeftLetter.word[0].location;
		// const titleLocation = topLabelData.word[0].location;
		const unitH = topLeftLetter.bottom - topLabelData.bottom;
		console.log('unitH: ', unitH)


		//49


	
		// const topLeftPos = topLeftLetter.location.top_left;

		
		const rectH = 0.469 * unitH//23   

		const rectW = 0.48 * unitH//41

		// const disW = 1.65 * unitH //101
		const disW = 1.13 * unitH //101

		const disH = 1.1 * unitH //49


		


		const baseX = topLeftLetter.right - rectW / 2;
		let baseY = -(topLeftLetter.top - rectH / 2 );
		// const baseX = 2.898 * unitH  // 142
		// let baseY = -( 5.612 * unitH ); // -275


		
		console.log('baseX: ', baseX);
		console.log('baseY: ', baseY);

		// wordDataArr.forEach(item => {
		// 	const pos = item.location.top_left;

		// 	item.cLen = Math.sqrt ( Math.pow(pos.x, 2) + Math.pow(pos.y, 2) );
		// })


		wordDataArr.forEach(item => {
			// const pos = item.location.top_left;
			const posX = item.left;
			const posY = item.top;
			item.cLen = Math.sqrt ( Math.pow(posX, 2) + Math.pow(posY, 2) );
		})

		wordDataArr = wordDataArr.sort((a, b) => {
			return a.cLen - b.cLen;
		})


		let col = 0;

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

			if (i == 2) {
				baseY -= disH;
				col = 0;
			}
		}

		return dotArr;

	},

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

	getColorRect(rect, color=null) {

		if (!color) {
			color = 'red'
		}
		// const node = new cc.Node();
		// const colorRect = node.addComponent(cc.Graphics);
		// 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=100) {
		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);



			// const rect1 = new cc.Rect(node.x -r/2, node.y -r/2, r, r);
			// const colorDot = this.getColorRect(rect1, 'green');

			// colorDot.dotRect = rect1;
			// return colorDot;
		}

		node.x = x;
		node.y = 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() {

		if (this.isSuccess) {
			return;
		}
		this.isSuccess = true;
		console.log(' in showPhotoSuccess')

		playAudio(this.audioTipSuccess.clip)
		

		this.endTesting();
	},

	getPhotoData(cb) {

		const tmpData = {
			"result": [
				{
					"bottom": 0.6095132,
					"classIdentifier": "A2",
					"classIndex": "1",
					"confidence": 0.89716965,
					"left": 0.2693717,
					"right": 0.37937102,
					"top": 0.5256099
				},
				{
					"bottom": 0.08970478,
					"classIdentifier": "originC",
					"classIndex": "3",
					"confidence": 0.8324693,
					"left": 0.12389323,
					"right": 0.41298285,
					"top": 0.003045585
				},
				{
					"bottom": 0.4752521,
					"classIdentifier": "originD",
					"classIndex": "4",
					"confidence": 0.75511265,
					"left": 0.13089058,
					"right": 0.67333806,
					"top": 0.40243015
				},
				{
					"bottom": 0.6113949,
					"classIdentifier": "A2",
					"classIndex": "1",
					"confidence": 0.73831165,
					"left": 0.61086684,
					"right": 0.6818537,
					"top": 0.5284275
				},
				{
					"bottom": 0.37669334,
					"classIdentifier": "xA1",
					"classIndex": "6",
					"confidence": 0.7338014,
					"left": 0.45656323,
					"right": 0.5282546,
					"top": 0.30524808
				},
				{
					"bottom": 0.751232,
					"classIdentifier": "A2",
					"classIndex": "1",
					"confidence": 0.71206063,
					"left": 0.31878722,
					"right": 0.38491434,
					"top": 0.6789177
				},
				{
					"bottom": 0.22740719,
					"classIdentifier": "A1",
					"classIndex": "0",
					"confidence": 0.6758007,
					"left": 0.42890796,
					"right": 0.5239676,
					"top": 0.10524011
				},
				{
					"bottom": 0.7594966,
					"classIdentifier": "A2",
					"classIndex": "1",
					"confidence": 0.6149159,
					"left": 0.6216999,
					"right": 0.6833995,
					"top": 0.6882967
				},
				{
					"bottom": 0.36094537,
					"classIdentifier": "xA1",
					"classIndex": "6",
					"confidence": 0.54596454,
					"left": 0.16600542,
					"right": 0.23377652,
					"top": 0.29491317
				},
				{
					"bottom": 0.76954556,
					"classIdentifier": "fork",
					"classIndex": "2",
					"confidence": 0.48939666,
					"left": 0.46151394,
					"right": 0.5331044,
					"top": 0.6959772
				}
			]
		}

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

			});
		}
	},

	onDestroy() {
		console.log(' in onDestroy OP_08')

		this.isDestroy = true;
		clearInterval(this.timer_1);
		clearInterval(this.timer_2);

	}
	// ------------------------------------------

});
