// 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 GameLogic from "./GameLogic"

cc.Class({

	extends: cc.Component,
	gameLogic: null,
	properties: {

	},

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

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

		getData((data) => {
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()

			// 添加游戏逻辑
			this.gameLogic = new GameLogic(this.data, {
				designSize: this._designSize,
				frameSize: this._frameSize,
				mapScaleMin: this._mapScaleMin,
				mapScaleMax: this._mapScaleMax,
				cocosScale: this._cocosScale,
			});
		})
	},

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

	getDefaultData() {
		const dataJson = '{"contentObj":{"version":"1.0","key":"DataKey_Sbox_FT_08","bgMusic":"","titleText":"TEstd","questionAudio_url":"","dataArray":[{"text":"","image_url":"http://staging-teach.cdn.ireadabc.com/51795b0a7c66d61ad85a388c4299f614.jpg","audio_url":"http://staging-teach.cdn.ireadabc.com/3b5540cc95a006dff8c41dba7537075a.mp3"},{"text":"","image_url":"http://staging-teach.cdn.ireadabc.com/c9d60af536380445e48c637acb753d51.gif"},{"text":"","image_url":"http://staging-teach.cdn.ireadabc.com/d3cdc8921c6ae9b4f29b25fbb3a0f2f9.jpg"}]}}'
		const data = JSON.parse(dataJson);
		return data;
	},

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


	addPreloadImage() {

		if (!this.data.dataArray) {
			return;
		}

		this.data.dataArray.forEach(item=>{
			this._imageResList.push({ url: item.question.centerImage_url});
		})
	

	},

	addPreloadAudio() {

		this._audioResList.push({ url: this.data.audio_url });
	},

	addPreloadAnima() {
		if (!this.data.dataArray) {
			return;
		}
		this.data.dataArray.forEach((item) => {
			if (item.dragonBones) {
				this._animaResList.push({url: item.dragonBones.skeJsonData.url});
				this._animaResList.push({url: item.dragonBones.texJsonData.url});
				this._animaResList.push({url: item.dragonBones.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.initView();
		// this.initListener();
	},

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

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

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

	pic1: null,
	pic2: null,
	initPic() {
		const canvas = cc.find('Canvas');
		const maxW = canvas.width * 0.7;

		this.getSprNodeByUrl(this.data.pic_url, (sprNode) => {
			const picNode1 = sprNode;
			picNode1.scale = maxW / picNode1.width;
			picNode1.baseX = picNode1.x;
			canvas.addChild(picNode1);
			this.pic1 = picNode1;

			const labelNode = new cc.Node();
			labelNode.color = cc.Color.YELLOW;
			const label = labelNode.addComponent(cc.Label);
			label.string = this.data.text;
			label.fontSize = 60;
			label.lineHeight = 60;
			label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent('cc.Label').font;
			picNode1.addChild(labelNode);
		});

		this.getSprNodeByUrl(this.data.pic_url_2, (sprNode) => {
			const picNode2 = sprNode;
			picNode2.scale = maxW / picNode2.width;
			canvas.addChild(picNode2);
			picNode2.x = canvas.width;
			picNode2.baseX = picNode2.x;
			this.pic2 = picNode2;

			const labelNode = new cc.Node();
			const label = labelNode.addComponent(cc.RichText);
			const size = 60
			label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent(cc.Label).font;
			label.string = `<outline color=#751e00 width=4><size=${size}><color=#ffffff>${this.data.text}</color></size></outline>`
			label.lineHeight = size;
			picNode2.addChild(labelNode);
		});

	},

	initIcon() {
		const iconNode = this.getSprNode('icon');
		iconNode.zIndex = 5;
		iconNode.anchorX = 1;
		iconNode.anchorY = 1;
		iconNode.parent = cc.find('Canvas');
		iconNode.x = iconNode.parent.width / 2 - 10;
		iconNode.y = iconNode.parent.height / 2 - 10;

		iconNode.on(cc.Node.EventType.TOUCH_START, () => {
			this.playAudioByUrl(this.data.audio_url);
		})
	},

	curPage: null,
	initBtn() {

		this.curPage = 0;
		const bottomPart = cc.find('Canvas/bottomPart');
		bottomPart.zIndex = 5; // 提高层级

		bottomPart.x = bottomPart.parent.width / 2;
		bottomPart.y = -bottomPart.parent.height / 2;

		const leftBtnNode = bottomPart.getChildByName('btn_left');
		//节点中添加了button组件 则可以添加click事件监听
		leftBtnNode.on('click', () => {
			if (!this._cantouch) {
				console.warn("_cantouch disabeld!")
				return;
			}
			if (this.curPage == 0) {
				return;
			}
			this.curPage = 0
			this.leftMove();

			cc.audioEngine.play(this.audioBtn.clip, false, 0.8)
		})

		const rightBtnNode = bottomPart.getChildByName('btn_right');
		//节点中添加了button组件 则可以添加click事件监听
		rightBtnNode.on('click', () => {
			if (!this._cantouch) {
				console.warn("_cantouch disabeld!")
				return;
			}
			if (this.curPage == 1) {
				return;
			}

			this.curPage = 1
			this.rightMove();

			cc.audioEngine.play(this.audioBtn.clip, false, 0.5)
		})
	},

	leftMove() {
		this._cantouch = false;
		const len = this.pic1.parent.width;
		cc.tween(this.pic1)
			.to(1, { x: this.pic1.baseX }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.pic2)
			.to(1, { x: this.pic2.baseX }, { easing: 'cubicInOut' })
			.call(() => {
				this._cantouch = true;
			})
			.start();
	},

	rightMove() {
		this._cantouch = false;
		const len = this.pic1.parent.width;
		cc.tween(this.pic1)
			.to(1, { x: this.pic1.baseX - len }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.pic2)
			.to(1, { x: this.pic2.baseX - len }, { easing: 'cubicInOut' })
			.call(() => {
				this._cantouch = true;
			})
			.start();
	},
	// 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;
	},

	getSprNode(resName) {
		const sf = cc.find(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();
					});
				}
			});
		}
	},

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

});
