/**
 * 游戏主逻辑
 */
var game = cc.Class({
	extends: cc.Component,

	properties: {
		contentArr_1: {
			default: null,
			type: cc.Node,
			displayName: "内容_1"
		},
		Item_1: {
			default: null,
			type: cc.Node,
			displayName: "滚动项"
		},
		contentArr_2: {
			default: null,
			type: cc.Node,
			displayName: "内容_2"
		},
		Item_2: {
			default: null,
			type: cc.Node,
			displayName: "滚动项"
		},
		draw: {
			default: null,
			type: cc.Graphics,
			displayName: "滚动项"
		},
		resultNode: {
			default: null,
			type: cc.Node,
			displayName: "结算弹窗"
		},
		title: {
			default: null,
			type: cc.Label,
			displayName: "标题"
		},
		btnList: {
			default: [],
			type: cc.Button,
			displayName: "上下页"
		},
		mask_node: {
			default: null,
			type: cc.Node,
			displayName: "遮罩"
		}
	},

	ctor: function () {
		game.inst = this;
		lwd_g.game = game;
		this._timeoutIds = [];

	},

	// 生命周期 onLoad
	onLoad() {
		//初始化游戏
		this.initGame();
	},

	//初始化游戏
	initGame: function () {
		//重置游戏数据游戏数据
		lwd_g.data_mgr.resGameData();
		//获得数据
		lwd_g.res_mgr.getFormData();
	},

	//更新界面信息
	UpdataUi: function () {
		//显示标题
		this.title.string = lwd_g.data_mgr.data.contentObj.title;
		//设置上下页按钮状态
		this.setButtonState();
		//获得上列表的数据
		var topList = lwd_g.data_mgr.getImgInfo(1);
		var botList = lwd_g.data_mgr.getImgInfo(2);
		//打乱列表顺序
		this.contentArr_1.opacity = 0;
		this.contentArr_2.opacity = 0;

		topList.sort(function () { return Math.random() > 0.5 ? -1 : 1; })
		botList.sort(function () { return Math.random() > 0.5 ? -1 : 1; })
		this.addItem(topList, this.contentArr_1, this.Item_1, 0);
		this.addItem(botList, this.contentArr_2, this.Item_2, 0);
		//准备完毕
	},

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

	//设置上下页按钮状态
	setButtonState: function () {
		//先判断题目长度
		if (lwd_g.data_mgr.data.contentObj.pageArr.length < 2) {
			this.btnList[0].node.active = false;
			this.btnList[1].node.active = false;
		} else {
			//如果第一页
			if (lwd_g.data_mgr.pageId == 0) {
				this.btnList[1].node.opacity = 255;
				this.btnList[1].interactable = true;
				this.btnList[0].node.opacity = 255 / 2;
				this.btnList[0].interactable = false;
			}
			if (lwd_g.data_mgr.pageId == lwd_g.data_mgr.data.contentObj.pageArr.length - 1) {
				this.btnList[0].node.opacity = 255;
				this.btnList[0].interactable = true;
				this.btnList[1].node.opacity = 255 / 2;
				this.btnList[1].interactable = false;
			}
			if (lwd_g.data_mgr.pageId > 0 && lwd_g.data_mgr.pageId < lwd_g.data_mgr.data.contentObj.pageArr.length - 1) {
				this.btnList[0].node.opacity = 255;
				this.btnList[0].interactable = true;
				this.btnList[1].node.opacity = 255;
				this.btnList[1].interactable = true;
			}
		}
	},

	//上一关
	onBtnLastPage: function () {
		if (lwd_g.data_mgr.pageId - 1 >= 0) {
			lwd_g.data_mgr.pageId -= 1;
			this.setButtonState();
			this.onBtnReStart();
		}
	},

	//下一关
	onBtnNextPage: function () {
		if (lwd_g.data_mgr.pageId + 1 < lwd_g.data_mgr.data.contentObj.pageArr.length) {
			lwd_g.data_mgr.pageId += 1;
			this.setButtonState();
			this.onBtnReStart();
		}
	},

	//获得随机播放的音乐并播放
	setAudioInfo: function (type) {
		//随机一个数字 播放这个数字的上段部分
		lwd_g.data_mgr.temPlayAudio.sort(function () { return Math.random() > 0.5 ? -1 : 1; })
		var num = lwd_g.data_mgr.temPlayAudio[0];
		//设置播放信息
		lwd_g.data_mgr.playId = num;
		lwd_g.data_mgr.playType = type;
		this.PlayAudio();
	},

	//重新播放音乐
	onBtnSound: function () {
		this.PlayAudio();
	},

	//重新开始
	onBtnReStart: function () {
		//移除所有计时器
		this.unscheduleAllCallbacks();
		for (var i = 0; i < this.contentArr_1.childrenCount; i++) {
			this.contentArr_1.children[i].active = false;
		}
		for (var i = 0; i < this.contentArr_2.childrenCount; i++) {
			this.contentArr_2.children[i].active = false;
		}
		this.resultNode.active = false;

		//重置游戏数据游戏数据
		lwd_g.data_mgr.resGameData();

		lwd_g.data_mgr.addPreloadImage();
		lwd_g.data_mgr.addPreloadAudio();
		lwd_g.data_mgr.addPreloadAnima();

		lwd_g.result.inst.End = true;

		//初始化界面
		this.UpdataUi();

		// //播放游戏开始音效
		// lwd_g.speaker.inst.play_start();

		//游戏开始
		lwd_g.game.inst.gameStart();

		//清除线
		this.clearLine();
	},

	//显示结算弹窗
	showResult: function (Info) {
		this.resultNode.scale = 0;
		this.resultNode.active = true;
		cc.tween(this.resultNode)
			.to(0.5, { scale: 1 })
			.start()
		lwd_g.result.inst.updateUI(Info);
	},


	//播放音乐
	PlayAudio: function () {
		//获得播放路径
		var path = lwd_g.data_mgr.getPlayUrl();
		lwd_g.res_mgr.playAudioByUrl(path, (url) => {
			lwd_g.snd_mgr.playEffect(url);
		});
	},

	//播放标题音效
	playAudioTitle: function (cb) {
		//获得播放路径
		var path = lwd_g.data_mgr.data.contentObj.audio_url;
		if (path == undefined) {
			cb && cb();
		}
		lwd_g.res_mgr.playAudioByUrl(path, (url) => {

			console.log(' type : ', typeof (cb));
			if (typeof (cb) != 'function') {
				cb = null;
			}
			lwd_g.snd_mgr.playEffect(url, cb);
		});
	},

	onBtnMask: function () {

		console.log('in onBtnMask');
		if (this.isLoadEnd) {
			this.isLoadEnd = false;
			lwd_g.speaker.inst.play_start(() => {
				this._timeoutIds.push( setTimeout(() => {

					console.log('aaaa')
					lwd_g.game.inst.playAudioTitle(() => {
						lwd_g.game.inst.mask_node.active = false;
						//游戏开始
						lwd_g.game.inst.gameStart();
					});
				}, 500));
			});
		}
	},

	//添加项 
	addItem: function (listInfo, content, item, i) {
		if (listInfo.length <= i) {
			content.getComponent(cc.Layout).updateLayout();
			this.contentArr_1.runAction(cc.fadeIn(0.2))
			this.contentArr_2.runAction(cc.fadeIn(0.2))
			return;
		}
		var len = content.childrenCount;
		// 添加子项
		let newItem = len > i ? content.children[i] : cc.instantiate(item);
		// 更新子项
		var com = newItem.getComponent("item");
		com.updateUI(listInfo[i]);
		newItem.active = true;
		newItem.parent = content;
		this.scheduleOnce(() => {
			i += 1;
			this.addItem(listInfo, content, item, i)
		}, 0);
	},

	//点亮 conten：上列表，下列表   state：0 点亮，2变暗
	allLightDark(positionId, state) {
		var conten = positionId == 1 ? this.contentArr_1 : this.contentArr_2;
		for (var i = 0; i < conten.childrenCount; i++) {
			var item = conten.children[i]
			if (item.state == 1 || item.state == 3) {
				// if (state == 2) {
				var com = item.getComponent("item");
				//设置状态为可答题
				com.setBtnState(item.state);
				continue;
				// }
			} else {
				var com = item.getComponent("item");
				//设置状态为可答题
				com.setBtnState(state);
			}
		}
	},

	ShowLine: function (sx, sy, ex, ey, cb) {
		var b = 0;
		var a = 0;
		var k = ex == sx ? 0 : (ey - sy) / (ex - sx);
		if (k == 0) {
			a = 0;
			b = -5;
		} else {
			a = k < 0 ? 5 : -5;
		}
		var difx = sx + a
		var dify = sy + k * a + b;
		if (ex == sx) {
			var difnode = dify > ey;
		}
		else {
			var difnode = ex > sx ? difx < ex : difx > ex;
		}
		if (difnode) {
			this.scheduleOnce(() => {
				this.DrawLine(sx, sy, difx, dify);
				this.ShowLine(difx, dify, ex, ey, cb);
			}, 0.01);
		}
		else {
			this.DrawLine(ex, ey, ex, ey);

			//移除播放列表的数据
			lwd_g.data_mgr.temPlayAudio.splice(0, 1);

			//显示弹窗
			var Info = lwd_g.data_mgr.getResultInfo(lwd_g.data_mgr.nowNode.typeId);
			lwd_g.game.inst.showResult(Info);
			cb && cb();
		}
	},

	//点击测试
	DrawLine: function (sx, sy, ex, ey) {
		//获得组件 
		var com = this.draw;
		//设置线的颜色
		com.strokeColor = new cc.Color().fromHEX(lwd_g.data_mgr.lineColor[lwd_g.data_mgr.playId]);;
		// 设置线条宽度
		com.lineWidth = 10;
		// 路径起点为0,0
		com.moveTo(sx, sy);
		// 路径画线到（100,100）
		// 路径看不见！！！
		com.lineTo(ex, ey);
		// 把路径画实，能看见啦！
		com.stroke();
	},

	//
	clearLine: function () {
		//获得组件 
		var com = this.draw;
		com.clear()
	},

	onDestroy() {
		this._timeoutIds.forEach(id => {
			clearTimeout(id);
		});
	}
});
