import Tittle from "./Tittle"
import Middle from "./Middle"
import Bottom from "./Bottom"


cc.Class({

	extends: cc.Component,

	properties: {
		loadInAudioSource:cc.AudioSource,
		dragonBonesNode:cc.Node,
		pic_a_sprite:cc.Node,
		pic_c_sprite:cc.Node,
		tittleJs:Tittle,
		middleJs:Middle,
		bottomJs:Bottom

	},

	// 生命周期 onLoad
	onLoad() {
		this.initSceneData();
		this.initSize();
		this.loadInAudioSource.play();
	},

	_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;
		}
		// this.dragonBonesNode.on(cc.Node.EventType.TOUCH_START,this.playDragonAnimation,this)
		getData((data) => {
			cc.log('data:', data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
	},

    playDragonAnimation(){
        let ad = this.dragonBonesNode.getComponent(dragonBones.ArmatureDisplay);
        if(ad){
            ad.playAnimation("normal", 1);
        }
    },

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

	getDefaultData() {
		const dataJson = '{"bt_text":"111","bt_audio_url":"http://staging-teach.cdn.ireadabc.com/7934cdcec68eabe639020bad5420d7f8.mp3","pic_or_dragonBone":[{"type":"dragonBone","audio_url":"http://staging-teach.cdn.ireadabc.com/b0c23eb327ec13212d09516a1a8a49ec.mp3","pic_url":"http://staging-teach.cdn.ireadabc.com/db8a7ed8fb354558fad66edfbba43d89.jpg","skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/14ca834d522122b031a2e18be5129251.json","name":"sb_boy_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/ecc48e23d55b1af8eb40d997dc573791.json","name":"sb_boy_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/2d668f8049bc98c0e026921ef316a0fd.png","name":"sb_boy_tex.png"}},{"type":"img","audio_url":"http://staging-teach.cdn.ireadabc.com/0f0482ddb8c0d3329165ab0612683148.mp3","pic_url":"http://staging-teach.cdn.ireadabc.com/2d668f8049bc98c0e026921ef316a0fd.png","skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/14ca834d522122b031a2e18be5129251.json","name":"sb_boy_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/ecc48e23d55b1af8eb40d997dc573791.json","name":"sb_boy_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/2d668f8049bc98c0e026921ef316a0fd.png","name":"sb_boy_tex.png"}},{"type":"dragonBone","audio_url":"http://staging-teach.cdn.ireadabc.com/b0c23eb327ec13212d09516a1a8a49ec.mp3","pic_url":"http://staging-teach.cdn.ireadabc.com/2d668f8049bc98c0e026921ef316a0fd.png","skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/14ca834d522122b031a2e18be5129251.json","name":"sb_boy_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/ecc48e23d55b1af8eb40d997dc573791.json","name":"sb_boy_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/2d668f8049bc98c0e026921ef316a0fd.png","name":"sb_boy_tex.png"}}],"bottom_text":"9999999999999","bottom_audio_url":"http://staging-teach.cdn.ireadabc.com/784cd4188bf126d6c3c9395d9a807619.mp3"}'
		const data = JSON.parse(dataJson);
		return data;
	},

	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},


	addPreloadImage() {
		this._imageResList.push({ url: this.data.pic_A_url });
		this._imageResList.push({ url: this.data.pic_C_url });
		// this._imageResList.push({ url: this.data.dragonBone.texPngData.url });
	},

	addPreloadAudio() {
		this._audioResList.push({ url: this.data.bt_audio_url });
		this._audioResList.push({ url: this.data.dragonBone_audio_url });
		this._audioResList.push({ url: this.data.pic_A_audio_url });
		this._audioResList.push({ url: this.data.pic_C_audio_url });
		this._audioResList.push({ url: this.data.bottom_audio_url });
	},

	addPreloadAnima() {
		// this._animaResList.push({url: this.data.dragonBone.skeJsonData.url});
		// this._animaResList.push({url: this.data.dragonBone.texJsonData.url});
		// this._animaResList.push({url: this.data.dragonBone.texPngData.url});
	},

	preload() {

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

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

			cc.debug.setDisplayStats(false);
		});
	},


	loadEnd() {
		this.initData();
		this.initAudio();
		this.initView();
		// this.initListener();
	},

	_cantouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		this._cantouch = true;
	},

	audioBtn: null,
	initAudio() {
		this.getAudioByUrl(this.data.bt_audio_url,(ac)=>{
			this.tittleJs.setAudioClip(ac);
		});
		this.getAudioByUrl(this.data.bottom_audio_url,(ac)=>{
			this.bottomJs.setAudioClip(ac);
		});
		this.getAudioByUrl(this.data.pic_or_dragonBone[0].audio_url,(ac)=>{
			this.middleJs.setAudioClip(ac,0);
		});
		this.getAudioByUrl(this.data.pic_or_dragonBone[1].audio_url,(ac)=>{
			this.middleJs.setAudioClip(ac,1);
		});
		this.getAudioByUrl(this.data.pic_or_dragonBone[2].audio_url,(ac)=>{
			this.middleJs.setAudioClip(ac,2);
		});
	},


	initView() {
		this.initBg();
		this.initPic();
		this.initTile();
		//this.initBtn();
		this.initIcon();
		// this.loadDragonBones();
	},
	loadDragonBones(node,urlData){
		var animNode = node;
		var dragonDisplay = animNode.addComponent(dragonBones.ArmatureDisplay);

		var image = urlData.texPngData.url;
		var ske = urlData.skeJsonData.url;
		var atlas = urlData.texJsonData.url;
		// var image = this.data.dragonBone.texPngData.url;
		// var ske = this.data.dragonBone.skeJsonData.url;
		// var atlas = this.data.dragonBone.texJsonData.url;
		var item = this.data;
		cc.loader.load(image, (error, texture) => {
			cc.loader.load({ url: atlas, type: 'txt' }, (error, atlasJson) => {
				cc.loader.load({ url: ske, type: 'txt' }, (error, dragonBonesJson) => {
					var atlas = new dragonBones.DragonBonesAtlasAsset();
					atlas.atlasJson = atlasJson;
					atlas.texture = texture;
					var asset = new dragonBones.DragonBonesAsset();
					asset.dragonBonesJson = dragonBonesJson;
					dragonDisplay.dragonAtlasAsset = atlas;
					dragonDisplay.dragonAsset = asset;
					let dbj = JSON.parse(dragonBonesJson);
					let armatureNames = dbj.armature.map(data => data.name);
					if(armatureNames.length>0){
						dragonDisplay.armatureName = armatureNames[0];
					}
					let width = animNode.width;
					let height = animNode.height;
					let tWidth = texture.width;
					let tHeight = texture.height;
					if(tWidth/tHeight>width/height){
						animNode.scale = width/tWidth;
					}else{
						animNode.scale = height/tHeight;
					}
				});
			});
		});

	},
	initTile(){
		this.tittleJs.setTittleText(this.data.bt_text);
		let dy = cc.winSize.height/2-10;
		this.tittleJs.node.y = dy;

	},
	initBg() {
		//等比缩放，底部对齐
		const bgNode = cc.find('Canvas/bg');
		let screen_size = cc.winSize.width / cc.winSize.height
		let design_size = this._designSize.width / this._designSize.height
		if(screen_size<design_size){
			bgNode.height = cc.winSize.height;
			bgNode.width = cc.winSize.height * design_size;
		}else{
			bgNode.width = cc.winSize.width;
			bgNode.height = cc.winSize.width /  design_size;
			let dy = (bgNode.height - cc.winSize.height)/2
			bgNode.y = bgNode.y + dy;
		}
		// bgNode.scale = this._mapScaleMin;
	},

	pic1: null,
	pic2: null,
	initPic() {
		// debugger
		if(this.data.pic_or_dragonBone[0].type == "img"){
			this.loadPic(this.dragonBonesNode,this.data.pic_or_dragonBone[0].pic_url);
		}else{
			this.loadDragonBones(this.dragonBonesNode,this.data.pic_or_dragonBone[0]);
		}

		if(this.data.pic_or_dragonBone[1].type == "img"){
			this.loadPic(this.pic_a_sprite,this.data.pic_or_dragonBone[1].pic_url);
		}else{
			this.loadDragonBones(this.pic_a_sprite,this.data.pic_or_dragonBone[1]);
		}

		if(this.data.pic_or_dragonBone[2].type == "img"){
			this.loadPic(this.pic_c_sprite,this.data.pic_or_dragonBone[2].pic_url);
		}else{
			this.loadDragonBones(this.pic_c_sprite,this.data.pic_or_dragonBone[2]);
		}
		// dragonBonesNode:cc.Node,
		// pic_a_sprite:cc.Node,
		// pic_c_sprite:cc.Node,
		/*
		this.getSpriteFrimeByUrl(this.data.pic_A_url,(spriteFrame)=>{
			let width = this.pic_a_sprite.node.width;
			let height = this.pic_a_sprite.node.height;
			this.pic_a_sprite.spriteFrame = spriteFrame;
			// cc.log(this.pic_a_sprite.node.scale);
			if(this.pic_a_sprite.node.width/this.pic_a_sprite.node.height > width/height){
				this.pic_a_sprite.node.scale = width/this.pic_a_sprite.node.width;
			}else{
				this.pic_a_sprite.node.scale = height/this.pic_a_sprite.node.height;
			}
		});
		this.getSpriteFrimeByUrl(this.data.pic_C_url,(spriteFrame)=>{
			let width = this.pic_c_sprite.node.width;
			let height = this.pic_c_sprite.node.height;
			this.pic_c_sprite.spriteFrame = spriteFrame;
			if(this.pic_c_sprite.node.width/this.pic_c_sprite.node.height > width/height){
				this.pic_c_sprite.node.scale = width/this.pic_c_sprite.node.width;
			}else{
				this.pic_c_sprite.node.scale = height/this.pic_c_sprite.node.height;
			}
		});
		*/
	},

	loadPic(node,pic_url){
		this.getSpriteFrimeByUrl(pic_url,(spriteFrame)=>{
			let width = node.width;
			let height = node.height;
			let sprite = node.addComponent(cc.Sprite);
			sprite.spriteFrame = spriteFrame;
			// cc.log(this.pic_a_sprite.node.scale);
			if(node.width/node.height > width/height){
				node.scale = width/node.width;
			}else{
				node.scale = height/node.height;
			}
		});
	},

	initIcon() {},

	curPage: null,
	initBtn() {	},

	leftMove() {},

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

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

	getAudioByUrl(audio_url, cb = null) {
		if (audio_url) {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				if (cb) {
					cb(audioClip);
				}
			});
		}
	},

	playAudioByUrl(audio_url, cb = null) {
		if (audio_url) {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				const audioId = cc.audioEngine.play(audioClip, false, 0.8);
				if (cb) {
					cc.audioEngine.setFinishCallback(audioId, () => {
						cb();
					});
				}
			});
		}
	},

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

});
