import { onHomeworkFinish, RandomInt, playAudio, playDragonBoneAnimation, asyncDelay, setSprNodeMaxLen, getSprNodeByUrl, getSprNode, showTrebleFirework } from "../script/util_JJ38";
import { defaultData } from "../script/defaultData_JJ38";

cc.Class({

	extends: cc.Component,

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

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

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

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

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

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

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

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

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

	},

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

	// 生命周期 onLoad
	onLoad() {
		this._timeoutIds = [];
		this._intervalIds = [];
		this.initSceneData();
		this.initSize();
	},

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

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

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

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

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

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


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

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

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

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


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

		// this.bindAlligatorButton(this._alligator);

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

			this.submitBtnClick();

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

		node.teeth = teeth;
		return node;
	},

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

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

		button.clickEvents.push(clickEventHandler);
	},

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

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

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

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

		func(this.getDefaultData());
	},

	getDefaultData() {
		return {"title":"Listen and colour.","audio_url":"http://staging-teach.cdn.ireadabc.com/555083b19cc70078d2ece421b0619520.mp3","picArr":[{"pic_url":"http://staging-teach.cdn.ireadabc.com/90ce5433218c53cb580a57a04ce696f8.png","colorData":{"key":"Blue","value":"蓝色","code":"#3988FF"}},{"pic_url":"http://staging-teach.cdn.ireadabc.com/223b1e8fc317bd435397347f6756c79b.png","colorData":{"key":"Yellow","value":"黄色","code":"#FAFF04"}},{"pic_url":"http://staging-teach.cdn.ireadabc.com/2c4061df2a7d91590b17580d6a426e7b.png","colorData":{"key":"Pink","value":"粉色","code":"#FFC6EC"}},{"pic_url":"http://staging-teach.cdn.ireadabc.com/a89d9738d55bd7373e34141f4c1c3e65.png","colorData":{"key":"Black","value":"黑色","code":"#555555"}},{"pic_url":"http://staging-teach.cdn.ireadabc.com/ee942a82682b6d5929c7f0b7c9b2c071.png","colorData":{"key":"Yellow","value":"黄色","code":"#FAFF04"}}],"pic_url":"http://staging-teach.cdn.ireadabc.com/f4d9c566c17699ff7af21ec3beaa7d97.png","bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/f4d9c566c17699ff7af21ec3beaa7d97.png","rect":{"x":405.12,"y":0,"width":1066.76,"height":717}},"hotZoneItemArr":[{"id":"1716804401017","index":0,"itemType":"rect","fontScaleX":1.46640625,"fontScaleY":1.46640625,"imgScale":1,"imgSizeW":0,"imgSizeH":0,"mapScale":1.46640625,"dragDot":{"x":938.5,"y":358.5},"gIdx":"0","posX":612.5,"posY":657.5,"labelArr":[{"key":"number","title":"序号","value":"1"}],"sizeW":56.99999999999999,"sizeH":56.99999999999999,"rect":{"x":178.88,"y":629,"width":57,"height":57}},{"id":"1716804410047","index":1,"itemType":"rect","fontScaleX":1.46640625,"fontScaleY":1.46640625,"imgScale":1,"imgSizeW":0,"imgSizeH":0,"mapScale":1.46640625,"dragDot":{"x":938.5,"y":358.5},"gIdx":"0","posX":872.5011925785761,"posY":576.4975947226569,"labelArr":[{"key":"number","title":"序号","value":"2"}],"sizeW":56.99979148165999,"sizeH":56.99979148165999,"rect":{"x":438.88,"y":548,"width":57,"height":57}},{"id":"1716804421092","index":2,"itemType":"rect","fontScaleX":1.46640625,"fontScaleY":1.46640625,"imgScale":1,"imgSizeW":0,"imgSizeH":0,"mapScale":1.46640625,"dragDot":{"x":938.5,"y":358.5},"gIdx":"0","posX":619.5002414422884,"posY":386.49789103819273,"labelArr":[{"key":"number","title":"序号","value":"3"}],"sizeW":56.99979148165999,"sizeH":56.99979148165999,"rect":{"x":185.88,"y":358,"width":57,"height":57}},{"id":"1716804428169","index":3,"itemType":"rect","fontScaleX":1.46640625,"fontScaleY":1.46640625,"imgScale":1,"imgSizeW":0,"imgSizeH":0,"mapScale":1.46640625,"dragDot":{"x":938.5,"y":358.5},"gIdx":"0","posX":1142.5011669710607,"posY":512.4985860993261,"labelArr":[{"key":"number","title":"序号","value":"4"}],"sizeW":56.99979148165999,"sizeH":56.99979148165999,"rect":{"x":708.88,"y":484,"width":57,"height":57}},{"id":"1716804439994","index":4,"itemType":"rect","fontScaleX":1.46640625,"fontScaleY":1.46640625,"imgScale":1,"imgSizeW":0,"imgSizeH":0,"mapScale":1.46640625,"dragDot":{"x":938.5,"y":358.5},"gIdx":"0","posX":1228.4992537238356,"posY":270.49812516404813,"labelArr":[{"key":"number","title":"序号","value":"5"}],"sizeW":56.99979148165999,"sizeH":56.99979148165999,"rect":{"x":794.88,"y":242,"width":57,"height":57}}]}
		return defaultData;
	},

	preloadItem() {

		if (this.data?.audio_url) {
			this._audioResList.push({url: this.data.audio_url});
		}


		if (this.data?.pic_ur) {
			this._imageResList.push({url: this.data.pic_ur});
		}
		if (this.data?.picArr) {
			for (let i=0; i<this.data.picArr.length; i++) {
				this._imageResList.push({url: this.data.picArr[i].pic_url});
			} 
		}

		this.preload();
	},


	preload() {

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

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

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

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


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


	initView() {

		this.initBgContainer();
		this.initTitle();
		this.initAudioPlayer();
		this.initPanel();
		this.initColorPanel();

		this.showBackBtn();

		this.initListener();

	},

	initListener() {

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

		const touchStart = (e) => {
			this.canvasTouchStart(e);
			console.log('touch start');
			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_DOWN)) {
				canvas.off(cc.Node.EventType.MOUSE_DOWN, mouseDown)
			}
		}

		const mouseDown = (e) => {
			if (!downFlag) {
				return;
			}
			this.canvasTouchStart(e);
			console.log('mouse down');

			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
				canvas.off(cc.Node.EventType.TOUCH_MOVE, touchMove)
				// this.removeHtmlCanvasListener('touchmove');
			}
		}

		const touchMove = (e) => {
			this.canvasTouchMove(e);

			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_MOVE)) {
				canvas.off(cc.Node.EventType.MOUSE_MOVE, mouseMove)
			}
		}

		const mouseMove = (e) => {
			if (!downFlag) {
				return;
			}
			this.canvasTouchMove(e);
			console.log('mouse move');

			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
				canvas.off(cc.Node.EventType.TOUCH_MOVE, touchMove)
				// this.removeHtmlCanvasListener('touchmove');
			}
		}

		const touchEnd = (e) => {

			downFlag = false;
			this.canvasTouchEnd(e);

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

		const mouseUp = (e) => {

			downFlag = false;

			this.canvasTouchEnd(e);

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


		// canvas.on(cc.Node.EventType.TOUCH_START, touchStart)
		// canvas.on(cc.Node.EventType.MOUSE_DOWN, mouseDown)

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

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

	},

	canvasTouchStart(e) {


		const pos = e.getLocation();
		// this.knife.x = pos.x - e.currentTarget.width / 2;
		// this.knife.y = pos.y - e.currentTarget.height / 2;


	},

	canvasTouchMove(e) {

		const pos = e.getLocation();
		// this.knife.x = pos.x - e.currentTarget.width / 2;
		// this.knife.y = pos.y - e.currentTarget.height / 2;


		if (!this.isProgressBtnDown) {
			return;
		}

		const curTouchBar = this.progressBtn;
		if (curTouchBar) {

			const px = pos.x - e.currentTarget.width / 2;
			const py = pos.y - e.currentTarget.height / 2;

			const worldPos = this.canvas.convertToWorldSpaceAR(cc.v2(px, py));
			const localPos = curTouchBar.parent.convertToNodeSpaceAR(worldPos);

			curTouchBar.x = localPos.x;
			if (curTouchBar.x < curTouchBar.minX) {
				curTouchBar.x = curTouchBar.minX;
			} else if (curTouchBar.x > curTouchBar.maxX) {
				curTouchBar.x = curTouchBar.maxX;
			}

			this.setPlayerTimeByTouchBar(curTouchBar);

		}

	},

	setPlayerTimeByTouchBar(curTouchBar) {


		let percent = curTouchBar.x / curTouchBar.maxX;
		const duration = this.totalTime;// this.muteVideoPlayer.getDuration();
		const curTime = duration * percent;
		// this.muteVideoPlayer.currentTime = curTime;

		// console.log("duration: " , duration);
		// console.log("curTouchBar: " , curTouchBar);
		// console.log("curTime: " , curTime);

		cc.audioEngine.setCurrentTime(this.audioId, curTime);
		this.setProgressBar(curTime);
		// console.log('this.audioId: ', this.audioId);
	},

	canvasTouchEnd(e) {

		this.isProgressBtnDown = false;
		// if (!this._curShowItem) {
		// 	return;
		// }

		// this._curShowItem = null;
	},



	initBgContainer() {
		const bgContainer = cc.find('Canvas/bg_container');
		const canvas = cc.find("Canvas");
		const sx = canvas.width / bgContainer.width;
		const sy = canvas.height / bgContainer.height;
		bgContainer.scale = Math.min(sx, sy) * 1;
	},

	showBackBtn() {
		const backBtn = cc.find('Canvas/back_btn');
		backBtn.active = true;
		backBtn.zIndex = 30;
		
		backBtn.on('touchstart', () => {
			const middleLayer = global["middleLayer"];
			if (middleLayer) {
				// 有些模板需要在返回时上报数据，直接把数据作为参数传入就可以了
				middleLayer.exitGame({});
			} else {
				console.log("==触发返回事件==");
			}
		})
	},
	


	initTitle() {
		const title = cc.find('Canvas/bg_container/top_part/title');
		const titleLabel = title.getComponent(cc.Label);
		titleLabel.string = this.data.title || '';
	},

	initAudioPlayer() {
		const audioPlayer = cc.find('Canvas/bg_container/top_part/AudioPlayer');
		const playBtn = cc.find('play', audioPlayer);
		const pauseBtn = cc.find('pause', audioPlayer);

		this.playBtn = playBtn;
		this.pauseBtn = pauseBtn;

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

		this.curTimeLabel = cc.find('curTime', audioPlayer).getComponent(cc.Label);
		const totalTimeLabel = cc.find('totalTime', audioPlayer).getComponent(cc.Label);
		this.progressBar = cc.find("timeBar", audioPlayer).getComponent(cc.ProgressBar);
		this.progressBtn = cc.find("timeBar/progressBtn", audioPlayer);
		this.progressBtn.baseX = this.progressBtn.x;

		this.progressBtn.minX = 0;
		this.progressBtn.maxX = this.progressBtn.parent.width;

		this.progressBtn.on('touchstart', (e) => {
			this.isProgressBtnDown = true;
			
			if (this.audioId != null) {
				this.pauseAudio();
				// cc.audioEngine.pause(this.audioId);
			}
		});


		



		let audioClip;

		let totalTimeAudioId;
		cc.assetManager.loadRemote(this.data.audio_url, (err, _audioClip) => {
			audioClip = _audioClip;
			this.totalTime = audioClip.duration;
			totalTimeLabel.string = this.formatTime(this.totalTime * 1000);

			if (!this.totalTime) {
				totalTimeAudioId = cc.audioEngine.play(audioClip, false, 0);
				// this.audioId = totalTimeAudioId;
				checkHasDuration();
			} else {
				
			// 	this.audioId =  cc.audioEngine.play(audioClip, false, 0.8);
			// 	setTimeout(() => {
			// 		if (this.isDestroy) {
			// 			return;
			// 		}
			// 		cc.audioEngine.pause(this.audioId);
			// 	}, 10);
			}

			

			// setTimeout(() => {
			// 	if (this.isDestroy) {
			// 		return;
			// 	}
			// 	totalTimeLabel.string = this.formatTime(audioClip.duration * 1000);

			// }, 300);
		});



		const checkHasDuration = () => {

			setTimeout(() => {

				console.log(' in checkIsPlaying 1')

				if (totalTimeAudioId == null) {
					return;
				}

				if (this.isDestroy) {
					return;
				}

				let duration = cc.audioEngine.getDuration(totalTimeAudioId);

				if (duration) {


					cc.audioEngine.stop(totalTimeAudioId);

					this.totalTime = duration;
					totalTimeLabel.string = this.formatTime(duration * 1000);

				} else {
					checkIsPlaying();
				}

			}, 300);
		}



		// this.audioId =  cc.audioEngine.play(audioClip, false, 0.8);
		// cc.audioEngine.pause(this.audioId);
		// this.audioId = audioId;

		playBtn.on('touchstart', () => {
			pauseBtn.active = true;
			playBtn.active = false;

			this.isAudioPlaying = true;

			if (this.audioId != null) {
				cc.audioEngine.resume(this.audioId);
			} else {
				this.audioId = cc.audioEngine.play(audioClip, false, 0.8);
			}

			cc.audioEngine.setFinishCallback(this.audioId, () => {

				if (this.isDestroy) {
					return;
				}

				// this.audioId =  cc.audioEngine.play(audioClip, false, 0.8);
				// setTimeout(() => {
				// 	if (this.isDestroy) {
				// 		return;
				// 	}
				// 	cc.audioEngine.pause(this.audioId);
				// }, 10);


				playBtn.active = true;
				pauseBtn.active = false;
				this.isAudioPlaying = false;
				this.audioId = null;
				// this.audioId = audioId = null;
			});
		})

		pauseBtn.on('touchstart', () => {
			this.pauseAudio();
		})

	},

	pauseAudio() {
		this.playBtn.active = true;
		this.pauseBtn.active = false;

		cc.audioEngine.pause(this.audioId);

		this.isAudioPlaying = false;
	},

	initPanel() {
		if (!this.data.pic_url) {
			return;
		}
		this.canvas = cc.find("Canvas");

		const panel = cc.find("Canvas/bg_container/panel");
		 
		// const sx = this.canvas.width / panel.width;
		// const sy = this.canvas.height / panel.height;
		// panel.scale = Math.min(sx, sy);

		


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

			spr.node.y = 5;
			setSprNodeMaxLen(spr.node, panel.width * 0.95, panel.height * 0.95);
			panel.addChild(spr.node);

			const paintBg = spr.node;
		
			paintBg.on('touchstart', () => {
				this.playAudioByName('wrong');
			})

			for (let i=0; i<this.data.picArr.length; i++) {
				const data = this.data.picArr[i];
				getSprNodeByUrl(this.data.picArr[i].pic_url, (spr) => {
	
					paintBg.addChild(spr.node, i+1);

					this.bindSubImgHit(spr.node, data);
				})
			}

			this.initHotZoneBg(spr.node);

		})

	
	},

	initColorPanel() {

		const selectCircle = cc.find("Canvas/bg_container/color_panel/select");

		const colorArr = this.getColorArr();
	
		console.log('colorArr: ', colorArr);

		const disX = 120;
		const disY = 100 * this._mapScaleMin;
		const colorPanel = cc.find('Canvas/bg_container/color_panel');
		const colorBtnBase = cc.find('Canvas/bg_container/color_panel/color_btn');

		const colorObj = {};
		let len = 0;
		let colorBtnsHeight = 0;

		for (let i=0; i<colorArr.length; i++) {
			const color = colorArr[i].code;

			if (colorObj[colorArr[i].key]) {
				continue;
			}
			colorObj[colorArr[i].key] = true;
			len ++;
			
			const colorBtn = cc.instantiate(colorBtnBase);
			colorBtn.active = true;
			colorBtn.parent = colorBtnBase.parent;
			// colorBtn.x = i * disX;
			colorBtn.x = 0;
			colorBtn.y = -i * disY;

			colorBtnsHeight += colorBtn.height + disY;

			const colorSpr = cc.find("spr", colorBtn);
			colorSpr.color = cc.Color.fromHEX(new cc.Color(), color);

			const colorLabel = cc.find('label', colorBtn).getComponent(cc.Label);
			colorLabel.string = colorArr[i].key;

			
			colorBtn.on('touchstart', () => {
				this.playAudioByName('select');
				this.curPaintColor = cc.Color.fromHEX(new cc.Color(), color);
				this.curPaintColorCode = color;
				selectCircle.x = colorBtn.x;
				selectCircle.y = colorBtn.y;

				if (this.lastColorSpr) {
					this.lastColorSpr.scale = 1;
				}

				colorSpr.scale = 1.2;

				this.lastColorSpr = colorSpr;
			})

			if (i == 0) {
				this.curPaintColor = cc.Color.fromHEX(new cc.Color(), color);
				this.curPaintColorCode = color;
				selectCircle.x = colorBtn.x;
				colorSpr.scale = 1.2;
				this.lastColorSpr = colorSpr;

			}
		}

		// colorPanel.x = -(len - 1) * disX / 2;
		const panel = cc.find('Canvas/bg_container/panel');
		colorPanel.y = (len - 1) * disY / 2 + panel.y;


	},

	getColorArr() {
		const arr = [];
		if (this.data.picArr) {
			console.log('this.data.picArr: ' , this.data.picArr);
			this.data.picArr.forEach(it => {
				if (it.colorData) {
					arr.push(it.colorData);
				}
			})
		}
		return arr;
	},

	setProgressBar(curTime = null) {

		if (this.audioId == null) {
			return;
		}
		if (!curTime)  {
			curTime = cc.audioEngine.getCurrentTime(this.audioId);
		}
		this.curTimeLabel.string = this.formatTime(curTime * 1000);

		// console.log('this.totalTime: ' , this.totalTime);

		this.progressBar.progress = curTime / this.totalTime;
		this.progressBtn.x = this.progressBtn.baseX + this.progressBtn.parent.width * this.progressBar.progress;
	},

	updateTimeBar() {
		if (!this.isAudioPlaying) {
			return;
		}


		if (this.audioId == null) {
			return;
		}

		this.setProgressBar();

		// const curTime = cc.audioEngine.getCurrentTime(this.audioId);
		// this.curTimeLabel.string = this.formatTime(curTime * 1000);

		// this.progressBar.progress = curTime / this.totalTime;
		// this.progressBtn.x = this.progressBtn.baseX + this.progressBtn.parent.width * this.progressBar.progress;
	},

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

	

	formatTime(milliseconds = 0) {
		if (typeof milliseconds !== 'number' || isNaN(milliseconds) || milliseconds < 0) {
		  console.error('传入的不是一个有效的非负数值');
		  return null;
		}
	  
		// 转换毫秒到秒
		var totalSeconds = Math.floor(milliseconds / 1000);
	  
		// 计算分钟和秒
		var minutes = Math.floor(totalSeconds / 60);
		var seconds = totalSeconds % 60;
	  
		// 格式化分钟和秒为两位数字
		var formattedMinutes = String(minutes).padStart(2, '0');
		var formattedSeconds = String(seconds).padStart(2, '0');
	  
		// 拼接并返回格式化后的时间字符串
		return formattedMinutes + ':' + formattedSeconds;
	  },


	hotZoneBg: null,
	initHotZoneBg(hotZoneBg) {
	
		const data = this.data;

		hotZoneBg.data = data;
		data.hotZoneBg = hotZoneBg;

		this.initHotZoneItem(hotZoneBg);

	},

	initHotZoneItem(bgItem) {

		const hotZoneItemArr = this.data.hotZoneItemArr || [];
		this.editBoxArr = [];

		hotZoneItemArr.forEach((item) => {

			this.setOneInputRect(item, bgItem);
		});
	},

	setOneInputRect(data, bg) {
		console.log(" in setOneInputRect ~", data)

		const rectNode = this.setOneRect(data, bg);
		rectNode.zIndex += 100;
		
		// const tempPos = rectNode.position;
		// tempPos.x += rectNode.width / 2;
		// tempPos.y += rectNode.height / 2;
		// const worldPos = rectNode.parent.convertToWorldSpaceAR(tempPos);
		// const localPos = this.canvas.convertToNodeSpaceAR(worldPos);

		const inputBgBase = cc.find("Canvas/input_bg");
		const inputNode = cc.instantiate(inputBgBase);
		inputNode.active = true;
		inputNode.parent = rectNode;
		inputNode.x = rectNode.width / 2;
		inputNode.y = rectNode.height / 2;
		setSprNodeMaxLen(inputNode, rectNode.width, rectNode.height);


		const eBoxNode = cc.find("editBox", inputNode);

		const eBox = eBoxNode.getComponent(cc.EditBox);
		eBox.data = data;
		this.editBoxArr.push(eBox);

		const wrongIcon = getSprNode("X");
		wrongIcon.x = eBoxNode.width / 2 * eBoxNode.scaleX;
		wrongIcon.y = -eBoxNode.height / 2 * eBoxNode.scaleY;;
		eBoxNode.addChild(wrongIcon);
		wrongIcon.active = false;

		const wSize = wrongIcon.getBoundingBoxToWorld();
		wrongIcon.scale = 25 / wSize.width;

		eBox.wrongIcon = wrongIcon;

		eBoxNode.on('editing-did-ended', () => {
			this.onEditBoxEnded(eBox);
		});

	



		// const inputBg = getSprNode('input_bg');
		// rectNode.addChild(inputBg);
		// setSprNodeMaxLen(inputBg, rectNode.width, rectNode.height);
		// inputBg.x = rectNode.width / 2;
		// inputBg.y = rectNode.height / 2;

		// const numLabelNode = new cc.Node();
		// numLabelNode.addComponent(cc.Label);
		// numLabelNode.parent = inputBg;
		// numLabelNode.width = inputBg.width;
		// numLabelNode.height = inputBg.height;
		 
		// const eBoxNode = new cc.Node();
		// inputBg.addChild(eBoxNode);
		// eBoxNode.width = inputBg.width;
		// eBoxNode.height = inputBg.height;
		// const eBox = eBoxNode.addComponent(cc.EditBox);
		// eBox.textLabel = numLabelNode;


		// const eBoxNode = new cc.Node();
		// // eBoxNode.scale = 5;
		// inputBg.addChild(eBoxNode);
		// const eBox = eBoxNode.addComponent(cc.EditBox);
		// eBox.stayOnTop = true;
		// const textLabel = eBox.textLabel;
		// console.log('eBox: ' , eBox);
		// console.log('textlabel: ' , textLabel);
		
		// // textLabel.fontSize = 150;

		// eBoxNode.scale = 3;

		// eBoxNode.width = inputBg.width / eBoxNode.scale;
		// eBoxNode.height = inputBg.height / eBoxNode.scale;
		// // eBox.fontSize = 150;
		// eBox.placeholderFontSize = 150;
		// eBox.lineHeight = 200;
		// eBox.maxLength = 1;
		// // eBox.inputMode = cc.EditBox.InputMode.

		// eBox.node.on('editing-did-ended', this.onEditBoxEnded, this);
	

		
		// eBoxNode.parent = this.canvas;
		// eBoxNode.position = localPos;
		// eBoxNode.zIndex=30;



		// inputBg.scale = bg.scale;
		// this.canvas.addChild(inputBg);
		// inputBg.position = localPos;

		// const labelData = this.findOneLabelByKey(data.labelArr, 'key');
		// const key = labelData.value; // tempItem中的关键key获取
		// rectNode.key = key;

		
		// if(data.checkbox && data.checkbox.list[0].label == '自动换行' && data.checkbox.list[0].value == true) {
		// 	//多行
		// 	rectNode.warp = true;
		// }

		// if (data.anchorGroup != null) {
		// 	this.setRectNodeAnchor(data, bg, rectNode);
		// }

		// this.inputTextArr.push(rectNode);

	},

	onEditBoxEnded(curEditBox) {

		if (curEditBox) {
			const inputNum = curEditBox.string;
			if (!inputNum) {
				// this.playAudioByName('a_o');
				// return;
			} else {
				curEditBox.isEnd = true;
	
				const data = curEditBox.data;
				const targetNum = data.labelArr[0].value;
				if (inputNum != targetNum) {
	
					curEditBox.isWrong = true;
				} else {
					curEditBox.isWrong = false;
				}


			}
			
		}

	

		if (this.isFillEnd) {

			if (curEditBox.isWrong) {
				curEditBox.wrongIcon.active = true;
				this.playAudioByName('a_o');
			} else {
				curEditBox.wrongIcon.active = false;
				this.checkGameEnd();
			}
			
		} else {
			this.checkGameEnd();
		}
		
		
		return;
		

		for(let i=0; i<this.editBoxArr.length; i++) {
			const editBox = this.editBoxArr[i];
			const inputNum = editBox.string;
			if (!inputNum) {
				continue;
			}

			const data = editBox.data;
			const targetNum = data.labelArr[0].value;
			if (inputNum != targetNum) {

				editBox.string = '';
				this.playAudioByName('a_o');
				return;
			}
		}

		this.playAudioByName('right');
		this.checkGameEnd();
     

    },

	checkGameEnd() {
		for(let i=0; i<this.editBoxArr.length; i++) {
			const editBox = this.editBoxArr[i];
			if (!editBox.isEnd) {
				this.isFillEnd = false;
				return;
			}
			// const inputNum = editBox.string;
			// if (!inputNum) {
			// 	return;
			// }
		}

		for (let i=0; i<this.data.picArr.length; i++) {
			const data = this.data.picArr[i];
			if (!data.isEnd) {
				this.isFillEnd = false;
				return;
			}
		}

		
		this.isFillEnd = true;
		console.log("isFillEnd == true ");

		const isAllRight = this.checkIsAllRight();	
		if (!isAllRight) {
			// if (isShowWrongAudio) {
				// this.playAudioByName('a_o');
			// }

			if (!this.isFirstWrongEnd) {
				this.isFirstWrongEnd = true;
				this.playAudioByName('a_o');
			}
			return;
		}
	
		this.gameEnd();
	},

	checkIsAllRight() {
		let isAllRight = true;
		for(let i=0; i<this.editBoxArr.length; i++) {
			const editBox = this.editBoxArr[i];
			editBox.wrongIcon.active = editBox.isWrong
			if (editBox.isWrong) {
				isAllRight = false;
			}
		}

		for (let i=0; i<this.data.picArr.length; i++) {
			const data = this.data.picArr[i];
			data.wrongIcon.active = data.isWrong;
			if (data.isWrong) {
				isAllRight = false;
			}
		}

		return isAllRight;
	},

	gameEnd() {
		if (this.isGameEnd) {
			return;
		}
		
		this.isGameEnd = true;
	
		this.playAudioByName('finish');
		const camera = cc.find('Canvas/Main Camera');
		camera.zIndex = 100;

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

		const panelMask = cc.find('Canvas/bg_container/panel_mask');
		panelMask.active = true;
	},


	setOneRect(data, bg, color=cc.Color.BLACK) {
		const quesData = bg.data;
		const rate = (bg.scale * bg.width) / quesData.bgItem.rect.width;

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


		const ctx = rectNode.addComponent(cc.Graphics);

		ctx.lineWidth = 4;
		ctx.strokeColor = color;//cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / bg.scaleY;


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

		rectNode.anchorX = rectNode.anchorY = 0;

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

	

		rectNode.addComponent(cc.Button);


		return rectNode;


	},








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

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

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

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

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

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

		this.bindAlligatorButton(this._alligator);

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


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

		console.log(' coolcat play end')

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

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

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

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

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


	// ------------------------------------------------
	getSprNode(resName) {
		const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
		const node = new cc.Node();
		node.addComponent(cc.Sprite).spriteFrame = sf;
		return node;
	},


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

	async getSprNodeByUrl(url) {
		const node = new cc.Node();
		const spr = node.addComponent(cc.Sprite);
		spr.spriteFrame=await this.getSpriteFrimeByUrl(url);
		return node;
	},

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

	// getSprNodeByUrl(url, cb) {
	// 	const node = new cc.Node();
	// 	const spr = node.addComponent(cc.Sprite);
	// 	this.getSpriteFrimeByUrl(url, (sf) => {
	// 		spr.spriteFrame = sf;
	// 		if (cb) {
	// 			cb(node);
	// 		}
	// 	})
	// },

	playAudioByUrl(audio_url, cb = null) {
		if (!audio_url) {
			cb && cb();
			return;
		}
		cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
			const audioId = cc.audioEngine.play(audioClip, false, 0.8);
			cc.audioEngine.setFinishCallback(audioId, () => {
				cb && cb();
			});
		});
	},

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

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

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

		if (isCanFinish) {
			this.isGameEnd = true;
			playDragonBoneAnimation(this.coolcat, 'finish', -1);
			this.playAudioByUrl(this.data.finishAudio,()=>{
				playDragonBoneAnimation(this.coolcat, 'normal', -1);
				this.showRestartBtn();
				onHomeworkFinish();
			});
			this.submitBtnClick();
		}
	},

	// gameEnd() {
	// 	if (window && window.courseware) {
	// 		window.courseware.gameEnd();
	// 	}
	// },

	sendAnswer(answer = "", isRight = false) {
		console.log(this._aiexerciseid, answer, isRight, this._startTime);

		if (window && window.courseware) {
			window.courseware.sendAnswer(this._aiexerciseid, answer, isRight, this._startTime);
		}
	},

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

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



	bindSubImgHit(sprNode, data) {
		sprNode.on(cc.Node.EventType.TOUCH_START, (e) => {

			e.stopPropagation();

			console.log('data: ' , data);
			console.log('this.curPaintColorCode: ' + this.curPaintColorCode);
			// if (data?.colorData?.code != this.curPaintColorCode) {
			// 	this.playAudioByName('a_o');
			// 	return;
			// }


			sprNode.color = this.curPaintColor;
	
			data.isEnd = true;
			data.isWrong = data?.colorData?.code != this.curPaintColorCode;

			this.playAudioByName('painted');

		

			if (!data.wrongIcon) {
				const wrongIcon = getSprNode('X');
				data.wrongIcon = wrongIcon;
				sprNode.addChild(wrongIcon);
				const touchPos = e.getLocation();

				const wSize = wrongIcon.getBoundingBoxToWorld();
				wrongIcon.scale = 25 / wSize.width;
				console.log('touchPos: ' , touchPos);

				const localPos = sprNode.convertToNodeSpaceAR(touchPos);
				wrongIcon.x = localPos.x;
				wrongIcon.y = localPos.y;
				data.wrongIcon.active = false;
			}

			if (this.isFillEnd) {
				if (data.isWrong) {
					data.wrongIcon.active = true;
				} else {
					data.wrongIcon.active = false;
				}
			}

			if (this.isFillEnd && data.isWrong) {
				this.playAudioByName('a_o');
			} else {
				this.checkGameEnd(!data.isWrong);
			}
		
		});

		sprNode._hitTest = this._hitTest.bind(this);
	},
	// ------------------------------------------

	bindTeethHit(tooth) {

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

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

			e.stopPropagation();

			if (this._can_tap != true)
				return;

			if (sprite.painted == true)
				return;

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

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

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

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

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

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

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

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

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

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

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