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.initLayout();
		this.catBegin().then(() => {
			this.catChoice();
		});
	},
	initStars() {
		// this.length = CardManager.getIns().getTestlet();
		// this.addStar();
	},
	initLayout() {
		pg.view.visible(this.btn_replay, false);
		this._cardLayout = pg.view.find(this, `layout_card_6`);
		ani.scaleIn(this._cardLayout);
		pg.view.visible(this._cardLayout, true);

		let itemBase = pg.view.find(this, "item");
		for (let i = 0; i < this._cardPage.length; i++) {
			let data = this._cardPage[i];
			let item = cc.instantiate(itemBase)
			item.parent = this._cardLayout;
			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`);

		pg.view.setNetImg(img, data.img);
		pg.view.visible(img, true);
		pg.view.visible(txt, false);
		pg.view.visible(audio, true);
		pg.view.visible(pg.view.find(audio, "icon_1"), false);
		pg.view.visible(pg.view.find(audio, "icon_2"), false);
		pg.view.visible(pg.view.find(audio, "icon_3"), false);
		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);
		pg.view.touchOn(audio, this.onTouchAudio, this);
	},
	onTouchAudio(touch) {
		if (this._gameCode != 0) return resolve('');
		if (!this._cantouch) return;
		this._cantouch = false;
		let item = touch.target.parent;
		this.playAudioAni(item).then(() => {
			this._cantouch = true;
		});
	},
	onTouchItem(touch, info) {
		return new Promise((resolve, reject) => {
			if (this._gameCode != 0) return resolve('');
			if (!this._cantouch) return resolve('');
			let item = touch.target;
			if (this._successItems.indexOf(item) > -1) return resolve('');
			let data = item.data;
			this._cantouch = false;
			if (data.right) {
				this.catRight();
				pg.view.visible(pg.view.find(item, 'box'), true);
				this.playSFX("audio_right").then(() => {
					//audio 播放的时候动画播放，   audio停的时候 动画正好能停下
					//如果动画停的位置不对，直接强制设置对应的效果
					//下一次播放没有问题即可
					this.playAudioAni(item).then(() => {
						this._cantouch = true;
						this._successItems.push(item);
						this.catNormal();
						this.groupEnd();
						resolve('');
					})
				});
			} else {
				this.catError();
				//失败--抖动效果
				ani.shake(item);
				this.playSFX("audio_error").then(() => {
					this.playAudioAni(item).then(() => {
						this._cantouch = true;
						this.catNormal();
						resolve('');
					});
				});
			}

		});
	},
	playAudioAni(item) {
		return new Promise((resolve, reject) => {
			// var anim = pg.view.find(item, `audio`).getComponent(cc.Animation);
			// anim.play();
			let audio = pg.view.find(item, `audio`);
			let icon_1 = pg.view.find(audio, "icon_1");
			let icon_2 = pg.view.find(audio, "icon_2");
			let icon_3 = pg.view.find(audio, "icon_3");
			icon_1.active = true;
			//如果没有audio也要能正常走
			pg.audio.playAudioByUrl(item.data.audio).then(() => {
				// anim.stop();
				icon_1.active = false;
				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 >= CardManager.getIns().allRightNum()) {
			//判定结束
			this._gameCode = 2;
			this.catFinish();
		}
		// 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();
			let id = cc.audioEngine.play(audioClip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				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;
	},

	catBegin() {
		return new Promise((resolve, reject) => {
			this._cantouch = false;
			let cat = pg.view.find(this, "cat");
			pg.view.playDragonBone(cat, "begin");
			pg.audio.playAudioByUrl(CardManager.getIns().getAudio()).then(() => {
				resolve('');
			});
		});
	},
	catChoice() {
		return new Promise((resolve, reject) => {
			this.playSFX("mao_choice").then(() => {
				let items = this._cardLayout.children;
				let item = items.filter(it => {
					return it.data.cardId == 0
				})[0];
				this._cantouch = true;
				this.onTouchItem({ target: item }).then(() => {
					resolve('');
				})
			});
		});
	},
	catFinish() {
		return new Promise((resolve, reject) => {
			let cat = pg.view.find(this, "cat");
			pg.view.playDragonBone(cat, "finish");
			this.playSFX("mao_right").then(() => {
			});
		});
	},
	catRight() {
		let cat = pg.view.find(this, "cat");
		pg.view.playDragonBone(cat, "right");
	},
	catError() {
		let cat = pg.view.find(this, "cat");
		pg.view.playDragonBone(cat, "wrong");
	},
	catNormal() {
		let cat = pg.view.find(this, "cat");
		pg.view.playDragonBone(cat, "normal");
	}
});
