const saveKey = "DataKey_Cocos_FT14";
const BaseUI = require('BaseUI');
import { DefaultData } from '../script/DefaultData';
import { jelly, onHomeworkFinish } from "../script/utils";

const POS = {
	LeftPage: { x: -239, y: -5 },
	RightPage: { x: 239, y: -5 },
}
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._timeoutIds = [];
		this._intervalIds = [];
		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;

		return {"haveCover":false,"coverType":"Image","coverImage":"","coverAudio":"","coverText":"","coverDragonBone":{"skeJsonData":{"url":""},"texJsonData":{"url":""},"texPngData":{"url":""}},"titleAudio":"","titleText":"","titleTextColor":"A","pageList":[{"pageType":"Image","pageAudio":"http://staging-teach.cdn.ireadabc.com/cc5b1a8730bc275ecac85185d5ce2c5b.mp3","pageText":"","pageImage":"","textColor":"A","pageDragonBone":{"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/679fed26daa464819d553de6331b3552.json","name":"alien-pro.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/65d8214c6b5c5d0496e17adb0408276a.atlas","name":"alien-pro.atlas"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/a319b372899239325b90bb4ec07b4970.png","name":"alien-pro.png"},"animType":"spine"}},{"pageType":"Image","pageAudio":"http://staging-teach.cdn.ireadabc.com/fd877ad376fdffdb0dfc62122065a78f.mp3","pageText":"","pageImage":"","textColor":"A","pageDragonBone":{"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/d1f859d3fba84bd03565e543c986fb28.json","name":"6_4_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/70f96e1cc7f013e27ed1952c503fb750.json","name":"6_4_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/b06f9b90018a6eb0175a01e355b9ced6.png","name":"6_4_tex.png"},"animType":"dragonBone"}},{"pageType":"Image","pageAudio":"http://staging-teach.cdn.ireadabc.com/dff6748c93f6bf3de8cb7105fa9ba5de.mp3","pageText":"","pageImage":"","textColor":"A","pageDragonBone":{"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/a278a56fe77dfade7366829e9c65c815.json","name":"6_3_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/96680527a570cec4d7c9818c91ec434a.json","name":"6_3_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/5c441810b0a5bc73248c50d8c32b4899.png","name":"6_3_tex.png"},"animType":"dragonBone"}}]}
	},

	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) => {
			if (window && window["air"]) {
				// cc.find('Canvas').opacity = 0;
				window.air.onCourseInScreen = (next) => {
					// cc.find('Canvas').opacity = 255;
					this.loadEnd();
					next();
				}
				window.air.hideAirClassLoading();
			} else {
				this.loadEnd();
			}

			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) {
				onHomeworkFinish();
				return resolve('');
			}
			GameData.isPlaying = true;
			let itemPage = page.getComponent('ItemPage');
			itemPage.playAudio();
			itemPage.playSpine().then(() => {
				if (this.pageList.length - GameData.pageIndex <=2) {
					onHomeworkFinish();
				}
				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.initArrowBtn();
		this.initPages().then(() => {
			this.updateBtnStatus();
			this.autoPlay();
		});
	},
	initArrowBtn() {
		const lastBtn = this.lastBtn = cc.find("Canvas/left_arrow");
		const nextBtn = this.nextBtn = cc.find("Canvas/right_arrow");

		lastBtn.on("touchstart", () => {
			const isSuccess = this.onTouchPanelLeft();
			isSuccess && jelly(lastBtn);
		})

		nextBtn.on("touchstart", () => {
			const isSuccess = this.onTouchPanelRight();
			isSuccess && jelly(nextBtn);
		})
	},
	checkShowArrowBtn() {
		setTimeout(() => {
			this.lastBtn.active = !this.nodeDict.btnLast.children[1].active;
			this.nextBtn.active = !this.nodeDict.btnNext.children[1].active;
		}, 220);

	},
	autoPlay() {
		//自动开始播放动画，及触发动画效果
		this.inited = false;
		this.onTouchLeft().then(() => {
			this.onTouchRight().then(() => {
				this.inited = true;
				this.isTruning = false
			})
		});
	},
	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() {

		if (this.isTruning) {
			return false;
		}
		if (GameData.isPlaying) {
			return false;
		}
		this.onTurnLast();
		this._timeoutIds.push(setTimeout(() => {
			this.autoPlay();
		}, 1000));
		return true;
	},
	onTouchPanelRight() {

		if (this.isTruning) {
			return false;
		}
		if (GameData.isPlaying) {
			return false;
		}
		this.onTurnNext();
		this._timeoutIds.push(setTimeout(() => {
			this.autoPlay();
		}, 1000));
		return true;
	},


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

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

		this.isTruning = true;

		if (this.verletRender) {
			this.verletRender.node.destroy();
			this.verletRender = null;
		}
		this.playAudioTurnPage();
		this._angle = 0
		let page0 = this.pageList[GameData.pageIndex + 1];
		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;
		cc.tween(page1)
			.to(1, { opacity: 0 })
			.start();

		let page2 = this.pageList[GameData.pageIndex - 1];
		if (page2) {
			page2.opacity = 0;
			// spf2 = this.capture.doCapture(page2);
			// page2.opacity = 0;
			// this.scheduleOnce(() => {
			page2.x = POS.RightPage.x;
			// })

			if (page0) {
				cc.tween(page0)
					// .delay(1)
					.to(1, { opacity: 0 })
					.start();
			}

			cc.tween(page2)
				// .delay(1)
				.to(1, { opacity: 255 })
				.call(() => {
					this.resetPages()
				})
				.start();

		}
		let page3 = this.pageList[GameData.pageIndex - 2]
		if (page3) {
			// this.scheduleOnce(() => {
			page3.opacity = 0;
			// })

			cc.tween(page3)
				// .delay(1)
				.to(1, { opacity: 255 })
				.call(() => {
				})
				.start();
		}


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

		this.isTruning = true;

		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 page0 = this.pageList[GameData.pageIndex]

		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;

		cc.tween(page1)
			.to(1, { opacity: 0 })

			.start();

		let page2 = this.pageList[GameData.pageIndex + 2]
		if (page2) {
			page2.opacity = 0;
			// spf2 = this.capture.doCapture(page2, true);
			// page2.opacity = 0;
			// this.scheduleOnce(() => {
			page2.x = POS.LeftPage.x;
			// })

			cc.tween(page0)
				// .delay(1)
				.to(1, { opacity: 0 })
				.start();

			cc.tween(page2)
				// .delay(1)
				.to(1, { opacity: 255 })
				.call(() => {
					this.resetPages()
				})
				.start();
		}
		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 (this.isTruning) {
			return;
		}
		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--;
			})
		});
	},
	_timeoutIds: null,
	_intervalIds: null,
	// 生命周期
	onDestroy() {
		this._timeoutIds.forEach(id => {
			clearTimeout(id);
		});
		this._intervalIds.forEach(id => {
			clearInterval(id);
		});
	},

});
