const { exchangeNodePos2 } = require("./utils");

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._currPageIndex = 0;
		this._startX = 0;
		this._endX = 0;
		this._pagesList = [];
		this._indicatorList = [];
		this._imageResList = [];
		this._audioResList = [];
		this._animaResList = [];
		window.GameData = {};
		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":"没 有 数 据","image_url":""},{"type":"Spine","text":"没 有 数 据","image_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) => {
			cc.audioEngine.play(clip, true, 1);
		});
	},

	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() {
		console.log(this.data)
		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');
				if (i == 0) {
					comp.setSelected();
				} else {
					comp.setUnselected();
				}
				comp.setNum(i + 1);
			}
			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();
			}
		}
	},

	// 下一页
	onPageDown() {
		if (GameData._isPageTurning) {
			return;
		}
		// 已经是最后一页了
		let len = this.data.contentObj.dataArray.length;
		if (this._currPageIndex + 1 >= len) {
			return;
		}
		this.showPageMask(this._currPageIndex + 1);
		this.hidePageMaskAction(this._currPageIndex + 1);
		this.stopPageAudio(this._currPageIndex);
		this.stopPageAudio(this._currPageIndex + 1);
		this._pagesList[this._currPageIndex].playPageDown();
		this._currPageIndex++;
		GameData._isPageTurning = true;
		this.scheduleOnce(this.onPageDownDone, 0.75)
		this._pagesList[this._currPageIndex].onCurrPage();
		cc.audioEngine.play(this.audTurnPage);
	},
	// 上一页
	onPageUp() {
		if (GameData._isPageTurning) {
			return;
		}
		// 已经是第一页了
		if (this._currPageIndex == 0) {
			return;
		}
		this._currPageIndex--;
		this.hidePageMask(this._currPageIndex + 1);
		this.showPageMaskAction(this._currPageIndex + 1);
		this.stopPageAudio(this._currPageIndex);
		this.stopPageAudio(this._currPageIndex + 1);
		this._pagesList[this._currPageIndex].playPageUp();
		GameData._isPageTurning = true;
		this.scheduleOnce(this.onPageUpDone, 0.75)
		this._pagesList[this._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);
	},

	onPageUpDone() {
		GameData._isPageTurning = false;
		this.refreshIndicator();
	},

	refreshIndicator(isPageDown) {
		if (isPageDown) {
			this._indicatorList[this._currPageIndex] && this._indicatorList[this._currPageIndex].select();
			this._indicatorList[this._currPageIndex - 1] && this._indicatorList[this._currPageIndex - 1].unselect();
		} else {
			this._indicatorList[this._currPageIndex] && this._indicatorList[this._currPageIndex].select();
			this._indicatorList[this._currPageIndex + 1] && this._indicatorList[this._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();
					});
				}
			});
		}
	},

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

});
