// const tools = require("./tools");

cc.Class({
	extends: cc.Component,

	properties: {
		picNode: {
			type: cc.Node,
			default: null
		},
		picTempNode: {
			type: cc.Node,
			default: null
		},
		leftNode: {
			type: cc.Node,
			default: null
		},
		rightNode: {
			type: cc.Node,
			default: null
		},
		pageNumNode: {
			type: cc.Node,
			default: null
		},
		movepageNode: {
			type: cc.Node,
			default: null
		},
		btn_audio: {
			type: cc.Node,
			default: null
		},
		btnClip: cc.AudioClip
	},

	// 生命周期 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) => {
			if (data) {
				if (data.data) {
					this.data = data.data;
				} else {
					this.data = data;
				}
			} else {
				this.data = this.getDefaultData();
			}
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
		//init show
		this.picNode.opacity = 0
		this.leftNode.active = false
		this.rightNode.active = false
	},

	onEnable() {
		cc.systemEvent.on('playAudio', this.onPlayAudio, this)
	},

	onDisable() {
		cc.systemEvent.off('playAudio', this.onPlayAudio, this)
	},


	getData(func) {
		if (window && window.courseware) {
			window.courseware.getData(func, 'ww03');
			return;
		}

		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.getData(func);
			return;
		}

		func(this.getDefaultData());
	},

	getDefaultData() {
		// const dataJson = ' [{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/a962378295f3deb54e9f9329d59aa909.jpg","rect":{"x":427.1,"y":0,"width":1534.81,"height":892}},"hotZoneItemArr":[{"id":"1634813643232","index":0,"audio_url":"http://staging-teach.cdn.ireadabc.com/0b42398a12e1b2f075e9965e4d608765.mp3","itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":108.92,"y":450.35,"width":290.08,"height":290.08}},{"id":"1634813702995","index":1,"itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":493.28,"y":408.29,"width":290.08,"height":290.08}},{"id":"1634813712642","index":2,"audio_url":"http://staging-teach.cdn.ireadabc.com/784cd4188bf126d6c3c9395d9a807619.mp3","itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":789.18,"y":469.21,"width":290.08,"height":290.08}}]},{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/281406244e10356325f075522f016ceb.jpg","rect":{"x":427.1,"y":0,"width":1534.81,"height":892}},"hotZoneItemArr":[{"id":"1634813750668","index":0,"itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":637.6,"y":419.17,"width":100.08,"height":100.08}},{"id":"1634813772152","index":1,"itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":791.35,"y":398.86,"width":85.57,"height":85.57}},{"id":"1634813784384","index":2,"itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":898.68,"y":374.21,"width":82.67,"height":82.67}},{"id":"1634813800497","index":3,"itemType":"rect","fontScale":1.86640625,"imgScale":1,"mapScale":1.86640625,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":1030.67,"y":342.3,"width":73.97,"height":73.97}}]},{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/562f741288227a9a36a7ce63a152278e.jpg","rect":{"x":288.4,"y":0,"width":1058.19,"height":615}},"hotZoneItemArr":[{"id":"1634813836558","index":0,"audio_url":"http://staging-teach.cdn.ireadabc.com/7c1d1540233b6d050eae8215679104a8.mp3","itemType":"rect","fontScale":1.27734375,"imgScale":1,"mapScale":1.27734375,"gIdx":"1","useHand":true,"useBorder":true,"rect":{"x":9.6,"y":305,"width":69,"height":69}},{"id":"1634813857964","index":1,"audio_url":"http://staging-teach.cdn.ireadabc.com/495324991838775e49e3ca6593d432c9.mp3","itemType":"rect","fontScale":1.27734375,"imgScale":1,"mapScale":1.27734375,"gIdx":"1","useHand":true,"useBorder":true,"rect":{"x":115.6,"y":303,"width":67,"height":67}},{"id":"1634813868736","index":2,"audio_url":"http://staging-teach.cdn.ireadabc.com/3d0fea61d5d97f3caf04a9b738a0291b.mp3","itemType":"rect","fontScale":1.27734375,"imgScale":1,"mapScale":1.27734375,"gIdx":"1","useHand":true,"useBorder":true,"rect":{"x":209.6,"y":290,"width":65,"height":65}}]}]'
		const dataJson = '[{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/35bfd1d1342e1f2ea3db408afd072343.jpg","rect":{"x":651.79,"y":0,"width":471.43,"height":660}},"hotZoneItemArr":[{"id":"1636511068807","index":0,"audio_url":"http://staging-teach.cdn.ireadabc.com/989f78ee25c48624047f9f0275eb4193.mp3","itemType":"rect","fontScale":1.38671875,"imgScale":1,"mapScale":1.38671875,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":89.71,"y":329,"width":130,"height":130}},{"id":"1636536972082","index":1,"audio_url":"http://staging-teach.cdn.ireadabc.com/3e5c5d427828a8d65bf3f980e954da0c.mp3","itemType":"rect","fontScale":1.38671875,"imgScale":1,"mapScale":1.38671875,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":275.71,"y":370,"width":200,"height":200}},{"id":"1636536992261","index":2,"audio_url":"http://staging-teach.cdn.ireadabc.com/130feba39f7665f46adfc6765f86c6cd.mp3","itemType":"rect","fontScale":1.38671875,"imgScale":1,"mapScale":1.38671875,"gIdx":"0","useHand":true,"useBorder":true,"rect":{"x":135.71,"y":230,"width":200,"height":200}}]}]'
		const data = JSON.parse(dataJson);
		return data;
	},

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

	addPreload() {
		let item
		for (let i = 0; i < this.data.length; i++) {
			item = this.data[i]
			if (!item.bgItem) {
				this.data.splice(i, 1)
				continue
			}
			this._imageResList.push({ url: item.bgItem.url })
			for (let item of item.hotZoneItemArr) {
				item.pic_url && this._imageResList.push({ url: item.pic_url })
				item.audio_url && this._audioResList.push({ url: item.audio_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;
		this.onHomeworkFinish();
	},

	initView() {
		this.initBg();
		this.initPic();
		this.initEvent();
	},
	initEvent() {
		this.movepageNode.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this)
		cc.systemEvent.on('stopAutoPlay', this.stopAll, this);
	},

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

	initPic() {
		this.picNode.opacity = 0
		cc.Tween.stopAllByTarget(this.picNode)
		cc.tween(this.picNode).to(1, { opacity: 255 }, { easing: 'cubicInOut' }).start()
		this.curPage = 0
		if (this.data.length == 1) {
			this.leftNode.active = false
			this.rightNode.active = false
		} else {
			this.leftNode.active = false
			this.rightNode.active = true
		}
		this.setContent(this.picNode, this.data[0])
	},
	curPage: null,

	onTouchEnd(e) {
		let touch = e.touch;
		let startPoint = touch.getStartLocation();
		let endPoint = touch.getLocation();
		let moveX = endPoint.x - startPoint.x;
		if (moveX < -100) {
			this.onClickRight();
		} else if (moveX > 100) {
			this.onClickLeft();
		}
	},

	onClickRight() {
		if (!this._cantouch) {
			return;
		}

		this.curPage += 1
		if (this.curPage == this.data.length) {
			this.curPage = 0
		};

		if (this.curPage == 1) {
			this.leftNode.active = true
			this.leftNode.scale = 1
		}

		if (this.curPage == this.data.length - 1) {
			this.rightNode.active = false
		}

		this.leftMove()

		cc.audioEngine.play(this.btnClip, false, 0.5)
	},

	onClickLeft() {
		if (!this._cantouch) {
			return;
		}
		this.curPage -= 1
		if (this.curPage < 0) {
			this.curPage = this.data.length - 1;
		}
		if (this.curPage == 0) {
			this.leftNode.active = false
		}

		if (this.curPage == this.data.length - 1) {
			this.rightNode.active = true
			this.rightNode.scale = 1
		}
		this.rightMove()

		cc.audioEngine.play(this.btnClip, false, 0.8)
	},
	//绑定音频按钮，点击按钮播放，再次点击按钮暂停
	onClickAudio(e) {
		if (this.isPlaying) {
			this.stopAll();
		} else {
			this.playAll();
		}
	},
	playAll() {
		this.stopAudio()
		this.isPlaying = true;
		let btn_loop = this.btn_audio.getComponent("btn_loop");//找到btn_loop
		btn_loop.startPlay();//执行播放的方法

		if (!this._playAllData) {
			this._playAllData = {
				currentPageIdx: this.curPage,
				currentPicIdx: 0,
				currentAudioId: null
			}
		}
		if (this.curPage != this._playAllData.currentPageIdx) {
			this._playAllData.currentPageIdx = this.curPage;
			this._playAllData.currentPicIdx = 0;
			this._playAllData.currentAudioId = null;
		}

		const picNodeComponent = this.picNode.getComponent('picNode');
		const hitItemComponent = picNodeComponent._items.children[this._playAllData.currentPicIdx].getComponent('hitItem');
		hitItemComponent.showBox();

		if (this._playAllData.currentAudioId === null) {
			const url = this.data[this._playAllData.currentPageIdx].hotZoneItemArr[this._playAllData.currentPicIdx].audio_url;
			if (!url) {
				hitItemComponent.hideBox();
				this._playAllData.currentPicIdx++;
				if (this._playAllData.currentPicIdx >= this.data[this._playAllData.currentPageIdx].hotZoneItemArr.length) {
					this._playAllData = null;
					this.stopAll();
				} else {
					this._playAllData.currentAudioId = null;
					this.playAll();
				}
			} else {
				cc.assetManager.loadRemote(url, (err, audioClip) => {
					if (err) return
					if (!this.isPlaying) return
					this._playAllData.currentAudioId = cc.audioEngine.play(audioClip, false, 0.8);
					cc.audioEngine.setFinishCallback(this._playAllData.currentAudioId, () => {
						const picNodeComponent = this.picNode.getComponent('picNode');
						const hitItemComponent = picNodeComponent._items.children[this._playAllData.currentPicIdx].getComponent('hitItem');
						hitItemComponent.hideBox();
	
						this._playAllData.currentPicIdx++;
						if (this._playAllData.currentPicIdx >= this.data[this._playAllData.currentPageIdx].hotZoneItemArr.length) {
							this._playAllData = null;
							this.stopAll();
						} else {
							this._playAllData.currentAudioId = null;
							this.playAll();
						}
					});
				});
			}
		} else {
			cc.audioEngine.resume(this._playAllData.currentAudioId);
		}
	},
	stopAll() {
		this.isPlaying = false;
		let btn_loop = this.btn_audio.getComponent("btn_loop");//找到btn_loop
		btn_loop.stopPlay();//执行暂停的方法

		const picNodeComponent = this.picNode.getComponent('picNode');
		picNodeComponent._items.children.forEach(item => {
			const hitItemComponent = item.getComponent('hitItem')
			hitItemComponent.hideBox();
		});

		if (this._playAllData && this._playAllData.currentAudioId !== undefined) {
			cc.audioEngine.pause(this._playAllData.currentAudioId);
		}
	},
	/** 左移动 */
	leftMove() {
		this.stopAll();
		this.stopAudio()
		this._cantouch = false;
		let width = cc.winSize.width + 64
		this.picNode.x = 0
		this.picTempNode.x = width
		this.setContent(this.picTempNode, this.data[this.curPage])
		cc.tween(this.picNode)
			.to(1, { x: -width }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.picTempNode)
			.to(1, { x: 0 }, { easing: 'cubicInOut' })
			.call(() => {
				let temp = this.picNode
				this.picNode = this.picTempNode
				this.picTempNode = temp
				this._cantouch = true;
			})
			.start();
	},

	/** 右移动 */
	rightMove() {
		this.stopAll();
		this.stopAudio()
		this._cantouch = false;
		let width = cc.winSize.width + 64
		this.picNode.x = 0
		this.picTempNode.x = -width
		this.setContent(this.picTempNode, this.data[this.curPage])
		cc.tween(this.picNode)
			.to(1, { x: width }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.picTempNode)
			.to(1, { x: 0 }, { easing: 'cubicInOut' })
			.call(() => {
				let temp = this.picNode
				this.picNode = this.picTempNode
				this.picTempNode = temp
				this._cantouch = true
			})
			.start();
	},
	stopAudio() {
		cc.systemEvent.emit('stopMusic')
	},

	// ------------------------------------------------
	/**设置显示区域内容 */
	setContent(picNode, data) {
		if (!data) {
			console.log('数据错误')
			return
		}
		let isAllNotAudio = data.hotZoneItemArr.every(dt => {
			return !!!dt.audio_url
		})
		if (isAllNotAudio) {
			this.btn_audio.active = false;
		} else {
			this.btn_audio.active = true;
		}
		picNode.getComponent('picNode').initWithData(data)
	},

	onHomeworkFinish() {
		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			if (middleLayerComponent.role == 'student') {
				middleLayerComponent.onHomeworkFinish(() => { });
			}
		} else {
			console.log('onHomeworkFinish');
		}
	},

	// ------------------------------------------
	update() {
		if (this.data) {
			this.pageNumNode.getChildByName("text").getComponent(cc.Label).string = (this.curPage % this.data.length + 1) + "/" + this.data.length
		}
	}
});
//3.自动连读