// 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.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() {
		this.initSceneData();
		this.initSize();
		window['play'] = 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 = {"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/47a5c15dbb2ef6270471ee1b091b6ef1.png","rect":{"x":112,"y":0,"width":726,"height":363}},"hotZoneItemArr":[{"id":"1597905583145","index":0,"pic_url":"http://staging-teach.cdn.ireadabc.com/12dd0995373672fdb9421aeb9cc252ef.png","audio_url":"http://staging-teach.cdn.ireadabc.com/f3c224078a9ae2c0c7c7e681089d4ecd.mp3","itemType":"rect","fontScale":0.7421875,"imgScale":1.6242816091954022,"mapScale":0.7421875,"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/e669aaa432910b448bcd6724fe03fbde.json","name":"walk_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/e4fee97e9cf1cb0028a115ccdcdcbf91.json","name":"walk_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/70796c815f8f4d39e02b45939d52fe8e.png","name":"walk_tex.png"},"gIdx":"0","rect":{"x":303,"y":175,"width":88,"height":85}}]}
		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, {cacheAsset: true}, null, (err, data) => {
			console.log(' preload data, ', data);
			
			// typeof
			this.loadEnd();
			// console.log('hide rabbit');
			// if (window && window["air"]) {
			// 	window["air"].hideAirClassLoading();
			// }
		});
	},

	addPreloadImage() {
		if (this.data.bgItem) {
			this._imageResList.push({url: this.data.bgItem.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});
		}
	},

	addPreloadAnima() {
		if (!this.data.hotZoneItemArr) {
			return;
		}
		this.data.hotZoneItemArr.forEach((item) => {
			if (item.gIdx == '0') {
				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.resourceLoaded = true;
		this.loadScratchCardsComponent();
		// cc.director.emit('GAME_RESOURCE_LOADED', this.hotZoneBg);
	},
	loadScratchCardsComponent() {
		// this.resourceLoaded = true;	
		// this.hotZoneLoaded = true;
		if (this.resourceLoaded &&  this.hotZoneLoaded) {
			console.log('hide rabbit');
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}
			cc.director.emit('GAME_RESOURCE_LOADED', this.hotZoneBg);
		}
	},
	initView() {
		this.initBg();
		this.initHotZone();
		this.initBottomPart();
	},

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


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

			this.hotZoneBg.scale = Math.min(sx, sy);
			this.hotZoneBg.__scaleRate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;
			
			// 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') {
					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)
				}
			});
			this.hotZoneLoaded = true;
			this.loadScratchCardsComponent()
		});

	},
	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, scale})
		// 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);
		rectNode.zIndex = 999;

		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();
		cc.director.emit('ADD_ANIMAT_MASK', rectNode)


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

		// rectNode.addChild(animaNode);
		// animaNode.x = rectNode.x + rectNode.width / 2;
		// animaNode.y = rectNode.y + rectNode.height / 2;
		// animaNode.width = rectNode.width;
		// animaNode.height = rectNode.height;
		// animaNode.anchorX = rectNode.anchorY = 0;


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


		const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);

		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', (e) => {
							console.log(e)
							
							if (rectNode.isClicked) {
								// return;
							}
							rectNode.isClicked = true;
							console.log('clicked');

							if (animaNode.audioClip) {
								cc.audioEngine.stopAll();
								
								const aid = cc.audioEngine.play(animaNode.audioClip, false, 0.8);
								if (e && e.cb && e.cb.call ) {
									cc.audioEngine.setFinishCallback(aid, () => {
										e.cb(aid)
									});
								}
							}

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

	}


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