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


	// 生命周期 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].audioUrl) {
					this._audioResList.push({ url: wordArr[i].audioUrl });
				}

			}
		}

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

			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.playAni('begin', 0);

		const begin = () => {
			this.playAni('normal', 0);

			this._cantouch = true;
			
			this.begin();
		}
		console.log(this.data.guideAudioUrl1);
		//如果有引导音频，则播放完引导音频再开始
		if (this.data.guideAudioUrl1) {
			//播放引导音频1
			this.playAudioByUrl(this.data.guideAudioUrl1, () => {
				begin();
			});
		}
		else {
			begin();
		}

		this.addDefaultMusic();

	},

	/**
	 * 依次显示
	 * @param {*} index 
	 */
	begin(index = 0){

		let wordArr = this.data.exercises.wordArr;

		if(index > wordArr.length - 1){
			//播放单词音频
			this.playTextAutio();

			return;
		}

		let word = this.data.exercises.wordArr[index];

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

		//有空格，取2 * index节点值
		let wordNode = textNode.wordNodeArr[2 * index];

		//播放音频
		this.playAudioByUrl(word.audioUrl, ()=>{

			this.begin(index + 1);
		})

		//显示文本动画
		this.textTwinkle(wordNode);

	},

	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;
			picNode.scale = pic.width / picNode.width;
			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(initial, 700, true);
			label.isInitial = true;
			wordNodeArr.push(label);

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

		}


		textNode.wordNodeArr = wordNodeArr;

		this.resetTextPosition(textNode, 40);

		this._curIndex = 0;

		this.initText2();
	},

	initText2(){
		let textNode = cc.find("Canvas/content/bg_green/text2/content");
		textNode.initScale = textNode.scale;
		let wordNodeArr = [];

		let wordArr = this.data.exercises.word2Arr;

		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(initial, 80, true);
			label.isInitial = true;
			wordNodeArr.push(label);

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

		}


		textNode.wordNodeArr = wordNodeArr;

		this.resetTextPosition(textNode, 15);

		this._curIndex = 0;
	},


	initBtn() {


	},

	getWord(wordVal, size, isInitial) {

		size /= 2;
		let color = new cc.color();
		color.fromHEX('#000000');
		const labelNode = new cc.Node();
		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();

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


	playAni(name, times = 1) {

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

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

		const state = dragonDisplay.playAnimation(name, times);
		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 {*} callback 
	 */
	playTextAutio(callback = null) {

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

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

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

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

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

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

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

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

	/**
	 * 重新设置文字位置
	 */
	resetTextPosition(textNode, space = 40) {

		let wordNodeArr = textNode.wordNodeArr;

		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._shown) {
			return;
		}

		this._shown = true;

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

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

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

			state.stop();

			this.playAni('normal', 0);

			this.showPhotoBtn();
		});



	},

	_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(audioId, arr) {

		if (this._stopAni) {
			return;
		}

		this._stopAni = false;

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

		let len = arr.length;

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

			let time = arr[i].time;

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

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

			if (time < currentTime) {

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

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

				break;
			}

		}

		requestAnimationFrame(() => {

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

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

		if (this._playText) {
			return;
		}

		this._playText = true;

		this._cantouch = false;

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

		let wordNodeArr = textNode.wordNodeArr;

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

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

	},

	/**
	 * 文本内容动画
	 * @param {*} node 
	 * @param {*} callback 
	 */
	textTwinkle(node, callback = null){
		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();
	},


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

		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;

					this._curIndex++;
					
					this.showEnd();
				})
				.start();
		};

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

		twinkle(textNode);
	},



	photoBtn: null,
	initPhotoBtn() {
		console.log("init photoBtn");

		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;console.log(this.photoBtn);
	},

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

		if (window && window.courseware && window.courseware.closeRecognitionCamera) {
			window.courseware.closeRecognitionCamera();
		} else {
			console.log('没有closeRecognitionCamera！！！');
		}
	},

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

			});
		}
	},

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

});
