const saveKey = "DataKey_Cocos_FT14";
const BaseUI = require('BaseUI');
import { DefaultData } from './DefaultData';
import EventMgr from './EventMgr';
import VerletRender from "./verlet-render";
import BezierRender from "./bezier-render";
const POS = {
	LeftPage: { x: -238, y: 62 },
	RightPage: { x: 238, y: 62 },
}
cc.Class({

	extends: BaseUI,

	properties: {
		testPanel: cc.Node,
		touchPanel: cc.Node,
		audTurnPage: cc.AudioClip,
		pfbItemPage: cc.Prefab,
		pfbItemTurnPage: cc.Prefab,
		pfbItemTurnPage2: cc.Prefab,
		tipFirst: cc.Node,
		tipLast: cc.Node,
		// verletRender: VerletRender,
		capture: require('capture_to_web'),
	},

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

	onEnable() {

	},

	onDisable() {

	},

	_resList: null,
	initSceneData() {
		this._resList = [];
		window.GameData = {};
	},

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {

	},


	// 生命周期 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() {
		let data = DefaultData;
		return data;
	},

	preloadItem() {
		this.addPreloadItem();
		this.preload();
	},

	addPreloadItem() {
		this._resList.push({ url: this.data.coverImage });
		this._resList.push({ url: this.data.coverDragonBone.skeJsonData.url });
		this._resList.push({ url: this.data.coverDragonBone.texJsonData.url });
		this._resList.push({ url: this.data.coverDragonBone.texPngData.url });
		this._resList.push({ url: this.data.titleAudio });
		for (let i = 0; i < this.data.pageList.length; i++) {
			this._resList.push({ url: this.data.pageList[i].pageAudio });
			this._resList.push({ url: this.data.pageList[i].pageImage });
			this._resList.push({ url: this.data.pageList[i].pageDragonBone.skeJsonData.url });
			this._resList.push({ url: this.data.pageList[i].pageDragonBone.texJsonData.url });
			this._resList.push({ url: this.data.pageList[i].pageDragonBone.texPngData.url });
		}
	},

	preload() {
		cc.assetManager.loadAny(this._resList, null, null, (err, data) => {
			this.loadEnd();
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}

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


	loadEnd() {
		this.initDataBoot();
		this.initData();
		this.initEvent();
		this.startGame();
	},

	initDataBoot() {
		GameData.pageIndex = 0;
		this.pageList = [];
		this._turnLeft = false;
		this._turnRight = false;
		this._angle = 0;
	},
	onTouchLeft() {
		return new Promise((resolve, reject) => {
			if (this.verletRender) {
				return resolve('');
			}
			if (GameData.isPlaying) {
				return resolve('');
			}
			GameData.isPlaying = true;
			let page = this.pageList[GameData.pageIndex];
			let itemPage = page.getComponent('ItemPage');
			itemPage.playAudio();
			itemPage.playSpine().then(() => {
				resolve('');
			})
		});
	},
	onTouchRight() {
		return new Promise((resolve, reject) => {
			if (this.verletRender) {
				return resolve('');
			}
			if (GameData.isPlaying) {
				return resolve('');
			}

			let page = this.pageList[GameData.pageIndex + 1];
			if (!page) {
				return;
			}
			GameData.isPlaying = true;
			let itemPage = page.getComponent('ItemPage');
			itemPage.playAudio();
			itemPage.playSpine().then(() => {
				resolve('');
			})
		});
	},
	initData() {
		this.data.haveCover = false;
		// 所有全局变量 默认都是null 
		GameData.audioCount = 0;
		this.initTitle();
	},
	initEvent() {
		// this.touchPanel._touchListener && this.touchPanel._touchListener.setSwallowTouches(false);
		// this.touchPanel._touchListener.swallowTouches = false;
		this.touchPanel.on(cc.Node.EventType.TOUCH_END, this.onTouchPanel, this)
	},
	cons(data) {
		console.log(`${this.touchPanel._touchListener.swallowTouches}  |  ` + "btn->" + data)
	},



	startGame() {
		// this.playAudioEntrer();
		this.initPageUI();
		this.initPages().then(() => {
			this.updateBtnStatus();
			this.autoPlay();
		});
	},
	autoPlay() {
		//自动开始播放动画，及触发动画效果
		this.inited = false;
		this.onTouchLeft().then(() => {
			this.onTouchRight().then(() => {
				this.inited = true;
			})
		});
	},
	initTitle() {
		// let label = this.nodeDict.labTitle.getComponent(cc.Label);
		// label.string = this.data.titleText;
		// label._forceUpdateRenderData();
		// if (this.nodeDict.labTitle.width > 250) {
		// 	this.nodeDict.labTitle.scale = 250 / this.nodeDict.labTitle.width
		// }
	},
	initPageUI() {
		if (this.data.haveCover) {
			this.nodeDict.nodUI1.active = false;
			this.nodeDict.nodUI2.active = true;
		} else {
			this.nodeDict.nodUI1.active = true;
			this.nodeDict.nodUI2.active = false;
		}
	},
	initPages() {
		return new Promise((resolve, reject) => {
			this.pageIndex = 0;
			if (this.data.pageList.length === 0) return resolve('');

			let count = this.data.pageList.length;
			let node = cc.instantiate(this.pfbItemPage);
			node.parent = this.nodeDict.nodPages;
			let itemPage = node.getComponent('ItemPage');
			itemPage.init(this.data.pageList[0], false, this.pageIndex).then(() => {
				count--;
				if (count == 0) return resolve('');
			});
			this.pageList.push(node);
			this.pageIndex++;
			node.zIndex = -1;
			node.x = POS.LeftPage.x;
			node.y = POS.LeftPage.y;
			for (let i = 1; i < this.data.pageList.length; i++) {
				let node = cc.instantiate(this.pfbItemPage);
				node.parent = this.nodeDict.nodPages;
				let itemPage = node.getComponent('ItemPage');
				itemPage.init(this.data.pageList[i], false, this.pageIndex).then(() => {
					count--;
					if (count == 0) return resolve('');
				});
				this.pageList.push(node);
				node.x = POS.RightPage.x;
				node.y = POS.RightPage.y;
				this.pageIndex++;
				node.zIndex = -1 - i;
			}
			this.resetPages();
		});
	},
	onTouchPanel(e) {
		if (!this.inited) return;
		//滑动监听以及单击监听， 通过使用节点与panel碰撞来进行判断
		let evt = e;
		let target = e.target;
		let touches = evt.getTouches();
		let startPoint = touches[0].getStartLocation();
		let point = touches[0].getLocation();
		let moveX = point.x - startPoint.x;
		if (Math.abs(moveX) < 50) {
			//点击
			this.onTouchPanelClick(target, point);
		} else if (moveX > 0) {
			//向右滑
			this.onTouchPanelLeft();
		} else {
			//向左滑
			this.onTouchPanelRight();
		}
	},
	onTouchPanelClick(target, point) {
		let pointXY = new cc.Vec2(point.x - (1280 / 2), point.y - (720 / 2));
		let leftPanel = this.nodeDict.nodLeftPage;
		let rightPanel = this.nodeDict.nodRightPage;
		let rectLeft = new cc.Rect(leftPanel.position.x, leftPanel.position.y, leftPanel.width, leftPanel.height)
		let rectRight = new cc.Rect(rightPanel.position.x, rightPanel.position.y, rightPanel.width, rightPanel.height)
		if (this.contains(rectLeft, pointXY)) {
			//与左侧相交
			this.onTouchLeftAni();
		} else if (this.contains(rectRight, pointXY)) {
			//与右侧相交
			this.onTouchRightAni();
		}
	},
	contains(rect, point) {
		let mx = Math.abs(point.x - rect.x);
		let my = Math.abs(point.y - rect.y);
		return mx * 2 <= rect.width && my * 2 <= rect.height
	},
	onTouchLeftAni() {
		this.onTouchLeft();
	},
	onTouchRightAni() {
		this.onTouchRight();
	},
	onTouchPanelLeft() {
		this.onTurnLast();
	},
	onTouchPanelRight() {
		this.onTurnNext();
	},


	playAudioEntrer() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audEnter, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
			this.playAudioQuestion();
		})
	},
	playAudioPage(isBtn, cb) {
		GameData.audioCount++;
		let url = this.data.questionList[GameData.questionIndex].pageAudio;
		// url = 'http://127.0.0.1/iamflying.mp3';
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				console.log(err)
				this.startStepDone();
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				GameData.audioCount--;
				cb && cb();
				if (!isBtn) {
					this.startStepDone();
				}
			})
		});
	},
	playAudioQuestion() {
		GameData.audioCount++;
		let url = this.data.questionAudio;
		// url = 'http://127.0.0.1/iamflying.mp3';
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				console.log(err)
				return;
			}
			let id = cc.audioEngine.play(clip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				GameData.audioCount--;
				this.playAudioPage();
			})
		});
	},

	updateBtnStatus() {
		if (GameData.pageIndex <= 0) {
			this.nodeDict.btnLast.children[1].active = true;
		} else {
			this.nodeDict.btnLast.children[1].active = false;
		}
		if (GameData.pageIndex >= this.data.pageList.length - 2) {
			this.nodeDict.btnNext.children[1].active = true;
		} else {
			this.nodeDict.btnNext.children[1].active = false;
		}
	},

	checkCover() {
		if (!this.data.haveCover) {
			return;
		}
		if (GameData.pageIndex === -1) {
			this.nodeDict.nodUI1.active = false;
			this.nodeDict.nodUI2.active = true;
		}
	},

	playAudioTurnPage() {
		GameData.audioCount++;
		let id = cc.audioEngine.play(this.audTurnPage, false, 1);
		cc.audioEngine.setFinishCallback(id, () => {
			GameData.audioCount--;
		})
	},

	onTurnLast() {
		if (GameData.pageIndex <= 0) {
			this.tipAni(this.tipFirst);
			return;
		}
		if (this.verletRender) {
			this.verletRender.node.destroy();
			this.verletRender = null;
		}
		this.playAudioTurnPage();
		this._angle = 0
		let page1 = this.pageList[GameData.pageIndex];
		let spf1 = this.capture.doCapture(page1, true);
		this.scheduleOnce(() => {
			page1.opacity = 0;
			page1.x = POS.RightPage.x;
		})
		let spf2 = spf1;
		let page2 = this.pageList[GameData.pageIndex - 1];
		if (page2) {
			page2.opacity = 255;
			spf2 = this.capture.doCapture(page2);
			page2.opacity = 0;
			this.scheduleOnce(() => {
				page2.x = POS.RightPage.x;
			})
		}
		let page3 = this.pageList[GameData.pageIndex - 2]
		if (page3) {
			this.scheduleOnce(() => {
				page3.opacity = 255;
			})
		}
		let node = cc.instantiate(this.pfbItemTurnPage2);
		node.parent = this.node;
		node.opacity = 0;
		cc.tween(node)
			.to(0.1, { opacity: 255 })
			.to(1, { x: POS.LeftPage.x })
			.call(() => {
				this.checkCover();
			})
			.delay(1)
			.start()
		this.verletRender = node.getComponent(BezierRender);
		this.verletRender.textureList[0] = spf1._texture;
		this.verletRender.textureList[1] = spf2._texture;
		this.verletRender.updateAngle(this._angle);
		this.verletRender.init();
		this._turnLeft = true;
		this._turnRight = false;
		this.scheduleOnce(() => {
			this.verletRender.node.opacity = 255;
		})
		GameData.pageIndex -= 2;
		this.updateBtnStatus();
	},

	onTurnNext() {
		if (GameData.pageIndex >= this.data.pageList.length - 2) {
			this.tipAni(this.tipLast);
			return;
		}
		if (this.verletRender) {
			this.resetPages()
			this.verletRender.node.destroy();
			this.verletRender = null;
		}
		this.playAudioTurnPage();
		this.nodeDict.nodUI1.active = true;
		this.nodeDict.nodUI2.active = false;
		this._angle = 0
		let page1 = this.pageList[GameData.pageIndex + 1]
		let spf1 = this.capture.doCapture(page1);
		this.scheduleOnce(() => {
			page1.opacity = 0;
			page1.x = POS.LeftPage.x;
		})
		let spf2 = spf1;
		let page2 = this.pageList[GameData.pageIndex + 2]
		if (page2) {
			page2.opacity = 255;
			spf2 = this.capture.doCapture(page2, true);
			page2.opacity = 0;
			this.scheduleOnce(() => {
				page2.x = POS.LeftPage.x;
			})
		}
		let page3 = this.pageList[GameData.pageIndex + 3]
		if (page3) {
			this.scheduleOnce(() => {
				page3.opacity = 255;
			})
		}

		let node = cc.instantiate(this.pfbItemTurnPage);
		node.parent = this.node;
		node.opacity = 0;
		cc.tween(node)
			.to(0.1, { opacity: 255 })
			.to(1, { x: POS.RightPage.x })
			.start()
		this.verletRender = node.getComponent(BezierRender);
		this.verletRender.textureList[0] = spf1._texture;
		this.verletRender.textureList[1] = spf2._texture;
		this.verletRender.updateAngle(this._angle);
		this.verletRender.init();
		this._turnLeft = true;
		this._turnRight = false;
		this.scheduleOnce(() => {
			this.verletRender.node.opacity = 255;
		})
		GameData.pageIndex += 2;
		this.updateBtnStatus();
	},
	tipAni(node) {
		node.active = true;
		node.opacity = 0;
		cc.tween(node)
			.to(0.5, { opacity: 255 })
			.delay(0.5)
			.to(0.5, { opacity: 0 })
			.call(() => {
				node.active = false;
			})
			.start()
	},
	buttonListener(button) {
		if (button.node.name == 'btnLast') {
			this.onTurnLast();
		} else if (button.node.name == 'btnNext') {
			this.onTurnNext();
		} else if (button.node.name == 'btnTitle') {
			this.playTitleAudio();
		}
	},

	resetPages() {
		for (let i = 0; i < this.pageList.length; i++) {
			this.pageList[i].opacity = 0;
		}
		if (this.pageList[GameData.pageIndex]) {
			this.pageList[GameData.pageIndex].opacity = 255;
		}
		if (this.pageList[GameData.pageIndex + 1]) {
			this.pageList[GameData.pageIndex + 1].opacity = 255;
		}
	},

	update(dt) {
		let anglePerDt = 180
		if (this._turnLeft) {
			this._angle += dt * anglePerDt
			if (this._angle > 180) {
				this._angle = 180
				this._turnLeft = false
				cc.tween(this.verletRender.node)
					.call(() => {
						this.resetPages()
					})
					.to(0.5, { opacity: 0 })
					.call(() => {
						if (this.verletRender) {
							this.verletRender.node.destroy();
							this.verletRender = null;
						}
					})
					.start()
			}
			this.verletRender.updateAngle(this._angle)
		}
		if (this._turnRight) {
			this._angle -= dt * anglePerDt
			if (this._angle < 0) {
				this._angle = 0
				this._turnRight = false
				cc.tween(this.nodeDict.sprPage)
					.call(() => {
						this.resetPages()
					})
					.to(0.5, { opacity: 0 })
					.call(() => {
						if (this.verletRender) {
							this.verletRender.node.destroy();
							this.verletRender = null;
						}
					})
					.start()
			}
			this.verletRender.updateAngle(this._angle)
		}
	},

	playTitleAudio() {
		GameData.audioCount++;
		let url = this.data.titleAudio;
		cc.audioEngine.stop(this.titleAudioId);
		cc.assetManager.loadRemote(url, null, (err, clip) => {
			if (err) {
				console.log(err)
				return;
			}
			this.titleAudioId = cc.audioEngine.play(clip, false, 1);
			cc.audioEngine.setFinishCallback(this.titleAudioId, () => {
				if (!cc.isValid(this)) {
					return;
				}
				GameData.audioCount--;
			})
		});
	},
});
