// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
// cc.audioEngine = require('../components/karaoke/scripts/audioEngineEx.js')

import { getSprNode, getSprNodeByUrl, playAudioByUrl, setSprNodeMaxLen } from "./util";

cc.Class({
	extends: cc.Component,

	properties: {
		baseWidth: {
			default: 1280,
			type: cc.Integer
		},
		baseHeight: {
			default: 720,
			type: cc.Integer
		},
		lrcPrefab: {
			default: null,
			type: cc.Prefab
		}
		// foo: {
		//     // ATTRIBUTES:
		//     default: null,        // The default value will be used only when the component attaching
		//                           // to a node for the first time
		//     type: cc.SpriteFrame, // optional, default is typeof default
		//     serializable: true,   // optional, default is true
		// },
		// bar: {
		//     get () {
		//         return this._bar;
		//     },
		//     set (value) {
		//         this._bar = value;
		//     }
		// },
	},

	// LIFE-CYCLE CALLBACKS:

	// baseWidth: 1280;
	// baseHeight: 720;

	onLoad() {
		cc.debug.setDisplayStats(false);
		this.initSceneData();
		this.initSize();
		window['ss'] = this;
	},

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

	_designSize: null,
	_frameSize: null,
	_mapScaleMin: null,
	_mapScaleMax: null,
	_cocosScale: null,
	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;

		console.log('_cocosScale: ', this._cocosScale);
	},

	start() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			// console.log('has window');
			getData = window.courseware.getData;
		}
		getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			// cc.director.emit('GAME_DATA_FETCHED', {...this.data})
			this.preloadItem()
		})
	},


	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},

	getData(func) {
		func(this.getDefaultData());
	},

	getDefaultData() {

		const data = {"songArr":[
			
			{"lrcData":{
				"audio_url":"http://staging-teach.cdn.ireadabc.com/2a25aaff4b6c84b859b4d77f944de57a.mp3",
				"fontSize":24,
				"lineHeight":32,
				"lyrics":[
					{"time":11.09,"data":"yi shan yi shan liang jing jing","newLine":true},
					{"time":14.9,"data":"1111满天都是小星星","newLine":true},
					{"time":19.31,"data":"挂在天上放光明","newLine":true},
					{"time":23.62,"data":"好像许多小眼睛","newLine":true},
					{"time":27.93,"data":"一闪一闪亮晶晶","newLine":true},
					{"time":32.32,"data":"满天都是小星星","newLine":true},{"time":41.1,"data":"一闪一闪亮晶晶","newLine":true},{"time":45.45,"data":"满天都是小星星","newLine":true},{"time":49.74,"data":"挂在天上放光明","newLine":true},{"time":54.16,"data":"好像许多小眼睛","newLine":true},{"time":58.39,"data":"一闪一闪亮晶晶","newLine":true},{"time":62.9,"data":"满天都是小星星","newLine":true},{"time":76.36,"data":"一闪一闪亮晶晶","newLine":true},{"time":80.28,"data":"满天都是小星星","newLine":true},{"time":84.65,"data":"挂在天上放光明","newLine":true},{"time":88.92,"data":"好像许多小眼睛","newLine":true},{"time":93.41,"data":"一闪一闪亮晶晶","newLine":true},
					{"time":97.72,"data":"满天都是小星星","newLine":true}
				]},"pic_url":"http://staging-teach.cdn.ireadabc.com/f6f4bbef497409fef3c8f1d375893829.png","accompany_audio_url":"http://staging-teach.cdn.ireadabc.com/86614bd904f63ab02fc69304e99618c6.mp3"
			},
			{"lrcData":{
				"audio_url":"http://staging-teach.cdn.ireadabc.com/3fa65d5f667a2ef9059d3dfc5df74a4d.mp3",
				"fontSize":24,
				"lineHeight":32,
				"lyrics":[
					{"time":4.81026,"data":"AAA","newLine":true},
					{"time":8.63464,"data":"aaaaa bbbb ccc ddddeedddddddgg","newLine":true},
					{"time":10.489051,"data":"eeee fffff gg hhh","newLine":false}
				]},
				"pic_url":"http://staging-teach.cdn.ireadabc.com/c8abf7383d65bcbdba8f390785cece60.png","accompany_audio_url":"http://staging-teach.cdn.ireadabc.com/22e9facddfbf087ecdf2b60dba6019ef.mp3"
			}
			],
			"title":"Let's play",
			"title_audio_url":"http://staging-teach.cdn.ireadabc.com/cd8daa8b4d8ff707b3a3680e80bc4761.mp3"
		}

		return data;
	},

	preload() {

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

			// typeof
			this.loadEnd();
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}
		});
	},

	addPreloadImage() {

		if (this.data.songArr) {
			for (let i=0; i<this.data.songArr.length; i++) {
				const data = this.data.songArr[i];
				this._imageResList.push({ url: data.pic_url || '' });
			}
		}
	},

	addPreloadAudio() {

		if (this.data.songArr) {
			for (let i=0; i<this.data.songArr.length; i++) {
				const data = this.data.songArr[i];
				this._audioResList.push({ url: data.accompany_audio_url || '' });
				this._audioResList.push({ url: (data.lrcData && data.lrcData.audio_url) || ''});
			}
		}
		
		this._audioResList.push({ url: this.data.title_audio_url || '' });

	},

	addPreloadAnima() {
		// if (!this.data.hotZoneItemArr) {
		// 	return;
		// }

		// this.data.hotZoneItemArr.forEach((item) => {
		// 	if (item.skeJsonData) {
		// 		this._animaResList.push({ url: item.skeJsonData.url || '' });
		// 		this._animaResList.push({ url: item.texJsonData.url || ''});
		// 		this._animaResList.push({ url: item.texPngData.url || ''});
		// 	}
		// })

	},

	loadEnd() {
		
		cc.director.emit('GAME_RESOURCE_LOADED');
		this.initData();
		this.initView();
		this.initAudio();
	},


	canvas: null,
	isMusicType: null,
	isSingType: null,
	initData() {
		console.log('this.data: ', this.data);
		this.canvas = cc.find('Canvas');
	},

	initView() {

		this.initTitle();
		this.initItem();
		this.initSongControler();
	},

	audioBtn: null,
	audioEnter: null,
	initAudio() {

		const audioNode = cc.find('Canvas/res/audio');

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


		this.audioBtn = getAudioByResName('btn');
		this.audioEnter = getAudioByResName('enter');

		cc.audioEngine.playEffect(this.audioEnter.clip, false, 0.5)
	},

	initTitle() {
		const title = getSprNode('bg_title');
		title.scale = this._mapScaleMin;

		title.parent = this.canvas;
		title.x = -this.canvas.width / 2 + title.width / 2 * title.scale;
		title.y = this.canvas.height / 2 - title.height / 2 * title.scale;

		title.addComponent(cc.Button)
		title.on('click', () => {
			if (this.data.title_audio_url) {
				playAudioByUrl(this.data.title_audio_url);
			}
		})

		const labelNode = new cc.Node();
		labelNode.parent = title;
		const label = labelNode.addComponent(cc.RichText);
		const size = 50
		label.font = cc.find('Canvas/res/font/aharoni').getComponent(cc.Label).font;
		label.string = `<outline color=#d55b75 width=2><size=${size}><color=#ffffff>${this.data.title || "let\'s chant" }</color></size></outline>`
		// label.string = `<size=${size}><color=#751e00>${this.curGroup.title }</color></size>`
		label.lineHeight = size;
		label.horizontalAlign = cc.macro.TextAlignment.LEFT
		labelNode.anchorX = 0;
		labelNode.anchorY = 1
		labelNode.x = -title.width / 2 + 100;

		const maxLen = 310;
		if (labelNode.width > maxLen) {
			labelNode.scale = maxLen / labelNode.width;
		}

		labelNode.y = labelNode.height / 2 * labelNode.scale + 12;

	},

	musicBtn: null,
	singBtn: null,
	initSongControler() {
		if (!this.itemArr[0]) {
			return
		}
		const songBgSize = getSprNode('song_bg');
		const disH = -songBgSize.height * this._mapScaleMin - 40 * this._mapScaleMin;
		const disW = 40 * this._mapScaleMin;	
		
		songBgSize.scale = this._mapScaleMin;
		let pxo, pyo
		let baseX = pxo = -songBgSize.width * this._mapScaleMin / 2 - disW / 2;
		let baseY = pyo = 80 * this._mapScaleMin;
		pxo += (this.itemArr[0].width * this._mapScaleMin + disW) 
		// pxo = baseX;
		// pyo += disH;


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

		let px = pxo + 240 * this._mapScaleMin;
		let py = pyo + 170 * this._mapScaleMin;
		const singBtn = this.addSingBtn(parent, px, py);

		px = singBtn.x - 100 * this._mapScaleMin;
		py = singBtn.y;
		const musicBtn = this.addMusicBtn(parent, px, py);

		this.musicBtn = musicBtn;
		this.singBtn = singBtn;
		this.setPlayAudioType(true)
	},

	addSingBtn(parent, px, py) {
		const singBtn = getSprNode('btn_singoff')
		singBtn.scale = this._mapScaleMin;
		singBtn.parent = parent;
		singBtn.addComponent(cc.Button);
		singBtn.on('click', () => {
			this.setPlayAudioType(false);
			cc.audioEngine.playEffect(this.audioBtn.clip, false, 0.5)
		})

		const singBtnOn = getSprNode('btn_singon');
		singBtnOn.parent = parent;
		singBtnOn.active = false;
		singBtn.btnOn = singBtnOn
		singBtnOn.addComponent(cc.Button);

		singBtn.x = singBtnOn.x = px;
		singBtn.y = singBtnOn.y = py;

		return singBtn;
	},

	addMusicBtn(parent, px, py) {

		const musicBtn = getSprNode('btn_musicoff')
		musicBtn.scale = this._mapScaleMin;
		musicBtn.parent = parent;
		musicBtn.addComponent(cc.Button);
		musicBtn.on('click', () => {
			this.setPlayAudioType(true);
			cc.audioEngine.playEffect(this.audioBtn.clip, false, 0.5)
		})

		const musicBtnOn = getSprNode('btn_musicon');
		musicBtnOn.parent = parent;
		musicBtnOn.active = false;
		musicBtn.btnOn = musicBtnOn
		musicBtnOn.addComponent(cc.Button);

		musicBtn.x = musicBtnOn.x = px;
		musicBtn.y = musicBtnOn.y = py;

		// const musicBtn = getSprNode('btn_musicoff')
		// musicBtn.scale = this._mapScaleMin;
		return musicBtn;
	},

	setPlayAudioType(isMusic) {
		if (isMusic) {

			this.isMusicType = true;
			this.isSingType = false;
	
			this.musicBtn.btnOn.active = true;
			this.singBtn.btnOn.active = false;
			this.setItemsPlayMode('mode3');
			
		} else {
			this.isMusicType = false;
			this.isSingType = true;

			this.musicBtn.btnOn.active = false;
			this.singBtn.btnOn.active = true;
			this.setItemsPlayMode('mode1');
		}

	},

	setItemsPlayMode(mode)  {
		const arr = this.itemArr;
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].lrcScript) {
				arr[i].lrcScript.setCurrentMode(mode);
			}
		}
	},


	itemArr: null,
	isSkipItem(item) {
		return !item.accompany_audio_url 
		|| !item.pic_url 
		|| !item.lrcData 
		|| !item.lrcData.audio_url
	},

	initItem() {

		this.itemArr = [];
		const songBgSize = getSprNode('song_bg');

		const arr = this.data.songArr;
		const disW = 40 * this._mapScaleMin;
		const disH = -songBgSize.height * this._mapScaleMin - 40 * this._mapScaleMin;

		let px, py
		let baseX = px = -songBgSize.width * this._mapScaleMin / 2 - disW / 2;
		let baseY = py = 80 * this._mapScaleMin;



		
		for (let i = 0; i < arr.length; i++) {
			console.log(`arr[${i}]`, arr[i]);
			if (this.isSkipItem(arr[i])) {
				continue
			}
			const item = this.setOneSongItem(arr[i]);
			item.x = px;
			item.y = py;
			

			px += (item.width * this._mapScaleMin + disW) 
			if (i == 1) {
				px = baseX;
				py += disH;
			}

			if (arr[i].pic_url) {
				this.addItemImg(item, arr[i]);
				this.addItemScript(item, arr[i]);
				this.addItemListener(item);
				this.addItemBorder(item);
			}
			

			this.itemArr.push(item);
		}
	},

	addItemBorder(item) {

		const border = getSprNode('bg_dibian');
		border.active = false;
		border.parent = item.parent;
		border.scale = item.scale;
		border.x = item.x;
		border.y = item.y;

		item.borderBg = border;
		
	},
	
	addItemImg(item, data) {
		if (!data.pic_url) {
			return
		}

		const imgLen = 170;
		getSprNodeByUrl(data.pic_url, (spr) => {
			spr.node.parent = item;

			const tmpNode = new cc.Node();
			spr.node.name = 'ItemImage'
			const g = tmpNode.addComponent(cc.Graphics);
			g.fillColor = cc.Color.RED;
			g.fillRect(0, 0, imgLen, imgLen);

			// tmpNode.parent = item;

			tmpNode.x = spr.node.x = -item.width / 2 + 10 + imgLen / 2;
			tmpNode.y = spr.node.y = -imgLen / 2 + imgLen / 2;
			setSprNodeMaxLen(spr.node, imgLen, imgLen);
		})
	},

	addItemScript(item, data) {
		if (!data.pic_url) {
			return
		}
		const lrcNode = cc.instantiate(this.lrcPrefab)
		lrcNode.parent = item; //lrcPrefab
		const lrcScript = lrcNode.getComponent('adapter')
		lrcScript.setData(data, this._mapScaleMin);
		item.lrcScript = lrcScript;

		// lrcScript.lrc.node.width = 
		// lrcScript.lrc.node.height
		console.log(111,item);
		// lrcScript.lrc.node.name = 'aaaaa'
		lrcScript.lrc.node.height = item.height - 50;
		// lrcScript.lrc.node.width = item.width - 30;
		console.log('aaaa y', lrcScript.lrc.node.y);
		lrcScript.stopSong();
		// console.log(333444);
        // lrcScript.lrc.richText.node.width = lrcScript.lrc.richText.node.width - 50;
		

		lrcNode.y = -lrcScript.lrc.node.height / 2 * lrcScript.lrc.node.scale + 90 * this._mapScaleMin;
	},

	addItemListener(item) {

		item.addComponent(cc.Button);
		item.on('click', () => {

			console.log(' in click ', item);
			this.stopAllSong(item.lrcScript);
			item.lrcScript.playSong();
			item.borderBg.active = true;
		})
	},

	stopAllSong(script) {
		const arr = this.itemArr;
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].lrcScript && arr[i].lrcScript != script) {
				arr[i].lrcScript.stopSong();
				arr[i].borderBg.active = false;
			}
		}
	},

	setOneSongItem(data) {
		const parent = cc.find('Canvas');

		const songBg = getSprNode('song_bg');
		songBg.scale = this._mapScaleMin;
		songBg.parent = parent;
		songBg.zIndex = 5;

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

		return songBg;
	},


	initMusic() {
		cc.assetManager.loadRemote(this.data.bg_audio_url, (err, clip) => {
			cc.audioEngine.setMusicVolume(0.3);
			const audioID = cc.audioEngine.playMusic(clip, true);
		});
	},

	_cocosScale: null,
	initBg() {
		// const frameSize = cc.view.getFrameSize();

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

		// const bgNode = cc.find('Canvas/bg');
		// // const sx = cc.winSize.width / bgNode.width;
		// // const sy = cc.winSize.height / bgNode.height;
		//  sx = frameSize.width / bgNode.width;
		//  sy = frameSize.height / bgNode.height;
		// bgNode.scale = Math.max(sx, sy) * s;
		// bgNode.anchorX = 1;
		// bgNode.anchorY = 0;
		// bgNode.x = frameSize.width / 2 * s;
		// bgNode.y = -frameSize.height / 2 * s;


		// const bg = cc.find('Canvas/bg');
		// const rectNode = new cc.Node();
		// rectNode.x = -bg.x;
		// rectNode.y = -bg.y;
		// rectNode.scaleX = bg.scaleX;
		// rectNode.scaleY = bg.scaleY;
		// bg.addChild(rectNode);
		// const ctx = rectNode.addComponent(cc.Graphics);
		// ctx.fillColor = this.data.bgColor || '#f9bd03';
		// ctx.fillRect(-bg.width / 2 , -bg.height / 2, bg.width, bg.height);
		// ctx.fill();

	},


	initHotZone() {
		this.initHotZoneBg();

	},

	hotZoneBg: null,
	initHotZoneBg() {
		this.hotZoneBg = new cc.Node();
		this.hotZoneBg.name = 'hotZoneBg';
		this.hotZoneBg.parent = cc.find('Canvas');
		this.hotZoneBg.zIndex = 4;


		const canvas = cc.find('Canvas/Main Camera');
		// console.log('canvas: ', canvas);

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

		cc.loader.load({url: this.data.bgItem.url}, (err, img) => {

			this.addMask(this.hotZoneBg);

			this.hotZoneBg.width = img.width;
			this.hotZoneBg.height = img.height;



			const box = this.hotZoneBg.getBoundingBox();


			const tmpS = 640 / 720;
			let subNum = 720 - 640;
			const frameSize = cc.view.getFrameSize();
			const winSize = cc.winSize;

			console.log('this.hotZoneBg.box: ', this.hotZoneBg.getBoundingBox());
			console.log('let visiSize=cc.director.getVisibleSize();: ', cc.view.getVisibleSize());
			console.log('lframeSize: ', frameSize);

			let sx = frameSize.width / this._designSize.width;
			let sy = frameSize.height / this._designSize.height;
			const mapS = Math.min(sx, sy);
			// const sy = canvas.height * tmpS / box.height;


			const bgBottom = cc.find('Canvas/bgBottom');
			bgBottom.scale = mapS * this._cocosScale;
			// subNum = bgBottom.height;

			 sx = frameSize.width * this._cocosScale / img.width;
			 sy = (frameSize.height * this._cocosScale - subNum * mapS * this._cocosScale) / img.height;


			const sprNode = new cc.Node();
			sprNode.name = 'bgItemSpr'
			var sf = new cc.SpriteFrame(img);
			// const spr = this.hotZoneBg.addComponent(cc.Sprite);
			const spr = sprNode.addComponent(cc.Sprite);
			spr.spriteFrame = sf
			sprNode.width = this.hotZoneBg.width;
			sprNode.height = this.hotZoneBg.height;
			sprNode.parent = this.hotZoneBg;
			window['bg'] =sprNode 
			this.hotZoneBg.scale = Math.min(sx, sy);
			
			// this.hotZoneBg.y = -frameSize.height / 2 * this._cocosScale + this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY + (subNum * mapS * this._cocosScale);
			this.hotZoneBg.y = frameSize.height / 2 * this._cocosScale - this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY ;
			console.log('this.hotZoneBg.y', this.hotZoneBg.y);

			// this.hotZoneBg.opacity = 20;

			const bgWhite = cc.find('Canvas/bgWhite');
			bgWhite.y = this.hotZoneBg.y;

			bgWhite.scaleX = this.hotZoneBg.width * this.hotZoneBg.scaleX / bgWhite.width;
			bgWhite.scaleY = this.hotZoneBg.height * this.hotZoneBg.scaleY / bgWhite.height;


			const canvas = cc.find('Canvas');
			const shadowNode = new cc.Node();
			shadowNode.y = bgWhite.y;
			shadowNode.scaleX = bgWhite.scaleX;
			shadowNode.scaleY = bgWhite.scaleY;
			canvas.addChild(shadowNode);
			const ctx = shadowNode.addComponent(cc.Graphics);
			ctx.fillColor = cc.Color.BLACK.setA(30);
			// ctx.fillRect(5, 5, this.hotZoneBg.width*this.hotZoneBg.scaleX, this.hotZoneBg.height * this.hotZoneBg.scaleY);
			ctx.fillRect(-bgWhite.width / 2 + 8 / bgWhite.scaleX * this.hotZoneBg.scale, -bgWhite.height / 2 - 8 / bgWhite.scaleX * this.hotZoneBg.scale, bgWhite.width, bgWhite.height);
			ctx.fill();

			shadowNode.zIndex = 1;
			bgWhite.zIndex = 2;

			bgBottom.y = -frameSize.height / 2 * this._cocosScale - 15 * bgBottom.scaleY;
			// this.data.bgItem.isShowDebugLine = true;
			this.data.hotZoneItemArr.forEach((item) => {
				if (item.gIdx == '0' || item.gIdx == '5') {
					this.setOneAnima(item);
				} else if (item.gIdx == '1') {
					this.setOnePic(item);
				} else if (item.gIdx == '2' || item.gIdx == '3' || item.gIdx == '4') {
					// this.setOneRect(item)
				}
			});

		});

	},
	setOneRect(data) {
		const rate =  (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;
		const rectNode = new cc.Node();
		rectNode.name = 'rect' + data.index;
		this.hotZoneBg.addChild(rectNode);
		console.log(1111, data.rect)

		const ctx = rectNode.addComponent(cc.Graphics);
		// 红色矩形
		ctx.lineWidth = 4;
		ctx.strokeColor = cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / this.hotZoneBg.scaleY;
		rectNode.width = data.rect.width * scale;
		rectNode.height = data.rect.height * scale;
		rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;
		const {x, y, width, height} = rectNode;
		rectNode.anchorX = rectNode.anchorY = 0;

		console.log(2222, {x,y,width, height})
		if (this.data.bgItem.isShowDebugLine) {
			ctx.rect(0, 0, rectNode.width, rectNode.height);
		}
		ctx.stroke();
		ctx.fill();
		window.bbbbb = rectNode
	},
	addMask(node) {
		const mask = node.addComponent(cc.Mask);
		mask.type = cc.Mask.Type.RECT;
	},

	initBottomPart() {

		const bgBottom = cc.find('Canvas/bgBottom');
		const script = bgBottom.getComponent('bgBottom');
		const picArr = [];
		this.data.hotZoneItemArr.forEach((item) => {
			if (item.gIdx == '0') {
				picArr.push(item);
			}
		});
		script.setItemData(picArr);
	},


	setOneAnima(data) {


		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

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


		const ctx = rectNode.addComponent(cc.Graphics);
		// 红色矩形
		ctx.lineWidth = 4;
		ctx.strokeColor = cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / this.hotZoneBg.scaleY;

		rectNode.width = data.rect.width * scale;
		rectNode.height = data.rect.height * scale;
		rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;

		rectNode.anchorX = rectNode.anchorY = 0;


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



		const animaNode = new cc.Node();
		animaNode.name = 'anima_' + data.index;
		this.hotZoneBg.addChild(animaNode);

		// rectNode.addChild(animaNode);
		// animaNode.x = rectNode.width / 2;
		// animaNode.y = rectNode.height / 2;


		if (data.audio_url) {
			cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
				animaNode.audioClip = audioClip;
			});
		}


		const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);
		if (!data.texPngData) {
			return
		}
		const image = data.texPngData.url//"http://staging-teach.cdn.ireadabc.com/5a0c5af3e952acd0ac83a6e5c6f03ff1.png";
		const ske = data.skeJsonData.url//"http://staging-teach.cdn.ireadabc.com/bd825dcceea298d1146be8067ae3d17f.json";
		const atlas = data.texJsonData.url//"http://staging-teach.cdn.ireadabc.com/246f8991b729fa3e5a7f4802de828efa.json";
		cc.loader.load(image, (error, texture) => {

			cc.loader.load({url: atlas, type: 'txt'}, (error, atlasJson) => {

				cc.loader.load({url: ske, type: 'txt'}, (error, dragonBonesJson) => {

					const atlas = new dragonBones.DragonBonesAtlasAsset();
					atlas.atlasJson = atlasJson;
					atlas.texture = texture;

					const asset = new dragonBones.DragonBonesAsset();
					asset.dragonBonesJson = dragonBonesJson;

					dragonDisplay.dragonAtlasAsset = atlas;
					dragonDisplay.dragonAsset = asset;

					let json = JSON.parse(asset.dragonBonesJson);
					let armatures = json["armature"];
					console.log('armatures: ', armatures);
					let armatureNames = [];
					for (let i = 0; i < armatures.length; i++) {
						armatureNames.push(armatures[i].name);
					}
					// console.log('armatureNames: ', armatureNames);
					if (armatureNames.length > 0) {
						let defaultArmatureName = armatureNames[0];
						dragonDisplay.armatureName = defaultArmatureName;
						// let animationNames = dragonDisplay.getAnimationNames(defaultArmatureName);
						let defaultArmature = armatures[0];
						let animations = defaultArmature.animation;
						let animationNames = [];
						for (let i = 0; i < animations.length; i++) {
							animationNames.push(animations[i].name);
						}

						rectNode.addComponent(cc.Button);
						rectNode.on('click', () => {
							if (rectNode.isClicked) {
								// return;
							}
							rectNode.isClicked = true;
							console.log('clicked');

							if (animaNode.audioClip) {
								cc.audioEngine.stopAllEffects();
								cc.director.emit('STOP_ALL_AUDIO')
								cc.audioEngine.playEffect(animaNode.audioClip, false, 0.8);
							}

							if (animationNames.length > 0) {
								dragonDisplay.playAnimation(animationNames[0], 1);
							}
						});
					}

				});
			});
		});

	},


	setOnePic(data) {
		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const picNode = new cc.Node();
		picNode.name= 'pic' + data.index;
		picNode.data = data;
		this.hotZoneBg.addChild(picNode);

		cc.loader.load({url: data.pic_url}, (err, img) => {

			const spr = picNode.addComponent(cc.Sprite);
			spr.spriteFrame = new cc.SpriteFrame(img)

			const scale = rate / this.hotZoneBg.scaleY;

			picNode.width = data.rect.width * scale;
			picNode.height = data.rect.height * scale;
			picNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
			picNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;

			picNode.anchorX = picNode.anchorY = 0;

			if (data.audio_url) {
				this.addPicAudio(picNode);
			}

		});

	},

	addPicAudio(picNode) {
		const data = picNode.data;
		
		cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
			picNode.audioClip = audioClip;
		});

		picNode.addComponent(cc.Button);
		picNode.on('click', () => {
				if (picNode.audioClip) {
					cc.audioEngine.stopAllEffects();
					cc.audioEngine.playEffect(picNode.audioClip, false, 0.8);
				}
		});
	},


	// update (dt) {},
});
