import { onHomeworkFinish } from "../script/common/utils";

/**
 * 游戏主逻辑
 */

var game = cc.Class({
	extends: cc.Component,

	properties: {
		Item: {
			default: null,
			type: cc.Node,
			displayName: "预制体"
		},

		contentArr: {
			default: null,
			type: cc.Node,
			displayName: "Layer"
		},

		dragonLion: {
			default: null,
			type: dragonBones.ArmatureDisplay,
			displayName: "狮子"
		},

		dragonCat: {
			default: null,
			type: dragonBones.ArmatureDisplay,
			displayName: "猫"
		},

		btnReStart: {
			default: null,
			type: cc.Node,
			displayName: "重新开始按钮"
		},
		nodCircle: {
			default: null,
			type: cc.Node,
			displayName: "光圈"
		},
		handTip: {
			default: null,
			type: cc.Node,
			displayName: "重新开始按钮"
		},
		nodEndEffect: {
			default: null,
			type: cc.Node,
			displayName: "结束特效节点"
		},
		nodMask: {
			default: null,
			type: cc.Node,
			displayName: "遮罩"
		}
	},

	ctor: function () {
		this._timeoutIds = [];
		this._intervalIds = [];
		game.inst = this;
		OP26.game = game;
	},

	// 生命周期 onLoad
	onLoad() {
	
	},

	start() {
		//初始化游戏
		this.initGame()
	},

	//屏幕缩放
	scaleEventCallBack: function () {
	},

	//初始化游戏
	initGame: function () {
		//获得数据
		OP26.res_mgr.getFormData();
	},

	setAABB() {
		var node = this.dragonLion.node;

		let svLeftBottomPoint = node.parent.convertToWorldSpaceAR(
			cc.v2(
				node.x - node.anchorX * node.width / 2,
				node.y - node.anchorY * node.height / 2
			)
		);

		// 求出 ScrollView 可视区域在世界坐标系中的矩形（碰撞盒）
		let svBBoxRect = cc.rect(
			svLeftBottomPoint.x,
			svLeftBottomPoint.y,
			node.width,
			node.height
		);
		// console.log(Id + ":" + svLeftBottomPoint.x + "," + svLeftBottomPoint.y);
		return svBBoxRect
	},

	//添加节点
	addItem: function () {
		let itemArr = OP26.data_mgr.getQuestionOneList(OP26.data_mgr.quesId);

		console.log(' in addItem id: OP26');
		itemArr.sort(function () { return Math.random() > 0.5 ? -1 : 1; })
		OP26.data_mgr.nowNum = 0;

		for (var i = 0; i < itemArr.length; i++) {
			let newItem = cc.instantiate(this.Item);
			//更新子项
			var com = newItem.getChildByName("item").getComponent("OP26_item");
			let itemInfo = itemArr[i];
			com.updateUI(itemInfo);
			newItem.active = true;
			if (itemInfo.is_right == true) {
				OP26.data_mgr.nowNum += 1;
			}

			newItem.getChildByName("item").is_right = itemInfo.is_right;

			newItem.parent = this.contentArr;
		};
	},

	//隐藏剩余物品并跳转下一题
	resetQues: function () {
		if (OP26.data_mgr.quesId >= 4) {
			this._timeoutIds.push(setTimeout(() => {
				this.finish();
			}, 1000));
			OP26.data_mgr.gameState = 2
		} else {
			for (var i = 0; i < this.contentArr.childrenCount; i++) {
				cc.tween(this.contentArr.children[i].children[0])
					.to(0.8, { opacity: 0 })
					.start();
			}

			this._timeoutIds.push(setTimeout(() => {
				this.UpdataUi();
				//播放题干
				this.playAudioTitle();
			}, 1000));
		}
	},

	//结束
	finish() {
		this.playLionDragon("normal")
		this.playCatDragon("finish")

		//播放引导音频
		let path = OP26.data_mgr.getAudioEnd();
		if (path == -1) {
			if (OP26.data_mgr.getIsFinishDB()) {
				this.showEndEffect();
			} else {
				this.showRestartBtn();
			}
			// this.showEndEffect();
			// this.showRestartBtn();
			return
		}
		OP26.res_mgr.playAudioByUrl(path, (url) => {
			OP26.snd_mgr.playEffect(url, () => {
				if (OP26.data_mgr.getIsFinishDB()) {
					this.showEndEffect();
				} else {
					this.showRestartBtn();
				}
				this.playCatDragon("normal");
				// this.showEndEffect();
				// this.showRestartBtn();
				onHomeworkFinish();
			})
		})
	},

	//开始引导游戏
	guideGame: function () {
		this.UpdataUi();
		this.playCatDragon("begin");
		//播放引导音频
		let path = OP26.data_mgr.getAudioBegin();
		if (path == -1) return this.nodMask.active = false;
		OP26.res_mgr.playAudioByUrl(path, (url) => {
			OP26.snd_mgr.playEffect(url, () => {
				this.nodMask.active = false;
				//播放题干
				this.playAudioTitle();
			})
		})
	},

	//更新界面信息
	UpdataUi: function () {
		OP26.data_mgr.gameState == 1;
		var Info = {
			tex_json: OP26.data_mgr.data.tex_json,
			ske_json: OP26.data_mgr.data.ske_json,
			tex_png: OP26.data_mgr.data.tex_png,
		}
		OP26.res_mgr.loadSpine(this.dragonLion, Info, ()=>{
			//刚进入课件
			//播放第一题题干

			//设置俩个人物状态
			this.playCatDragon("begin");
			this.playLionDragon("normal");

			// //播放题干
			// this.playAudioTitle();

			//重置UI界面
			this.resetUI();
			//添加项
			this.addItem();
		});
	},

	//播放猫动画
	playCatDragon(name) {
		this.dragonCat.armatureName = "Armature";
		this.dragonCat.playAnimation(name);
	},

	//播放猫动画  normal wrong right waiting
	playLionDragon(name) {
		// this.dragonLion.armatureName = "Armature";
		this.dragonLion.playAnimation(name, -1);
	},

	//点击猫猫
	onBtnCheckCat: function () {
		if (this._isSpeak) return;
		//判断当前状态
		if (OP26.data_mgr.quesId < 4) {
			this._isSpeak = true;
			this.playCatDragon("begin");
			this.playAudioTitle(() => {
				this._isSpeak = false;
				this.playCatDragon("normal");
			});
		}

		//如果结束了则提示音
		if (this.btnReStart.active || this.nodEndEffect.active) {
			let path = OP26.data_mgr.getAudioReStart();
			if (path == -1) return;
			this._isSpeak = true
			this.playCatDragon("begin");
			OP26.res_mgr.playAudioByUrl(path, (url) => {
				OP26.snd_mgr.playEffect(url, () => {
					this._isSpeak = false;
					this.playCatDragon("normal");
				})
			});
		}
	},

	//播放题干
	playAudioTitle: function (cb) {
		var path = OP26.data_mgr.getQuestionStem(OP26.data_mgr.quesId);
		if (OP26.data_mgr.quesId >= 4 || !path) return
		//获得播放路径
		OP26.res_mgr.playAudioByUrl(path, (url) => {
			OP26.snd_mgr.playEffect(url, () => {
				//结束回调
				this.playCatDragon("normal");
				cb && cb();
			});
		});
	},

	//重置UI界面
	resetUI: function () {
		//移除所有子节点
		this.contentArr.removeAllChildren();
	},

	//游戏开始
	gameStart: function () {
		console.log("游戏开始:" + OP26.data_mgr);
		//播放一个上面的音乐
		this.setAudioInfo(1);
	},

	//重新开始
	onBtnReStart() {
		//隐藏节点
		this.btnReStart.active = false;
		//播放音效
		OP26.speaker.inst.playEffect(OP26.enum.E_Audio.BtnCommom);
		//数据重置
		OP26.data_mgr.quesId = 0;
		//更新界面
		this.UpdataUi();

		//播放题干
		this.playAudioTitle();

		this.hideRestartBtn();
	},

	//手势移动
	setHandTip(node) {
		//传入当前点击的节点坐标，移动至中心点
		var beginPos = cc.v2(node.x, node.y + this.contentArr.y);
		//50偏移量到嘴巴
		var EndPos = cc.v2(this.dragonLion.node.x, this.dragonLion.node.y);
		this.handTween && this.handTween.stop();
		this.handTween = cc.tween(this.handTip)
			.call(() => {
				this.handTip.active = true;
				this.handTip.x = beginPos.x;
				this.handTip.y = beginPos.y;
			})
			.to(1.5, { x: EndPos.x, y: EndPos.y })
			.call(() => {
				this.handTip.active = false;
			})
			.union()
			.repeat(2) // 执行2次
			.start();
	},

	//显示结束效果界面
	showEndEffect() {
		this.nodEndEffect.getComponent("OP26_nodEndEffect").onShow();
	},

	showRestartBtn() {
		// return;
		this.btnReStart.active = true;
		cc.tween(this.nodCircle)
			.set({ scale: 0.8, opacity: 255 })
			.to(2, { scale: 1.2, opacity: 0 })
			.union()
			.repeatForever()
			.start();
	},

	hideRestartBtn() {
		// return;
		this.nodCircle.stopAllActions();
		this.nodCircle.scale = 0.8;
		this.nodCircle.opacity = 255;
	},

	_timeoutIds: null,
	_intervalIds: null,
	// 生命周期
	onDestroy() {
		this._timeoutIds.forEach(id => {
			clearTimeout(id);
		});
		this._intervalIds.forEach(id => {
			clearInterval(id);
		});
		OP26.game.inst._intervalIds.forEach(id => {
			clearInterval(id);
		});
		OP26.data_mgr.quesId = 0;
	},
});
