import { asyncDelay, RandomInt } from "../script/util";

cc.Class({

	extends: cc.Component,

	properties: {
		dataLabel: {
			type: cc.Label,
			default: null
		},
		picNode: {
			type: cc.Node,
			default: null
		},
		picTempNode: {
			type: cc.Node,
			default: null
		},
		leftNode: {
			type: cc.Node,
			default: null
		},
		rightNode: {
			type: cc.Node,
			default: null
		},
		playAnim: {
			type: cc.Animation,
			default: null
		},
		TopBoxNode: cc.Node,
		clips: [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) => {
			console.log('data:', data);
			if (data == null || data == undefined || data.length == 0 || data.length == undefined) {
				this.data = this.getDefaultData()
			} else {
				this.data = data
			}
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
		//init show
		this.TopBoxNode.opacity = 0
		this.picNode.opacity = 0
		this.leftNode.active = false
		this.rightNode.active = false
	},

	onEnable() {
		this.rightNode.on(cc.Node.EventType.MOUSE_DOWN, this.changeIcon.bind(this, this.rightNode, true))
		this.rightNode.on(cc.Node.EventType.MOUSE_UP, this.changeIcon.bind(this, this.rightNode, false))
		this.rightNode.on(cc.Node.EventType.MOUSE_LEAVE, this.changeIcon.bind(this, this.rightNode, false))
		this.leftNode.on(cc.Node.EventType.MOUSE_DOWN, this.changeIcon.bind(this, this.leftNode, true))
		this.leftNode.on(cc.Node.EventType.MOUSE_UP, this.changeIcon.bind(this, this.leftNode, false))
		this.leftNode.on(cc.Node.EventType.MOUSE_UP, this.changeIcon.bind(this, this.leftNode, false))
	},

	onDisable() {
		this.rightNode.off(cc.Node.EventType.MOUSE_DOWN)
		this.rightNode.off(cc.Node.EventType.MOUSE_UP)
		this.rightNode.off(cc.Node.EventType.MOUSE_LEAVE)
		this.leftNode.off(cc.Node.EventType.MOUSE_DOWN)
		this.leftNode.off(cc.Node.EventType.MOUSE_UP)
		this.leftNode.off(cc.Node.EventType.MOUSE_LEAVE)
	},

	changeIcon(node, bl) {
		node.children[0].active = !bl
		node.children[1].active = bl
	},

	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 = '  [{"type":"0","txt":"对对对","pic_url":"http://staging-teach.cdn.ireadabc.com/ff3536cb7e11e2fa5f8b98425dc27735.png","audio_url":"http://staging-teach.cdn.ireadabc.com/6b13f8509a360476c26336029a1ce570.mp3"},{"txt":"11发发","pic_url":"http://staging-teach.cdn.ireadabc.com/e28666860c7d1ab255569201c6749a03.png"},{"txt":"11发发","pic_url":"http://staging-teach.cdn.ireadabc.com/e28666860c7d1ab255569201c6749a03.png"}]'
		const data = JSON.parse(dataJson);
		return data;
	},

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

	addPreload() {
		for (let one of this.data) {
			one.pic_url && this._imageResList.push({ url: one.pic_url })
			one.audio_url && this._audioResList.push({ url: one.audio_url })
		}
	},

	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.initView();
		// this.initListener();
	},

	_cantouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		this._cantouch = true;
	},

	initView() {
		this.initBg();
		this.initPic();
	},

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

	front: null,

	initPic() {
		this.fired = false
		this.front = true
		this.TopBoxNode.opacity = 0
		this.picNode.opacity = 0
		cc.Tween.stopAllByTarget(this.TopBoxNode)
		cc.Tween.stopAllByTarget(this.picNode)
		cc.tween(this.TopBoxNode).to(1, { opacity: 255 }, { easing: 'cubicInOut' }).start()
		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.setPic(this.picNode, this.data[0])
		this.dataLabel.string = (this.curPage + 1) + '/' + this.data.length
	},
	curPage: null,

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

		this.curPage += 1

		if (this.curPage == 1) {
			this.leftNode.active = true
			this.leftNode.children[0].active = true
			this.leftNode.children[1].active = false
			this.leftNode.scale = 1
		}

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

		this.leftMove()

		cc.audioEngine.play(this.clips[0], false, 0.5)
	},

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

		if (this.curPage == this.data.length - 2) {
			this.rightNode.active = true
			this.rightNode.children[0].active = true
			this.rightNode.children[1].active = false
			this.rightNode.scale = 1
		}
		this.rightMove()

		cc.audioEngine.play(this.clips[0], false, 0.8)
	},

	onClickAudio() {
		if (!this._cantouch) return
		let data = this.data[this.curPage]
		if (!data || !data.audio_url || data.audio_url == '') {
			if (this.curPage == this.data.length - 1) {
				this.showFire()
			}
			console.log('数据错误')
			return
		}

		this.stopAudio()
		cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
			this.audioId = cc.audioEngine.play(audioClip, false, 0.8);
			this.playAnim.play('playAudio')
			cc.audioEngine.setFinishCallback(this.audioId, () => {
				this.audioId = null
				this.playAnim.play('stopAudio')
				if (this.curPage == this.data.length - 1) {
					this.showFire()
				}
			});
		});
	},

	stopAudio() {
		if (this.audioId != null) {
			cc.audioEngine.stop(this.audioId)
			this.playAnim.node.opacity != 0 && this.playAnim.play('stopAudio')
			this.audioId = null
		}
	},

	onClickRotate() {
		this._cantouch = false
		let btn = this.picNode.getComponent(cc.Button)
		btn.enabled =false
		cc.Tween.stopAllByTarget(this.picNode)
		cc.tween(this.picNode).to(0.4, { scaleX: 0 }).call(() => {
			if (this.front) {
				this.setTxt(this.picNode, this.data[this.curPage])
			} else {
				this.setPic(this.picNode, this.data[this.curPage])
			}
			this.front = !this.front
		}).to(0.4, { scaleX: 1 }).call(() => {
			this._cantouch = true
			btn.enabled =true
		}).start()
		cc.audioEngine.play(this.clips[3], false)
	},

	fired: false,
	showFire() {
		return
		if (this.fired) return
		this.fired = true
		this.showAllFirework(cc.find("Canvas"), cc.find("paperBase").children)
		cc.audioEngine.play(this.clips[2], false)
	},

	// onClickReplay() {
	// 	if (!this._cantouch) return
	// 	this.stopAudio()
	// 	this.rightNode.active = true
	// 	this.leftNode.active = false
	// 	this.data.sort((a, b) => -0.5 + Math.random())
	// 	this._cantouch = false
	// 	cc.tween(this.TopBoxNode).to(0.4, { opacity: 0 }).start()
	// 	cc.tween(this.picNode).to(0.4, { opacity: 0 }).start()
	// 	this.replayAnim.play().wrapMode = cc.WrapMode.Reverse
	// 	this.replayAnim.once(cc.Animation.EventType.FINISHED, () => {
	// 		this.initPic()
	// 		this._cantouch = true
	// 	})
	// 	cc.audioEngine.play(this.clips[1], false, 0.5)
	// 	// 游戏结束时需要调用这个方法通知系统作业完成
	// 	onHomeworkFinish();
	// },

	/** 音频id */
	audioId: null,

	/** 左移动 */
	leftMove() {
		this.stopAudio()
		this._cantouch = false;
		let width = cc.winSize.width
		this.picNode.x = 0
		this.picTempNode.x = width
		this.front = true
		this.setPic(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.dataLabel.string = (this.curPage + 1) + '/' + this.data.length
				if (this.curPage == this.data.length - 1) {
					this._cantouch = true
					// 游戏结束时需要调用这个方法通知系统作业完成
					if (typeof (onHomeworkFinish) != "undefined") {
						onHomeworkFinish();
					}
				} else {
					this._cantouch = true;
				}
			})
			.start();
	},

	/** 右移动 */
	rightMove() {
		this.stopAudio()
		this._cantouch = false;
		let width = cc.winSize.width
		this.picNode.x = 0
		this.picTempNode.x = -width
		this.front = true
		this.setPic(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.dataLabel.string = (this.curPage + 1) + '/' + this.data.length
				this._cantouch = true
			})
			.start();
	},

	/** 设置图片 */
	setPic(picNode, data) {
		if (!data) {
			console.log('数据错误')
			return
		}
		picNode.children[4].getComponent(cc.Label).string = ''
		let sprite = picNode.children[2].getComponent(cc.Sprite)
		this.getSpriteFrimeByUrl(data.pic_url, (sp) => {
			let rect = sp.getRect()
			let scale = rect.width / rect.height
			let originScale = 65 / 41
			if (scale < originScale) {
				let width = rect.width / (rect.height / 410)
				picNode.width = width + 30
				picNode.height = 440
			} else if (scale > originScale) {
				let height = rect.height / (rect.width / 650)
				picNode.height = height + 30
				picNode.width = 680
			} else {
				picNode.width = 680
				picNode.height = 440
			}
			sprite.spriteFrame = sp
			let child = picNode.children[5]
			child.x = (picNode.width - child.width) / 2
			child.y = -(picNode.height - child.height) / 2
			picNode.scaleY =1
		})
	},
	/** 设置txt */
	setTxt(picNode, data) {
		if (!data) {
			console.log('数据错误')
			return
		}
		picNode.height = 410
		picNode.width = 650
		picNode.children[4].getComponent(cc.Label).string = data.txt
		picNode.children[2].getComponent(cc.Sprite).spriteFrame = null
		picNode.children[5].x = 273.5
		picNode.children[5].y = -178
		picNode.scaleY =1
	},

	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();
					});
				}
			});
		}
	},
	// ------------------------------------------
	async showAllFirework(parentNode, nodeList) {
		for (let i = 0; i < 6; i++) {
			this.showFirework(cc.v2(0, -parentNode.height / 2), parentNode, nodeList, parentNode.width * 2 / 3, parentNode.height * 1.3);
			await asyncDelay(0.1);
		}
	},

	showFirework(pos, parentNode, nodeList, width = 200, height = 200, number = 30) {
		for (let i = 0; i < number; i++) {
			const quad = this.createQuads(pos, parentNode, nodeList);
			const targetX = RandomInt(width / 2, -width / 2);
			const targetY = RandomInt(height);

			cc.tween(quad)
				.by(0.5, { x: targetX })
				.by(3, { x: targetX * 2 })
				.start();

			cc.tween(quad)
				.by(0.5, { y: targetY }, { easing: 'quadOut' })
				.to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
				.removeSelf()
				.start();

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

	createQuads(pos, parentNode, nodeList) {
		const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
		quadBase.x = pos.x;
		quadBase.y = pos.y;
		quadBase.z = pos.z;
		quadBase.angle = RandomInt(180);
		quadBase.parent = parentNode;

		const quad = quadBase.getChildByName('quad');
		quad.x = 0;
		quad.y = 0;
		quad.angle = RandomInt(180);

		const paper = quad.getChildByName('paper');
		paper.scaleX = Math.random() * 0.5 + 0.5;
		paper.scaleY = Math.random() * 0.5 + 0.5;

		quadBase.scaleX = Math.random();
		cc.tween(quadBase)
			.to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
			.call(() => {
				const time = Math.random() * 0.2;
				cc.tween(quadBase)
					.to(0.1 + time, { scaleX: -1 })
					.to(0.1 + time, { scaleX: 1 })
					.union()
					.repeatForever()
					.start();
			})
			.start();


		return quadBase;
	}
});
