import { onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";
import { itemData } from "./data";
import { hyLoader } from "./hyLoader";
import CardManager from "./cardManager";
import pg from "./pg";
import ani from "./ani";
import { asyncDelay, RandomInt, showFireworks } from "../script/utils";

cc.Class({

	extends: cc.Component,

	properties: {
	},

	// 生命周期 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);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
	},

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

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

		func(this.getDefaultData());
	},

	getDefaultData() {
		return itemData;
		// return defaultData;
	},

	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.initSingleData();
		this.initAudio();
		this.initView();
		// this.initListener();
	},
	//全局游戏
	_gameCode: null,
	initData() {
		//数据解析
		CardManager.getIns().initCards(this.data);
		CardManager.getIns().resetPageNum();
		CardManager.getIns().randomPageCards();
		this._gameCode = 0;
	},
	//单局游戏
	_cantouch: null,
	_cardPage: null,
	_cardLayout: null,
	_cardTouchItems: null,
	_successItems: null,
	initSingleData() {
		// 所有全局变量 默认都是null 
		this._cantouch = true;
		//界面用数据
		this._cardTouchItems = [];
		this._successItems = [];
		this._cardPage = CardManager.getIns().getPage();
		cc.log(this._cardPage);
	},
	initAudio() {
	},

	initView() {
		this.btn_replay = pg.view.find(this, "btn_replay");
		pg.view.visible(this.btn_replay, false);
		pg.view.touchOn(this.btn_replay, this.onTouchReplay, this);
		this.initStars();
		this.initLayout();
	},
	initStars() {
		// this.length = CardManager.getIns().getTestlet();
		// this.addStar();
	},
	initLayout() {
		pg.view.visible(this.btn_replay, false);
		pg.view.visible(pg.view.find(this, `layout_card_4`), false);
		pg.view.visible(pg.view.find(this, `layout_card_6`), false);
		pg.view.visible(pg.view.find(this, `layout_card_8`), false);
		pg.view.visible(pg.view.find(this, `layout_card_10`), false);
		this._cardLayout = pg.view.find(this, `layout_card_${this._cardPage.length}`);
		ani.scaleIn(this._cardLayout);
		pg.view.visible(this._cardLayout, true);
		for (let i = 0; i < this._cardPage.length; i++) {
			let data = this._cardPage[i];
			let item = pg.view.find(this._cardLayout, `item_${i}`);
			if (!data || !item || data.type == CardManager.TYPE_NULL) continue;
			this.updateItem(item, data);
		}
	},
	updateItem(item, data) {
		let img = pg.view.find(item, `img`);
		let txt = pg.view.find(item, `txt`);
		let audio = pg.view.find(item, `audio`);
		let box = pg.view.find(item, `box`);
		console.log(CardManager.TYPE_IMG);
		if (data.type == CardManager.TYPE_IMG) {
			pg.view.setNetImg(img, data.img);
			pg.view.visible(img, true);
			pg.view.visible(txt, false);
			pg.view.visible(audio, false);
		} else if (data.type == CardManager.TYPE_TXT) {
			pg.view.setString(txt, data.txt);
			pg.view.visible(img, false);
			pg.view.visible(txt, true);
			pg.view.visible(audio, false);
		} else if (data.type == CardManager.TYPE_MP3) {
			pg.view.visible(img, false);
			pg.view.visible(txt, false);
			pg.view.visible(audio, true);
			pg.view.visible(pg.view.find(item, `audio/btn_laba`), true);
		}
		item.scaleX = 1;
		item.scaleY = 1;
		pg.view.visible(box, false);
		item.attr({ data: data });
		pg.view.visible(item, true);
		pg.view.touchOn(item, this.onTouchItem, this);
	},
	onTouchItem(touch, info) {
		if (!this._cantouch) return;
		this._cantouch = false;
		let item = touch.target;
		let data = item.data;
		console.log(data);
		this._cardTouchItems.push(item);
		if (this._cardTouchItems.length == 2) {
			let item0 = this._cardTouchItems[0];
			let item1 = this._cardTouchItems[1];
			//检测重复点击   取消选中
			if (item0.data && item1.data && item0.data.cardId == item1.data.cardId) {
				pg.view.visible(pg.view.find(item, 'box'), false);
				this._cantouch = true;
			} else if (item0.data && item1.data && item0.data.cardDid == item1.data.cardDid) {
				//成功--变小 消失
				this._successItems.push(item0);
				this._successItems.push(item1);
				pg.view.visible(pg.view.find(item, 'box'), true);
				this.playSFX("audio_choice").then(() => {
					this.playAudioAni(item).then(() => {
						this.createRightAni(cc.v2(item0.x, item0.y));
						this.createRightAni(cc.v2(item1.x, item1.y));
						this.playSFX("audio_right").then(() => {
							this._cantouch = true;
							this.playAudioAni(item0).then(() => {
								this.playAudioAni(item1).then(() => {
									ani.scaleOut(item0);
									ani.scaleOut(item1).then(() => {
										setTimeout(() => {
											this.groupEnd();//判定单组结束
										}, 100);
									});
									pg.view.visible(pg.view.find(item0, 'box'), false);
									pg.view.visible(pg.view.find(item1, 'box'), false);
								});
							});
						});
					})
				});
			} else {
				//失败--抖动效果
				pg.view.visible(pg.view.find(item, 'box'), true);
				this.playSFX("audio_choice").then(() => {
					this.playAudioAni(item).then(() => {
						ani.shake(item0);
						ani.shake(item1);
						pg.view.visible(pg.view.find(item0, 'box'), false);
						pg.view.visible(pg.view.find(item1, 'box'), false);
						this.playSFX("audio_error").then(() => {
							this._cantouch = true;
						});
					});
				});
			}
			this._cardTouchItems.length = 0;
		} else if (this._cardTouchItems.length == 1) {
			//显示选中效果
			pg.view.visible(pg.view.find(item, 'box'), true);
			this.playSFX("audio_choice").then(() => {
				//audio 播放的时候动画播放，   audio停的时候 动画正好能停下
				//如果动画停的位置不对，直接强制设置对应的效果
				//下一次播放没有问题即可
				this.playAudioAni(item).then(() => {
					this._cantouch = true;
				})
			});
		} else {
			//异常情况
			this._cardTouchItems.length = 0;
			this._cantouch = true;
		}
	},
	playAudioAni(item) {
		return new Promise((resolve, reject) => {
			var anim = pg.view.find(item, `audio`).getComponent(cc.Animation);
			anim.play();
			//如果没有audio也要能正常走
			pg.audio.playAudioByUrl(item.data.audio).then(() => {
				anim.stop();
				pg.view.visible(pg.view.find(item, `audio/btn_laba`), true);
				resolve('');
			});
		});
	},
	onTouchReplay() {
		this.playSFX("audio_btn");
		this.initData();
		this.initSingleData();
		pg.view.visible(this.btn_replay, false);
		this.initStars();
		this.initLayout();
	},
	//回合结束
	groupEnd() {
		if (this._successItems.length < this._cardPage.length) return;
		if (this._gameCode != 0) return;
		let code = CardManager.getIns().addPageNum();
		if (code == 0) {
			this._gameCode = 0;
			this.initSingleData();
			this.initLayout();
		} else if (code == 1) {
			this._gameCode = 1;
			//播放星星动画 然后下一页
			this.playSFX("audio_bigStar");
			this.createStarAni().then(() => {
				this._gameCode = 0;
				this.initSingleData();
				this.initLayout();
			})
		} else if (code == 2) {
			this._gameCode = 2;
			//播放星星动画 然后结束
			this.playSFX("audio_bigStar");
			this.playSFX("audio_sahua");
			this.createStarAni().then(() => { })
			this.createFireworkAni().then(() => {
				//gameOver

				// 游戏结束时需要调用这个方法通知系统作业完成
				onHomeworkFinish();

				pg.view.visible(this.btn_replay, true);
			})
		}
	},
	createRightAni(pos) {
		// let right = pg.view.find(this, 'right');
		// let aniRight = cc.instantiate(right);
		// aniRight.x = pos.x;
		// aniRight.y = pos.y;
		// pg.view.find(this, 'ani').addChild(aniRight);
		// let armDisplay = aniRight.getComponent(dragonBones.ArmatureDisplay);
		// armDisplay.playAnimation('newAnimation', 1);
		// pg.view.visible(aniRight, true);
	},
	createStarAni() {
		return new Promise((resolve, reject) => {
			this.showStar();
			setTimeout(() => {
				resolve('');
			}, 500);
		});
	},
	createFireworkAni() {
		return new Promise((resolve, reject) => {
			// this.showAllFirework(cc.find('Canvas/firework_ani'), cc.find('Canvas/paperBase').children);
			showFireworks(
				cc.find('Canvas/firework_ani'),
				cc.find('Canvas/RibbonNodeBase').children,
				cc.v2(0, -400), cc.v2(0, 1000), 200, 200
			);
			showFireworks(
				cc.find('Canvas/firework_ani'),
				cc.find('Canvas/RibbonNodeBase').children,
				cc.v2(-600, -400), cc.v2(200, 1000), 200, 200
			);
			showFireworks(
				cc.find('Canvas/firework_ani'),
				cc.find('Canvas/RibbonNodeBase').children,
				cc.v2(600, -400), cc.v2(-200, 1000), 200, 200
			);
			setTimeout(() => {
				resolve('');
			}, 1000);
		});
	},
	playSFX(name) {
		return new Promise((resolve, reject) => {
			let node = pg.view.find(this, "audio/" + name);
			if (!node) return resolve();
			let audioSource = node.getComponent(cc.AudioSource);
			if (!audioSource) return resolve();
			let audioClip = audioSource.clip;
			if (!audioClip) return resolve();
			cc.audioEngine.play(audioClip, false, 1);
			resolve('');
		});
	},
	length,
	addStar() {
		if (!this.length) {
			this.length = 0;
		}
		this.length++;
		let length = this.length;

		const starLayout = cc.find('Canvas/layout_stars');
		starLayout.removeAllChildren();
		const paddingY = starLayout.getComponent(cc.Layout).spacingY;

		for (let i = 0; i < length; i++) {
			const starBase = cc.instantiate(cc.find('Canvas/StarBase'));
			starBase.name = `starBase_${i}`;
			starBase.scale = this.Between(0.5, (starLayout.height / length - paddingY) / starBase.height, 1);
			starBase.parent = starLayout;
		}
		this.currentStarIdx = 0;
	},

	currentStarIdx: null,
	showStar() {
		if (!this.currentStarIdx) {
			this.currentStarIdx = 0;
		}

		const starBase = cc.find(`Canvas/layout_stars/starBase_${this.currentStarIdx}`);
		if (!starBase) {
			return;
		}
		const star = starBase.getChildByName('Star');
		const starBig = star.getChildByName('StarBig');
		starBig.scale = 1;
		star.active = true;
		star.scaleX = 0.7 / starBase.scale;
		star.scaleY = 1 / starBase.scale;
		star.angle = 90;
		const canvas = cc.find('Canvas');
		const startPos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 2));
		const middlePos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 4));
		star.x = startPos.x;
		star.y = startPos.y - starBig.height;

		console.log('middlePos = ' + JSON.stringify(middlePos));
		const time = 1;
		cc.tween(star)
			.to(0.3, { y: middlePos.y + 80 }, { easing: 'quadOut' })
			.to(0.1, { y: middlePos.y + 40, scaleX: 1.2 / starBase.scale, scaleY: 0.8 / starBase.scale }, { easing: 'quadOut' })
			.to(0.1, { y: middlePos.y, scaleX: 1 / starBase.scale, scaleY: 1 / starBase.scale }, { easing: 'quadOut' })
			.delay(0.1)
			.to(0.8, { angle: -720, scale: 1 })
			.start();

		cc.tween(star)
			.delay(0.6)
			.to(0.8, { x: 0 }, { easing: 'quadIn' })
			.start();
		cc.tween(star)
			.delay(0.6)
			.to(0.8, { y: 0 }, { easing: 'quadOut' })
			.start();

		cc.tween(starBig)
			.delay(0.6)
			.to(0.8, { scale: 0 }, { easing: 'quadOut' })
			.call(() => {
				// this.checkGameEnd();
			})
			.start();

		this.currentStarIdx++;
	},

	Between(a, b, c) {
		return [a, b, c].sort()[1];
	},

	exchangeNodePos(targetNode, baseNode, basePos) {
		return targetNode.convertToNodeSpaceAR(baseNode.convertToWorldSpaceAR(cc.v2(basePos.x, basePos.y)));
	},


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


	// audioBtn: null,
	// initAudio() {
	// 	const audioNode = cc.find('Canvas/res/audio');

	// 	const getAudioByResName = (resName) => {
	// 		return audioNode.getChildByName(resName).getComponent(cc.AudioSource);
	// 	}

	// 	this.audioBtn = getAudioByResName('btn');

	// },


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

	// 	hyLoader.getSprNodeByUrl(this.data.pic_url, (sprNode) => {
	// 		const picNode1 = sprNode;
	// 		picNode1.scale = maxW / picNode1.width;
	// 		picNode1.baseX = picNode1.x;
	// 		canvas.addChild(picNode1);
	// 		this.pic1 = picNode1;

	// 		const labelNode = new cc.Node();
	// 		labelNode.color = cc.Color.YELLOW;
	// 		const label = labelNode.addComponent(cc.Label);
	// 		label.string = this.data.text;
	// 		label.fontSize = 60;
	// 		label.lineHeight = 60;
	// 		label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent('cc.Label').font;
	// 		picNode1.addChild(labelNode);
	// 	});

	// 	hyLoader.getSprNodeByUrl(this.data.pic_url_2, (sprNode) => {
	// 		const picNode2 = sprNode;
	// 		picNode2.scale = maxW / picNode2.width;
	// 		canvas.addChild(picNode2);
	// 		picNode2.x = canvas.width;
	// 		picNode2.baseX = picNode2.x;
	// 		this.pic2 = picNode2;

	// 		const labelNode = new cc.Node();
	// 		const label = labelNode.addComponent(cc.RichText);
	// 		const size = 60
	// 		label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent(cc.Label).font;
	// 		label.string = `<outline color=#751e00 width=4><size=${size}><color=#ffffff>${this.data.text}</color></size></outline>`
	// 		label.lineHeight = size;
	// 		picNode2.addChild(labelNode);
	// 	});

	// },

	// initIcon() {
	// 	const iconNode = hyLoader.getSprNode('icon');
	// 	iconNode.zIndex = 5;
	// 	iconNode.anchorX = 1;
	// 	iconNode.anchorY = 1;
	// 	iconNode.parent = cc.find('Canvas');
	// 	iconNode.x = iconNode.parent.width / 2 - 10;
	// 	iconNode.y = iconNode.parent.height / 2 - 10;

	// 	iconNode.on(cc.Node.EventType.TOUCH_START, () => {
	// 		hyLoader.playAudioByUrl(this.data.audio_url);
	// 	})
	// },
	// curPage: null,
	// initBtn() {

	// 	this.curPage = 0;
	// 	const bottomPart = cc.find('Canvas/bottomPart');
	// 	bottomPart.zIndex = 5; // 提高层级

	// 	bottomPart.x = bottomPart.parent.width / 2;
	// 	bottomPart.y = -bottomPart.parent.height / 2;

	// 	const leftBtnNode = bottomPart.getChildByName('btn_left');
	// 	//节点中添加了button组件 则可以添加click事件监听
	// 	leftBtnNode.on('click', () => {
	// 		if (!this._cantouch) {
	// 			return;
	// 		}
	// 		if (this.curPage == 0) {
	// 			return;
	// 		}
	// 		this.curPage = 0
	// 		this.leftMove();

	// 		// 游戏结束时需要调用这个方法通知系统作业完成
	// 		onHomeworkFinish();

	// 		cc.audioEngine.play(this.audioBtn.clip, false, 0.8)
	// 	})

	// 	const rightBtnNode = bottomPart.getChildByName('btn_right');
	// 	//节点中添加了button组件 则可以添加click事件监听
	// 	rightBtnNode.on('click', () => {
	// 		if (!this._cantouch) {
	// 			return;
	// 		}
	// 		if (this.curPage == 1) {
	// 			return;
	// 		}

	// 		this.curPage = 1
	// 		this.rightMove();

	// 		cc.audioEngine.play(this.audioBtn.clip, false, 0.5)
	// 	})
	// },

	// leftMove() {
	// 	this._cantouch = false;
	// 	const len = this.pic1.parent.width;
	// 	cc.tween(this.pic1)
	// 		.to(1, { x: this.pic1.baseX }, { easing: 'cubicInOut' })
	// 		.start();

	// 	cc.tween(this.pic2)
	// 		.to(1, { x: this.pic2.baseX }, { easing: 'cubicInOut' })
	// 		.call(() => {
	// 			this._cantouch = true;
	// 		})
	// 		.start();
	// },

	// rightMove() {
	// 	this._cantouch = false;
	// 	const len = this.pic1.parent.width;
	// 	cc.tween(this.pic1)
	// 		.to(1, { x: this.pic1.baseX - len }, { easing: 'cubicInOut' })
	// 		.start();

	// 	cc.tween(this.pic2)
	// 		.to(1, { x: this.pic2.baseX - len }, { easing: 'cubicInOut' })
	// 		.call(() => {
	// 			this._cantouch = true;
	// 		})
	// 		.start();
	// },

	// update (dt) {},
	// ------------------------------------------
});
