
/**
 * 游戏主逻辑
 */

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: "重新开始按钮"
		},
		nodMask: {
			default: null,
			type: cc.Node,
			displayName: "遮罩"
		}
	},

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

	// 生命周期 onLoad
	onLoad() {

	},

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

	//屏幕缩放
	scaleEventCallBack: function () {
		// LWD_3.event_mgr.send("adjustUI");
	},

	//初始化游戏
	initGame: function () {
		//获得数据
		LWD_3.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 = LWD_3.data_mgr.getQuestionOneList(LWD_3.data_mgr.quesId);
		console.log(' in addItem id: LWD_3');

		itemArr.sort(function () { return Math.random() > 0.5 ? -1 : 1; })
		LWD_3.data_mgr.nowNum = 0;

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

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

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

	//隐藏剩余物品并跳转下一题
	resetQues: function () {
		if (LWD_3.data_mgr.quesId >= 4) {
			this._timeoutIds.push(setTimeout(() => {
				this.finish();
			}, 1000));
			LWD_3.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 = LWD_3.data_mgr.getAudioEnd();
		if (path == -1) return this.showRestartBtn();
		LWD_3.res_mgr.playAudioByUrl(path, (url) => {
			LWD_3.snd_mgr.playEffect(url, () => {
				this.showRestartBtn();
				// TODO 结束游戏，上报成绩
				onHomeworkFinish();
			})
		})
	},

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

	//更新界面信息
	UpdataUi: function () {
		LWD_3.data_mgr.gameState == 1;
		var Info = {
			tex_json: LWD_3.data_mgr.data.tex_json,
			ske_json: LWD_3.data_mgr.data.ske_json,
			tex_png: LWD_3.data_mgr.data.tex_png,
		}
		LWD_3.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);
	},

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

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

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

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

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

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

	//重新开始
	onBtnReStart() {
		//隐藏节点
		this.btnReStart.active = false;
		//播放音效
		LWD_3.speaker.inst.playEffect(LWD_3.enum.E_Audio.BtnCommom);
		//数据重置
		LWD_3.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();
	},

	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() {
		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);
		});
		LWD_3.game.inst._intervalIds.forEach(id => {
			clearInterval(id);
		});
		LWD_3.data_mgr.quesId = 0;
	},
});
