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

cc.Class({
	extends: cc.Component,

	properties: {
		baseWidth: {
			default: 1280,
			type: cc.Integer
		},
		baseHeight: {
			default: 720,
			type: cc.Integer
		}
		// 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,
	initSize() {
		this._designSize = cc.view.getDesignResolutionSize();

	},

	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 = {"bgColorId":0,"bgColor":"#f9bd03","lrcData":{"audio_url":"http://staging-teach.cdn.ireadabc.com/9259e1b99cc17f61210e7edc17f1d697.mp3","fontSize":24,"lineHeight":32,"lyrics":[{"time":0.112745,"data":"","newLine":false},{"time":0.685942,"data":"","newLine":false},{"time":0.31448,"data":"","newLine":false},{"time":0.386885,"data":"","newLine":false}]},"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/539e2f58cb1817f852d9c09ec1ac7c8b.png","rect":{"x":265.18,"y":0,"width":776.65,"height":500}},"hotZoneItemArr":[{"id":"1611200754821","index":0,"pic_url":"http://staging-teach.cdn.ireadabc.com/05a37c3f8249811eda089c44f5d2acc6.png","audio_url":"http://staging-teach.cdn.ireadabc.com/66878465ec50d162bd60fcdaa641933b.mp3","itemType":"pic","fontScale":1.02109375,"imgScale":0.46864686468646866,"mapScale":1.02109375,"gIdx":"1","rect":{"x":24.14,"y":341,"width":234.32,"height":142}},{"id":"1611200760188","index":1,"pic_url":"http://staging-teach.cdn.ireadabc.com/c8abf7383d65bcbdba8f390785cece60.png","text":"aa111","audio_url":"http://staging-teach.cdn.ireadabc.com/83513f8d6083ebe072e3f9e47a21558a.mp3","itemType":"rect","fontScale":1.02109375,"imgScale":0.7029268568840579,"mapScale":1.02109375,"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/51e9d8e4e2e963a7658d07eba6c282f8.json","name":"Ubbie_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/4232e00c9b1d272e650e51dbb785e498.json","name":"Ubbie_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/2e56dbe3134380952a725eacceb86359.png","name":"Ubbie_tex.png"},"gIdx":"0","rect":{"x":259.31,"y":85,"width":200,"height":200}},{"id":"1611200801763","index":2,"audio_url":"http://staging-teach.cdn.ireadabc.com/1961d807c944e6551af02c7b57e117f3.mp3","itemType":"rect","fontScale":1.02109375,"imgScale":1,"mapScale":1.02109375,"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/51e9d8e4e2e963a7658d07eba6c282f8.json","name":"Ubbie_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/4232e00c9b1d272e650e51dbb785e498.json","name":"Ubbie_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/2e56dbe3134380952a725eacceb86359.png","name":"Ubbie_tex.png"},"gIdx":"5","rect":{"x":550.31,"y":275,"width":200,"height":200}}],"picArr":[],"bg_audio_url":"http://staging-teach.cdn.ireadabc.com/3fa65d5f667a2ef9059d3dfc5df74a4d.mp3"}
		// if (data.picArr) {
		// 	data.picArr = data.picArr.concat(data.picArr);
		// 	data.picArr = data.picArr.concat(data.picArr);
		// 	data.picArr = data.picArr.concat(data.picArr);
		// 	data.picArr = data.picArr.concat(data.picArr);
		// 	data.picArr = data.picArr.concat(data.picArr);
		// }
		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.bgItem) {
			this._imageResList.push({ url: this.data.bgItem.url });
		}
		if (!this.data.hotZoneItemArr) {
			return;
		}
		this.data.hotZoneItemArr.forEach((item) => {
			if (item.pic_url) {
				this._imageResList.push({ url: item.pic_url });
			}
		})
	},

	addPreloadAudio() {

		if (!this.data.hotZoneItemArr) {
			return;
		}
		this.data.hotZoneItemArr.forEach((item) => {
			this._audioResList.push({url: item.audio_url});
		});
		if (this.data.lrcData && this.data.lrcData.audio_url) {
			this._audioResList.push({url: this.data.lrcData.audio_url });
		}	
		if (this.data.accompany_audio_url) {
			this._audioResList.push({url: this.data.accompany_audio_url});
		}

		this._audioResList.push({url: this.data.bg_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();
		cc.director.emit('GAME_RESOURCE_LOADED');
	},

	initView() {
		this.initBg();
		this.initHotZone();
		this.initBottomPart();
		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);
		});
	},

	_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', function(){
							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);
							}
						}, this);
					}

				});
			});
		});

	},


	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', function() {
				if (picNode.audioClip) {
					cc.audioEngine.stopAllEffects();
					cc.audioEngine.playEffect(picNode.audioClip, false, 0.8);
				}
		}, this);
	},


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