// 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 {
	asyncTweenTo,
	asyncPlayDragonBoneAnimation,
    asyncDelay,
} from '../script/utils'

cc.Class({

	extends: cc.Component,

	properties: {
	},

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

	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	_dragonAnimaList: 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;
		}

		getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
	},

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

	getDefaultData() {
		
		// const dataJson = '{"animationName":"DailyConversations"}'
		// const dataJson = '{"animationName":"WarmUp"}'
		// const dataJson = '{"animationName":"LettersInLife"}'
		// const dataJson = '{"animationName":"Phonics"}'
		// const dataJson = '{"animationName":"LetsBlend"}'
		// const dataJson = '{"animationName":"ExerciseTime"}'
		const dataJson = '{"animationName":"TraceAndRead"}'
		// const dataJson = '{"animationName":"LookAndSay"}'
		// const dataJson = '{"animationName":"LetsReview"}'
		// const dataJson = '{"animationName":"SightWords"}'
		// const dataJson = '{"animationName":"StoryTime"}'
		// const dataJson = '{"animationName":"Topic"}'
		// const dataJson = '{"animationName":"ReadClosely"}'
		const data = JSON.parse(dataJson);
		return data;
	},

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


	addPreloadImage() {

	},

	addPreloadAudio() {

	},

	addPreloadAnima() {

	},

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

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

	initAudio() {
		
	},


	initView() {
		this.initBg();
		this.initPic();
		this.initBtn();
		this.initIcon();
	},

	initBg() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMin;
	},

	initPic() {
		const ferrisWheelBg = cc.find('Canvas/bg/ferris_wheel_bg');
		ferrisWheelBg.scale = this._mapScaleMin;
	},
	
	initIcon() {
		
	},
	initBtn() {
		this.showDragon();
	},
	async showDragon() {
		const nodeName = 'Canvas/' + this.data.animationName;
        const animationNode = cc.find(nodeName);
		animationNode.active = true;
		var dragonDisplay = animationNode.getComponent(dragonBones.ArmatureDisplay);
		var animNameArr = dragonDisplay.getAnimationNames("armatureName");
		dragonDisplay.playAnimation(animNameArr[0], 1);
		dragonDisplay.once(dragonBones.EventObject.COMPLETE, () => {
			this.playEffect(this.data.animationName);
		});
		animationNode.x = cc.find('Canvas').width;
		animationNode.y = 0;

		animationNode.scale = this._mapScaleMin;
        await asyncTweenTo(animationNode, 0.5, { x: 0 });
    },
	// 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);
			}
		})
	},

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

	// ------------------------------------------
	playEffect(name, loop, volume) {
        let musicComponent = cc.find('Canvas/MusicNode').getComponent('Music');
        musicComponent.playEffect(name, loop, volume);
    }

});
