import EventMgr from '../script/EventMgr';
const saveKey = "DataKey_Cocos_Test";
cc.Class({

	extends: cc.Component,

	properties: {
		nodLayerIndicators: cc.Node,
		nodLayerPages: cc.Node,
		pfbItemIndicator: cc.Prefab,
		pfbItemPage: cc.Prefab,
		audTurnPage: cc.AudioClip,
	},

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

		
	},

	onEnable() {
		this.node.on('touchstart', this.onTouchStart, this);
		this.node.on('touchmove', this.onTouchMove, this);
		this.node.on('touchend', this.onTouchEnd, this);
		this.node.on('touchcancel', this.onTouchCancel, this);
	},

	onDisable() {
		this.node.off('touchstart', this.onTouchStart, this);
		this.node.off('touchmove', this.onTouchMove, this);
		this.node.off('touchend', this.onTouchEnd, this);
		this.node.off('touchcancel', this.onTouchCancel, this);
	},

	_startX: 0,
	_endX: 0,
	onTouchStart(e) {
		let pos = e.getLocation();
		pos = this.node.convertToNodeSpaceAR(pos);
		this._startX = pos.x;
	},
	onTouchMove(e) {

	},
	onTouchEnd(e) {
		this.calcMoveX(e);
	},
	onTouchCancel(e) {
		this.calcMoveX(e);
	},

	calcMoveX(e) {
		let pos = e.getLocation();
		pos = this.node.convertToNodeSpaceAR(pos);
		this._endX = pos.x;
		// 滑动距离过短
		if (Math.abs(this._startX - this._endX) < 300) {
			return;
		}
		if (this._startX > this._endX) {
			// 左滑,下一页
			this.onPageDown();
		} else {
			// 上一页
			this.onPageUp();
		}
	},

	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	initSceneData() {
		this._startX = 0;
		this._endX = 0;
		this._pagesList = [];
		this._indicatorList = [];
		this._imageResList = [];
		this._audioResList = [];
		this._animaResList = [];
		window.GameData = {};
		GameData._currPageIndex = 0;
		GameData._isPageTurning = false;
	},

	_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() {
		this.getData((data) => {
			console.log('data:', data);
			this.data = data;
			if (data) {
				this.preloadItem()
			}
		})
	},

	getData(cb) {
		// 获取数据
		if (window.courseware) {
			const getData = window.courseware.getData;
			getData((data) => {
				data = data || this.getDefaultData();
				cb && cb(data);
			}, saveKey);
		} else {
			cb && cb(this.getDefaultData());
		}
	},

	getDefaultData() {
		const dataJson = '{"contentObj":{"version":"1.1","key":"DataKey_Cocos_Test","haveCover":true,"dataArray":[{"type":"Spine","text":"I am driving my car","image_url":"","ske_json":"http://staging-teach.cdn.ireadabc.com/48b884b3c7b3a717f6e4b055f490a1f1.json","ske_json_name":"walkingfish_ske.json","tex_json":"http://staging-teach.cdn.ireadabc.com/608b2c5f85297f0b7930325733b7bea9.json","tex_json_name":"walkingfish_tex.json","tex_png":"http://staging-teach.cdn.ireadabc.com/ecfd66f932659635f5b66642378d826b.png","tex_png_name":"walkingfish_tex.png","shortAudio_url":"http://staging-teach.cdn.ireadabc.com/248e684b0680d5ae39bacab7242b49f0.mp3"},{"type":"Image","text":"","image_url":"http://staging-teach.cdn.ireadabc.com/eedc467139a363a01e60aa7f0e843cba.jpg","shortAudio_url":"http://staging-teach.cdn.ireadabc.com/d2a9d8815d0370dc3b9aa18987dee584.mp3"},{"type":"Spine","text":"","image_url":"","ske_json":"http://staging-teach.cdn.ireadabc.com/48b884b3c7b3a717f6e4b055f490a1f1.json","ske_json_name":"walkingfish_ske.json","tex_json":"http://staging-teach.cdn.ireadabc.com/608b2c5f85297f0b7930325733b7bea9.json","tex_json_name":"walkingfish_tex.json","tex_png":"http://staging-teach.cdn.ireadabc.com/ecfd66f932659635f5b66642378d826b.png","tex_png_name":"walkingfish_tex.png","shortAudio_url":"http://staging-teach.cdn.ireadabc.com/248e684b0680d5ae39bacab7242b49f0.mp3"}],"bgm_url":""}}'
		const data = JSON.parse(dataJson);
		return data;
	},

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


	addPreloadImage() {
		this._imageResList.push({ url: this.data.pic_url });
		this._imageResList.push({ url: this.data.pic_url_2 });
	},

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

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

		this.initIndicators();
		this.initPages();
		// this.initListener();
		this.playBgm();
	},

	playBgm() {
		if (!this.data || !this.data.contentObj || !this.data.contentObj.bgm_url) {
			return;
		}
		cc.assetManager.loadRemote(this.data.contentObj.bgm_url, null, (err, clip) => {
			this.bgAudioId = cc.audioEngine.play(clip, true, 0.5);
		});
	},
	stopBgm() {
		if (this.bgAudioId) {
			cc.audioEngine.stop(this.bgAudioId);
		}
	},

	initData() {
		// 所有全局变量 默认都是null 

	},

	audioBtn: null,
	initAudio() {


	},


	initView() {

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

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

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

	},

	initIcon() {

	},

	curPage: null,
	initBtn() {


	},
	// update (dt) {},

	/**
	 * 初始化下方小圆点
	 */
	initIndicators() {
		let len = this.data.contentObj.dataArray.length;
		let haveCover = this.data.contentObj.haveCover;
		for (let i = 0; i < len; i++) {
			let node = cc.instantiate(this.pfbItemIndicator);
			node.parent = this.nodLayerIndicators;
			let comp = node.getComponent('ItemIndicator');
			if (haveCover) {
				// 有主页，主页不显示序号，后面的序号-1
				if (i == 0) {
					comp.setNum('');
					comp.setSelected();
				} else {
					let comp = node.getComponent('ItemIndicator');
					comp.setNum(i);
					comp.setUnselected();
				}
			} else {
				let comp = node.getComponent('ItemIndicator');
				comp.setNum(i + 1);
				if (i == 0) {
					comp.setSelected();
				} else {
					comp.setUnselected();
				}
			}
			this._indicatorList.push(comp);
		}
		
	},

	/**
	 * 
	 * 初始化页面，创建所有页面
	 */
	initPages() {
		let len = this.data.contentObj.dataArray.length;
		// 倒序，因为后添加的page，显示在前面
		for (let i = len - 1; i >= 0; i--) {
			let node = cc.instantiate(this.pfbItemPage);
			node.parent = this.nodLayerPages;
			let comp = node.getComponent('ItemPage');
			comp.setInfo(this.data.contentObj.dataArray[i], i);
			this._pagesList[i] = comp;
			if (i !== 0) {
				comp.showMask();
			}
		}
		this.scheduleOnce(()=>{
			EventMgr.emit('refreshMask')
		})
	},

	// 下一页
	onPageDown() {
		if (GameData._isPageTurning) {
			return;
		}
		// 已经是最后一页了
		let len = this.data.contentObj.dataArray.length;
		if (GameData._currPageIndex + 1 >= len) {
			return;
		}
		this.showPageMask(GameData._currPageIndex + 1);
		this.hidePageMaskAction(GameData._currPageIndex + 1);
		this.stopPageAudio(GameData._currPageIndex);
		this.stopPageAudio(GameData._currPageIndex + 1);
		this._pagesList[GameData._currPageIndex].playPageDown();
		GameData._currPageIndex++;
		GameData._isPageTurning = true;
		this.scheduleOnce(this.onPageDownDone, 0.75)
		this._pagesList[GameData._currPageIndex].onCurrPage();
		cc.audioEngine.play(this.audTurnPage);
	},
	// 上一页
	onPageUp() {
		if (GameData._isPageTurning) {
			return;
		}
		// 已经是第一页了
		if (GameData._currPageIndex == 0) {
			return;
		}
		GameData._currPageIndex--;
		this.hidePageMask(GameData._currPageIndex + 1);
		this.showPageMaskAction(GameData._currPageIndex + 1);
		this.stopPageAudio(GameData._currPageIndex);
		this.stopPageAudio(GameData._currPageIndex + 1);
		this._pagesList[GameData._currPageIndex].playPageUp();
		GameData._isPageTurning = true;
		this.scheduleOnce(this.onPageUpDone, 0.75)
		this._pagesList[GameData._currPageIndex].onCurrPage();
		cc.audioEngine.play(this.audTurnPage);
	},
	// 显示下一页的黑色遮罩
	showPageMask(index) {
		let page = this._pagesList[index];
		if (!page) {
			return;
		}
		page.showMask();
	},
	// 隐藏下一页的黑色遮罩
	hidePageMask(index) {
		let page = this._pagesList[index];
		if (!page) {
			return;
		}
		page.hideMask();
	},
	showPageMaskAction(index) {
		let page = this._pagesList[index];
		if (!page) {
			return;
		}
		page.playShowMask();
	},
	hidePageMaskAction(index) {
		let page = this._pagesList[index];
		if (!page) {
			return;
		}
		page.playHideMask();
	},
	stopPageAudio(index) {
		let page = this._pagesList[index];
		if (!page) {
			return;
		}
		page.stopAudio();
	},

	onPageDownDone() {
		GameData._isPageTurning = false;
		this.refreshIndicator(true);
		EventMgr.emit('refreshMask')
	},

	onPageUpDone() {
		GameData._isPageTurning = false;
		this.refreshIndicator();
		EventMgr.emit('refreshMask')
	},

	refreshIndicator(isPageDown) {
		if (isPageDown) {
			this._indicatorList[GameData._currPageIndex] && this._indicatorList[GameData._currPageIndex].select();
			this._indicatorList[GameData._currPageIndex - 1] && this._indicatorList[GameData._currPageIndex - 1].unselect();
		} else {
			this._indicatorList[GameData._currPageIndex] && this._indicatorList[GameData._currPageIndex].select();
			this._indicatorList[GameData._currPageIndex + 1] && this._indicatorList[GameData._currPageIndex + 1].unselect();
		}
	},


















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

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

});
