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

// import { getSprNode } from "./util";
import { getSprNode, playAudioByUrl, getScaleRateBy2Node, localPosTolocalPos, randomSortByArr, loadDragonBones, playAudio, showTrebleFirework, RandomInt} from "./util";

cc.Class({
	extends: cc.Component,

	properties: {
		baseWidth: {
			default: 1280,
			type: cc.Integer
		},
		baseHeight: {
			default: 720,
			type: cc.Integer
		}
	},

	onLoad() {
		cc.debug.setDisplayStats(false);
		this.initSceneData();
		this.initSize();
	},

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


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

		this.canvas = cc.find('Canvas');


		// cc.log('cc.Canvas: ', cc.Canvas);
	},

	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.preloadItem()
		})
	},

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

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

	getDefaultData() {
		const dataJson = '{"groupArr":[{"ques":"","optionArr":[{"type":"text","isRight":"1","text":"aaaaa","audio_url":"http://staging-teach.cdn.ireadabc.com/5285e1e88a26a08783757e9c43a8653f.mp3"},{"type":"text","isRight":"0","text":"bbbbb","audio_url":"http://staging-teach.cdn.ireadabc.com/440cf9d57752b30691d90ed565e8c924.mp3"},{"type":"pic","isRight":"1","audio_url":"http://staging-teach.cdn.ireadabc.com/66878465ec50d162bd60fcdaa641933b.mp3","pic_url":"http://staging-teach.cdn.ireadabc.com/7709a0ddfde321cb70fc3099da32c35b.png"}],"audio_url":"http://staging-teach.cdn.ireadabc.com/85cff126986f5cc11b05e95181da5869.mp3"},{"ques":"","optionArr":[{"type":"text","isRight":"1","text":"444","audio_url":"http://staging-teach.cdn.ireadabc.com/a5fa20e0c6024421b0d9a7007c303503.mp3"},{"type":"pic","isRight":"0","pic_url":"http://staging-teach.cdn.ireadabc.com/1c9a510039065355e8f2402227cf8ef0.png"},{"type":"text","isRight":"0","text":"!!!!!"}],"audio_url":"http://staging-teach.cdn.ireadabc.com/a5fa20e0c6024421b0d9a7007c303503.mp3"}],"pic_url_2":"http://staging-teach.cdn.ireadabc.com/f6f4bbef497409fef3c8f1d375893829.png"}';
		const data1 = JSON.parse(dataJson);
		return data1;

	},

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

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

	addPreloadImage() {
	
		const groupArr = this.data.groupArr;
		if (groupArr) {
			for (let i=0; i<groupArr.length; i++) {

				const optionArr = groupArr[i].optionArr;
				for (let j=0; j<optionArr.length; j++) {
					this._imageResList.push({ url: optionArr[j].pic_url || ''});
				}

			}
		}
	},

	addPreloadAudio() {

		const groupArr = this.data.groupArr;
		if (groupArr) {
			for (let i=0; i<groupArr.length; i++) {
				
				const optionArr = groupArr[i].optionArr;
				for (let j=0; j<optionArr.length; j++) {
					this._audioResList.push({ url: optionArr[j].audio_url || ''});
				}

				this._audioResList.push({ url: groupArr[i].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() {
		this.initView();
		this.initData();
		// this.initMusic();
	},

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


	initView() {

		this.initHole();
		this.initStar();
		this.initBtn();
		this.showSoundBtn();
	},

	penguinPool: null,
	groupIndex: null,
	initData() {

		this.penguinPool = [];
		this.groupIndex = 0;

		this.initCurGroup();
		this.initAudioEffect();
	},

	appearClip: null,
	starClip: null,
	rightClip: null,
	wrongClip: null,
	bigStarClip: null,
	btnClip: null,
	endClip: null,
	initAudioEffect() {
		this.appearClip = cc.find('Canvas/res/audio/appear').getComponent(cc.AudioSource).clip;
		this.starClip = cc.find('Canvas/res/audio/star').getComponent(cc.AudioSource).clip;
		this.rightClip = cc.find('Canvas/res/audio/right').getComponent(cc.AudioSource).clip;
		this.wrongClip = cc.find('Canvas/res/audio/wrong').getComponent(cc.AudioSource).clip;
		this.bigStarClip = cc.find('Canvas/res/audio/big_star').getComponent(cc.AudioSource).clip;
		this.btnClip = cc.find('Canvas/res/audio/btn').getComponent(cc.AudioSource).clip;
		this.endClip = cc.find('Canvas/res/audio/end').getComponent(cc.AudioSource).clip;

	},


	curGroup: null,
	initCurGroup() {

		this.curGroup = JSON.parse( JSON.stringify(this.data.groupArr[this.groupIndex]) );
	},


	holeArr: null,
	initHole() {

		this.holeArr = [];
		
		const edge = 100 * this._mapScaleMin;
		const itemW = 260 * this._mapScaleMin;
		const disW = (this.canvas.width - edge * 2 - itemW * 4) / 3;
		const baseX = -this.canvas.width / 2 + edge + itemW / 2;

		const disH = 200 * this._mapScaleMin;
		const baseY = -this.canvas.height / 2 + 260 * this._mapScaleMin;
		let j = 0;

		for (let i = 0; i < 8; i++) {
			const hole = this.getHole();
			this.canvas.addChild(hole);
			this.holeArr.push(hole);

			hole.x = baseX + i % 4 * (itemW + disW);
			hole.y = baseY - j * disH;

			if (i == 3) {
				j ++;
			}
		}
	},

	bigStarArr: null,
	initStar() {
		const gArr = this.data.groupArr;
		if (gArr.length <= 1) {
			return;
		}

		this.bigStarArr = [];

		let baseX = this.canvas.width / 2 - 50 * this._mapScaleMin;
		let baseY = this.canvas.height / 2 - 80 * this._mapScaleMin;
		let disH = 80 * this._mapScaleMin;
		for (let i=0; i<gArr.length; i++) {
			const starBg = getSprNode('star_bg');
			this.canvas.addChild(starBg, 2);
			starBg.x = baseX;
			starBg.y = baseY - i * disH;

			const starTop = getSprNode('star');
			starBg.addChild(starTop);
			starTop.active = false;
			starBg.star = starTop;
			
			this.bigStarArr.push(starBg);
		}
	},


	startBtn: null,
	restartBtn: null,
	initBtn() {

		const btn = cc.find('Canvas/btn_start')
		btn.scale = this._mapScaleMin;
		btn.active = true;
		btn.zIndex = 50;
		btn.on(cc.Node.EventType.TOUCH_START, () => {
			console.log(' in click');
			cc.tween(btn)
				.to(0.05, {scale: 0.9 * this._mapScaleMin})
				.to(0.05, {scale: 1 * this._mapScaleMin})
				.call(() => {
					btn.active = false;
					this.startBtnClicked();
					this.addSoundBtnListner();

				})
				.start();
		})

		this.startBtn = btn;


		const restartBtn = cc.find('Canvas/btn_restart');
		restartBtn.zIndex = 50;
		restartBtn.on(cc.Node.EventType.TOUCH_START, () => {
			console.log(' in click');
			cc.tween(restartBtn)
				.to(0.05, {scale: 0.9 * this._mapScaleMin})
				.to(0.05, {scale: 1 * this._mapScaleMin})
				.call(() => {
					restartBtn.active = false;
					this.restartBtnClicked();
				})
				.start();
		})

		this.restartBtn = btn;
	},

	showSoundBtn() {
		const btn = cc.find('Canvas/btn_laba')
		btn.scale = this._mapScaleMin;
	},

	startBtnClicked() {
		
		cc.tween(this)
			.delay(0.3)
			.call(() => {
				this.showPenguin();
			})
			.start();

		this.showQuestion();
		playAudio(this.btnClip);
	},

	restartBtnClicked() {
		this.groupIndex = 0;
		this.initCurGroup();
		this.hideBigStar();
		this.startBtnClicked();
	},

	hideBigStar() {
		for (let i=0; i<this.bigStarArr.length; i++) {
			cc.tween(this.bigStarArr[i].star)
				.to(0.5, {scale: 0}, {easing: 'cubicOut'})
				.start();
		}
	},

	soundAnima: null,
	addSoundBtnListner() {
		const btn = cc.find('Canvas/btn_laba')
		btn.addComponent(cc.Button);
		btn.on('click', () => {
			this.showQuestion();
			playAudio(this.btnClip);
		})
	},

	showQuestion() {

		var anim = cc.find('Canvas/btn_laba').getComponent(cc.Animation);
		anim.play();

		playAudioByUrl(this.curGroup.audio_url, () => {
			anim.stop();
		});

	

		// // 指定播放 test 动画
		// anim.play('test');

		// // 指定从 1s 开始播放 test 动画
		// anim.play('test', 1);

		// // 使用 play 接口播放一个动画时，如果还有其他的动画正在播放，则会先停止其他动画
		// anim.play('test2');

	},


	getHole() {
		const hole = new cc.Node();
		hole.scale = this._mapScaleMin;

		const holeBg = getSprNode('hole_1');
		hole.addChild(holeBg, 1);

		const holeTop = getSprNode('hole_2');
		hole.addChild(holeTop, 10);

		return hole;
	},



	showPenguin() {

		this.showOnePenguin();
	},

	showOnePenguin() {

		const hole = this.getFreeHole();
		if (hole) {

			const penguin = this.getPenguin();
			const optionData = this.getOptionData();
			this.addPenguin(hole, penguin, optionData);

		} else {

			cc.tween(this)
				.delay(0.3)
				.call(() => {
					this.showOnePenguin();
				})
				.start();
		}
	},

	getOptionData() {

		const arr = randomSortByArr( this.curGroup.optionArr );
		return arr[0];
	},
	    

	getPenguin() {

		// console.log('this.penguinPool.length: ', this.penguinPool.length);

		if (this.penguinPool.length > 0) {
			return this.penguinPool.shift();
		}

		const node = new cc.Node();

		const id = RandomInt(1, 2)
		const penguin = getSprNode('penguin_' + id);
		node.penguin = penguin;

		this.addPenguinWrong(node, id);
		this.addTextPanel(node);
		this.addPicPanel(node);
		this.addClickNode(node);

		node.textPanel.y = penguin.height / 2 + node.textPanel.height / 2 - 25;
		node.picPanel.y = penguin.height / 2 + node.picPanel.height / 2 - 25;

		node.addChild(node.picPanel);
		node.addChild(node.textPanel);
		node.addChild(penguin);
		node.addChild(node.wrong);

		return node;
	},

	addClickNode(node) {
		const rectNode = new cc.Node();
		rectNode.addComponent(cc.Button);
		rectNode.width = 270;
		rectNode.height = 180;
		rectNode.anchorX = 0;
		rectNode.anchorY = 0;
		// const ctx = rectNode.addComponent(cc.Graphics);
		// ctx.fillColor = '#f9bd03';
		// ctx.fillRect(0, 0, 270, 180);
		// ctx.stroke();		

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

			this.checkPenguinIsRight(node)
		})

		node.addChild(rectNode, 10);
		rectNode.x = -130;
		rectNode.y = 40;

		rectNode.opacity = 50;
	},

	checkPenguinIsRight(node) {

		if (!node.data) {
			return;
		}
		if (this.isRightDuration) {
			return;
		}

		if (node.data.end) {
			return;
		}

		if (node.data.isRight == '1') {
			this.showPenguinRight(node);
			node.data.end = true;
		} else {
			this.showPenguinWrong(node);
		}
	},

	isRightDuration: null,
	showPenguinRight(node) {
		
		this.isRightDuration = true;

		this.showAnimaStar(node);
		this.stopPenguin(node);
		this.showRightSound(node);
	},

	showPenguinWrong(node) {
		node.penguin.active = false;
		node.wrong.active = true;

		playAudio(this.wrongClip);
	},

	showAnimaStar(node) {

		const resDragonBone = cc.find("Canvas/res/anima/star")
		const d = cc.instantiate(resDragonBone)	
		node.addChild(d, 20);

		d.x = 0;
		d.y = node.penguin.height / 2;

	},

	checkNextStar(node) {

		const data = node.data;
		
		console.log('this.curGroup: ', this.curGroup);

		const optionArr = this.curGroup.optionArr
		const index = optionArr.indexOf(data);
		if (index != -1) {
			optionArr.splice(index, 1);
		}



		const isEnd = this.checkIsGroupEnd();
		if (isEnd) {
			this.showBigStar();
		} else {
			cc.tween(this)
			.delay(1)
			.call(() => {
				this.showOnePenguin();
			})
			.start();
		}
		

		this.hideCurPenguin(node);
		this.isRightDuration = false;

	
	},

	hideCurPenguin(penguin) {
		

		const {	downY, moveTime, panel, hole} = penguin.hideData;

		cc.tween(penguin)
		.call(() => {
			hidePanel();
		})
		.to(moveTime, {y: downY}, {easing: 'quadInOut' })
		.call(() => {
			penguin.active = false;
			penguin.penguin.active = true;
			penguin.wrong.active = false;
			
			hole.penguin = null;
			this.penguinPool.push(penguin);

			penguin.moveTween = null;
		})
		.start();


		const hidePanel = () => {
		
			cc.tween(panel)
				.to(moveTime * 0.3, {opacity: 0})
				.call(() => {
					panel.active = false;
				})
				.start();	
		}	
	},

	showBigStar() {
		const bigStarBg = this.bigStarArr[this.groupIndex];
		const star = bigStarBg.star;
		star.active = true;
		star.opacity = 0;
		star.scale = 3 * this._mapScaleMin;
		star.rotation = 0;


		const time = 1;
		cc.tween(star)
			.to(time, {scale: 1, opacity: 255, rotation: 360}, {easing: 'quadOut'})
			.call(() => {
				this.checkGameEnd();
			})
			.start();

		playAudio(this.bigStarClip);
	},

	checkGameEnd() {

		this.groupIndex ++;
	
		if (!this.data.groupArr[this.groupIndex] ) {
			this.gameEnd();
			return;
		}

		this.initCurGroup();
		this.showOnePenguin();
		this.showQuestion();
	},

	gameEnd() {
		this.playEndEffect();

		cc.tween(this)
			.delay(0.2)
			.call(() => {
				this.showRestartBtn();
			})
			.start();
	},

	showRestartBtn() {
		const restartBtn = cc.find('Canvas/btn_restart');
		restartBtn.zIndex = 20;
		restartBtn.active = true;
		restartBtn.scale = 0;

		cc.tween(restartBtn)
			.to(1, {scale: this._mapScaleMin}, {easing: 'elasticOut'})
			.start();

		
	},

	playEndEffect() {
		playAudio(this.endClip);
		const camera = cc.find('Canvas/Main Camera');
		camera.zIndex = 100;

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

	checkIsGroupEnd() {
		
		const optionArr = this.curGroup.optionArr
		for (let i=0; i<optionArr.length; i++) {
			if (optionArr[i].isRight == '1') {
				return false;
			}
		}
		return true;
	},

	stopPenguin(node) {
		if (node.moveTween) {
			console.log('node.moveTween: ', node.moveTween);
			node.moveTween.stop();
		}
	},

	showRightSound(node) {
		playAudio(this.rightClip, () => {

			if (!node.data.audio_url) {
				this.checkNextStar(node);
				return;
			}
			playAudioByUrl(node.data.audio_url, () => {
				this.checkNextStar(node)
			})
		});
	},


	addPenguinWrong(node, id) {
		const penguinWrong = getSprNode('penguin_' + id + '_wrong');
		penguinWrong.active = false;
		node.wrong = penguinWrong;
	},


	addTextPanel(node) {
		const textPanel = getSprNode('panel_text');
		textPanel.active = false;
		node.textPanel = textPanel;

		const labelNode = new cc.Node();
		const label = labelNode.addComponent(cc.Label)
		textPanel.addChild(labelNode, 5);
		label.fontSize = 54;

		label.font = cc.find('Canvas/res/font/Berlin Sans FB').getComponent(cc.Label).font;

		const color = new cc.Color();
		cc.Color.fromHEX(color, 'c1431d');
		labelNode.color = color;

		labelNode.y = 5;
		textPanel.label = label;


		textPanel.addComponent(cc.Button)
		textPanel.on('click', () => {
			this.checkPenguinIsRight(node);
		})
	},

	addPicPanel(node) {

		const picPanel = getSprNode('panel_pic');
		picPanel.active = false;
		node.picPanel = picPanel;

		const picNode = new cc.Node();
  	const spr = picNode.addComponent(cc.Sprite);
		picPanel.addChild(picNode);

		picNode.y = 0;
		picPanel.spr = spr;


		picPanel.addComponent(cc.Button)
		picPanel.on('click', () => {
			this.checkPenguinIsRight(node);
		})
		
	},

	getFreeHole() {

		const holeArr = randomSortByArr(this.holeArr)
		for (let i=0; i<holeArr.length; i++) {
			if (!holeArr[i].penguin) {
				return holeArr[i]
			}
		}
		return null;
	},



	addPenguin(hole, penguin, optionData) {
		penguin.active = true;
		penguin.parent = hole;
		penguin.zIndex = 5;
		hole.penguin = penguin;

	
		const downY = -180;
		penguin.y = downY;


		let panel;
		if (optionData.type == 'text') {
			panel = penguin.textPanel;
		} else {
			panel = penguin.picPanel;
		}
		this.setPanelData(panel, optionData);


		const moveTime = 0.2 + Math.random() * 0.1;
		const standTime = 1 + Math.random() * 2;
	

		penguin.hideData = {
			downY, moveTime, panel, hole
		}

		penguin.moveTween = cc.tween(penguin)
			.to(moveTime, {y: 0}, {easing: 'quadInOut' })
			.delay(standTime)
			.call(() => {
				hidePanel();
			})
			.to(moveTime, {y: downY}, {easing: 'quadInOut' })
			.call(() => {
				penguin.active = false;
				penguin.penguin.active = true;
				penguin.wrong.active = false;
				
				hole.penguin = null;
				this.penguinPool.push(penguin);

				penguin.moveTween = null;
			})
			.start();




		const nextTime = 0.3 + Math.random() * 2 ;
		cc.tween(this)
			.delay(nextTime)
			.call(() => {

				if (!this.isRightDuration) {
					this.showOnePenguin();
				}
			})
			.start();




		const showPanel = () => {
			panel.active = true;
			panel.opacity = 0;
	
			cc.tween(panel)
				.to(moveTime * 0.3, {opacity: 255})
				.start();	
		}

		const hidePanel = () => {
		
			cc.tween(panel)
				.to(moveTime * 0.3, {opacity: 0})
				.call(() => {
					panel.active = false;
				})
				.start();	
		}	

		showPanel();

	
		playAudio(this.appearClip);
	},

	setPanelData(panel, optionData) {
		panel.data = optionData;
		panel.parent.data = optionData;
		
		if (optionData.type == 'text') {
			this.setTextPanelData(panel, optionData);
		} else {
			this.setPicPanelData(panel, optionData);
		}
	},

	setTextPanelData(panel, optionData) {

		const panelW = 255 ;

		panel.label.string = optionData.text;
		panel.label["_forceUpdateRenderData"](true);

		if (panel.label.node.width > panelW) {
			panel.label.node.scale = panelW / panel.label.node.width 
		} else {
			panel.label.node.scale = 1;
		}

	},

	setPicPanelData(panel, optionData) {
		cc.loader.load({url: optionData.pic_url}, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			panel.spr.spriteFrame = spriteFrame
			

			const panelW = 215;
			const panelH = 135;
			const sx = panelW / img.width;
			const sy = panelH / img.height;
			const s = Math.min(sx, sy);
			panel.spr.node.scale = s;
			
		})
	},













	_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');
		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 titleH = 107 * this._mapScaleMin + 11 * 2

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



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


			const sx = this.canvas.width / this.hotZoneBg.width;
			const sy = (this.canvas.height - titleH) / this.hotZoneBg.height;
			const s = Math.min(sx, sy);
			this.hotZoneBg.scale = s;
			
			// this.hotZoneBg.y = -frameSize.height / 2 * this._cocosScale + this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY + (subNum * mapS * this._cocosScale);
			this.hotZoneBg.y = 0 - titleH / 2 ;
			// console.log('this.hotZoneBg.y', this.hotZoneBg.y);




			// this.data.bgItem.isShowDebugLine = true;
			this.initHotZoneItem();


	
		});

	},

	initHotZoneItem() {
		this.data.hotZoneItemArr.forEach((item) => {
			// console.log('item.gIdx: ', item.gIdx);
			if (item.gIdx == '0') {
				this.setOneAnimaSmall(item);
			} else if (item.gIdx == '1') {
				this.setOnePic(item);
			} else if (item.gIdx == '2') {
				this.setOneRect(item)
			} else if (item.gIdx == '3') {
				this.setOneAction(item);
			}
		});

	},


	addMask(node) {
		const mask = node.addComponent(cc.Mask);
		mask.type = cc.Mask.Type.RECT;
	},

	setOneAction(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;
		const {x, y, width, height} = rectNode;
		rectNode.anchorX = rectNode.anchorY = 0;

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



		// console.log('setOneAction ~~ data: ', data)
		const actionData = data['actionData_' + data.gIdx];
		if (actionData && actionData.type == 'text') {
			const label = this.setOneActionText(rectNode, actionData);
			label.node.scale = scale * data.fontScale;

			// label.overflow = cc.Label.Overflow.NONE;
			// label.node.setContentSize(new cc.Size(0, lineHeight));
			label["_forceUpdateRenderData"](true);
			
			// console.log('label.node.width: ', label.node.width * label.node.scale)
			// console.log('label.node.height: ', label.node.height * label.node.scale)
			// console.log('rectNode.width: ', rectNode.width)
			// console.log('rectNode.height: ', rectNode.height)
			// console.log('label.node.scale: ', label.node.scale)
			// rectNode.width = label.node.width;

			// let textWidth = Math.min(label.node.width, designSize.width);
			// textWidth = Math.floor(textWidth / fontSize) * fontSize;

			// const size = label.getContentSize();
			// console.log('label: ', label)
			// console.log('size: ', size)

			
		}
	},

	setOneActionText(rectNode, actionData) {


		const labelNode = new cc.Node();
		labelNode.parent = rectNode;
		const label = labelNode.addComponent(cc.Label);

		label.font = cc.find('Canvas/res/font/aharoni').getComponent(cc.Label).font;
		label.string = actionData.text;
		// 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.color = cc.Color.BLACK;


		const opArr = actionData.changeOption
		// console.log('opArr', opArr);


		const tweenArr = [];

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

			const opData = opArr[i];
			console.log('opArr[0]', opArr[i])
			if (opData[0] == 'fontColor') {
				const color = new cc.Color();
				cc.Color.fromHEX(color, opData[1] );
				labelNode.color = color;

			} else if (opData[0] == 'opacity') {
				// console.log('opData: ', opData)
				labelNode.opacity = Number( opData[1] / 100 * 255 ) + 0.1;
				// console.log(labelNode.opacity);
				tweenArr.push({item: labelNode , option: `{"${opData[0]}" : ${opData[2] / 100 * 255}}`, optionName: opData[0]},)

			} else {
				label[opData[0]] = opData[1];
				tweenArr.push({item: label, option: `{"${opData[0]}" : ${opData[2]}}`, optionName: opData[0]})

			}
		}


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


		label.lineHeight = label.fontSize;

		labelNode.y += rectNode.height / 2;
		labelNode.x += rectNode.width / 2;
		

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

			if (labelNode.audioClip) {
				cc.audioEngine.stopAllEffects();
				cc.audioEngine.playEffect(labelNode.audioClip, false, 0.8);
			}

			if (labelNode.isClicked) {
				// return;
			}
			labelNode.isClicked = true;

			// const j = JSON.stringify({'fontSize': 500});
			// console.log('j: ', JSON.parse('{"fontSize":500}'));

			for (let i=0; i<tweenArr.length; i++) {
				const tweenData = tweenArr[i];

				// JSON.parse(tweenData.option)

				// console.log( JSON.parse(tweenData.option) );

				if (tweenData.optionName == 'opacity') {
					console.log('~~~ ',  tweenData.item[tweenData.optionName] );
					// tweenData.item[tweenData.optionName] = tweenData.item[tweenData.optionName] + 1

					cc.tween(tweenData.item)
						.to(actionData.changeTime,  JSON.parse(tweenData.option) )
						.start();
				}
				

			}

			// cc.tween({})
			// 	.to(5, { scale: (Math.random() - 0.5) + 1})
			// 	.start();

		});

		// labelNode.opacity = 255;

		return label;
	},



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



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


					animaNode.x = rectNode.x + rectNode.width / 2;
					animaNode.y = rectNode.y + rectNode.height / 2;

					const sx = rectNode.width / animaNode.width;
					const sy = rectNode.height / animaNode.height;
					const scale = Math.min(sx, sy);
					animaNode.scale = scale;
					
				});
			});
		});

	},


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

		});

	},

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


		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;
		// console.log('scale: ', scale);
		// console.log('scale2: ', scale / data.mapScale);


		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.scale = 1 / data.mapScale;

		rectNode.anchorX = rectNode.anchorY = 0;


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

		// console.log('```data: ', data)


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

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

			if (rectNode.audioClip) {
				cc.audioEngine.stopAllEffects();
				cc.audioEngine.playEffect(rectNode.audioClip, false, 0.8);
			}
		});


	},

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


});
