var container = document.querySelector(".container");
container.style.width = window.innerWidth + "px";
container.style.height = window.innerHeight + "px";
document.getElementsByTagName("html")[0].style.fontSize = window.innerWidth / 20 + "px";
var tradeDOM = document.querySelector(".commit"); //工作台
var timeTimer = null;
var firstPage = document.querySelector(".firstPage");
var gamePage = document.querySelector(".gamePage");
var gameEnd = document.querySelector(".endPage");
var rankMenu = document.querySelector(".rankMenu");
var restartEndDIv = document.querySelectorAll(".restartEnd");
restartEndDIv[1].style.top = (window.innerHeight - window.innerWidth * 3 / 20) + "px";
var source = "";

window.onload = function() {
	var container = document.querySelector(".container");
	container.style.width = window.innerWidth + "px";
	container.style.height = window.innerHeight + "px";
	document.getElementsByTagName("html")[0].style.fontSize = window.innerWidth / 20 + "px";
}

window.onresize = function() {
	var container = document.querySelector(".container");
	container.style.width = window.innerWidth + "px";
	container.style.height = window.innerHeight + "px";
	document.getElementsByTagName("html")[0].style.fontSize = window.innerWidth / 20 + "px";
}

//游戏参数
var dataGame = {
	gameid: 0,
	cash: 0,
	debt: 0,
	station_passed: 0,
	start_time: 0,
	end_time: null,
	checkout: false,
	stationcom: [],
	commodities: [],
	warehouse_left: 88,
	warehouse_total: 110,
	time_left: -63272,
	pre_station: "北京",
	next_station: "北京",
	community_id: 1,
	current_station_name: "天津",
	current_station_id: 2,
	arrived_at: 1481877013.002169
}

//进入游戏界面 判断游戏状态
gamestatus();

function gamestatus() {
	loadXMLDoc("GET", "/game_server/tycoon/game_status/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			gamePage.style.display = "block";
			dataGame["gameid"] = back["game_status"]["id"];
			dataGame["debt"] = back["game_status"]["debt"];
			dataGame["station_passed"] = back["game_status"]["station_passed"];
			dataGame["commodities"] = back["game_status"]["commodities"];
			dataGame["warehouse_left"] = back["game_status"]["warehouse_left"];
			dataGame["cash"] = back["game_status"]["cash"];
			dataGame["warehouse_total"] = back["game_status"]["warehouse_total"];
			dataGame["start_station"] = back["game_status"]["start_station"];

			document.querySelector(".place").innerHTML = '<span>' + dataGame["start_station"] + '</span><span>——></span><span>' + dataGame["start_station"] + '</span>';
			train();
			render();
			userOrigin();
		} else {
			firstPage.style.display = "block";
		}
	}, {});
}

//现金负债存货刷新
function render() {
	//现金与负债
//	var cash = document.querySelector(".nowMoney_num span");
//	var debt = document.querySelector(".senMoneyNum span");
//	cash.innerHTML = dataGame["cash"];
//	debt.innerHTML = dataGame["debt"];
	var section_money = document.querySelectorAll(".section_money_test span");
	var sectionDiv = document.querySelector(".section_money_test");
	var cash = section_money[0];
	var debt = section_money[1];
	var payback = section_money[2];
	var percentColor = dataGame["cash"] / (dataGame["cash"] + dataGame["debt"]);
	cash.innerHTML = "现金 " + dataGame["cash"];
	if(dataGame["debt"] > 0){
		debt.innerHTML = "欠款 " + dataGame["debt"];
		debt.style.display = "block";
		payback.style.display = "block";
		sectionDiv.style.backgroundImage = "-webkit-linear-gradient(to right,#34BAE3 "+window.innerWidth * (percentColor-0.5)+"px,#A7C607 "+window.innerWidth * (percentColor+0.5)+"px)";
		sectionDiv.style.backgroundImage = "linear-gradient(to right,#34BAE3 "+window.innerWidth * (percentColor-0.5)+"px,#A7C607 "+window.innerWidth * (percentColor+0.5)+"px)";
	}else {
		debt.style.display = "none";
		payback.style.display = "none";
		sectionDiv.style.backgroundImage = "-webkit-linear-gradient(to right,#34BAE3 400px,#A7C607 300px)";
		sectionDiv.style.backgroundImage = "linear-gradient(to right,#34BAE3 400px,#A7C607 300px)";
	}
	//我的仓库
	var bagTitle = document.querySelector(".bagTitle span:nth-of-type(2)");
	bagTitle.innerHTML = dataGame["warehouse_left"] + "/" + dataGame["warehouse_total"];
	var passStation = document.querySelector(".placeNum span:nth-of-type(2)");
	passStation.innerHTML = parseInt(40 - dataGame["station_passed"]);
	var bagSection = document.querySelector(".bagsection");
	var bagstr = "";
	//背包刷新
	for(var i = 0; i < dataGame["commodities"].length; i++) {
		var str = '<div class="bagSectionCell" onclick="sell(' + dataGame["commodities"][i]["id"] + ',' + dataGame["commodities"][i]["count"] + ',\'' + dataGame["commodities"][i]["commodity_name"] + '\')"><span>' + dataGame["commodities"][i]["commodity_name"] + '</span><span>' + dataGame["commodities"][i]["cost"] + '</span><span>' + dataGame["commodities"][i]["count"] + '</span></div>';
		bagstr += str;
	}
	bagSection.innerHTML = bagstr;
	if(tradeDOM.status == 3) {
		tradeDOM.style.height = "0rem";
	}
}

//本地市场刷新
function station_commodities() {
	var marketSection = document.querySelector(".marketSection");
	var stationcomstr = "";
	//本地市场
	for(var i = 0; i < dataGame["stationcom"].length; i++) {
		var str = '<div class="marketSectionCell" onclick="buy(' + dataGame["stationcom"][i]["id"] + ',\'' + dataGame["stationcom"][i]["name"] + '\')"><span>' + dataGame["stationcom"][i]["name"] + '</span><span>' + dataGame["stationcom"][i]["current_price"] + '</span></div>';
		stationcomstr += str;
	}
	marketSection.innerHTML = stationcomstr;
}

//当前交易栏刷新
function sell(index, count, name) {
	tradeDOM.status = 1;
	tradeDOM.item = index;
	tradeDOM.itemsname = name;
	tradeDOM.innerHTML = '<span>' + tradeDOM.itemsname + ' x ' + count + '</span><span onclick = "trade()">卖出</span>';
	tradeDOM.style.height = "2rem";
}

function buy(index, name) {
	tradeDOM.status = 0;
	tradeDOM.item = index;
	tradeDOM.itemsname = name;
	var count = getCountBuy(index);
	if(count == 0) {
		tradeDOM.innerHTML = "无法购买，请确认您的现金与仓库位置是否充足。"
	} else {
		tradeDOM.innerHTML = '<span>' + tradeDOM.itemsname + ' x ' + count + '</span><span onclick = "trade()">买入</span>';
	}
	tradeDOM.style.height = "2rem";
}

function getCountBuy(itemid) {
	var itemsNull = parseInt(dataGame["warehouse_left"]);
	for(x in dataGame["stationcom"]) {
		if(dataGame["stationcom"][x].id == itemid) {
			var price = dataGame["stationcom"][x]["current_price"];
			break;
		}
	}
	var itemsMoney = parseInt(dataGame["cash"] / price);
	return Math.min(itemsNull, itemsMoney);
}

function trade() {
	if(tradeDOM.status == 1) {
		loadXMLDoc("POST", "/game_server/tycoon/sell_commodity/", function(data) {
			var back = JSON.parse(data);
			if(back["ok"] == true) {
				dataGame["cash"] = back["game_status"]["cash"];
				dataGame["commodities"] = back["game_status"]["commodities"];
				dataGame["warehouse_left"] = back["game_status"]["warehouse_left"];
				dataGame["warehouse_total"] = back["game_status"]["warehouse_total"];
				tradeDOM.status = 3;
				render();
				//成交成功
			} else {
				occMessage("卖不出去喽~~")
			}
		}, {
			game_id: dataGame.gameid,
			game_commodity_id: tradeDOM.item
		});
	} else if(tradeDOM.status == 0) {
		loadXMLDoc("POST", "/game_server/tycoon/buy_commodity/", function(data) {
			var back = JSON.parse(data);
			if(back["ok"] == true) {
				dataGame["cash"] = back["game_status"]["cash"];
				dataGame["commodities"] = back["game_status"]["commodities"];
				dataGame["warehouse_left"] = back["game_status"]["warehouse_left"];
				dataGame["warehouse_total"] = back["game_status"]["warehouse_total"];
				tradeDOM.status = 3;
				render();
			}
		}, {
			game_id: dataGame.gameid,
			station_commodity_id: tradeDOM.item
		})
	}
}
//站点刷新
function train() {
	loadXMLDoc("GET", "/game_server/tycoon/train_status/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			dataGame["time_left"] = back["train_status"]["time_left"];
			dataGame["stationcom"] = back["train_status"]["goods"];
			dataGame["pre_station"] = back["train_status"]["pre_station"];
			dataGame["next_station"] = back["train_status"]["next_station"];
			dataGame["community_id"] = back["train_status"]["community_id"];
			dataGame["current_station_name"] = back["train_status"]["current_station_name"];
			dataGame["current_station_id"] = back["train_status"]["current_station_id"];
			dataGame["arrived_at"] = back["train_status"]["arrived_at"];

			var nextStation = document.querySelector(".nextstation");
			var nextStationTime = document.querySelector(".nextstationTime");
			var placeName = document.querySelector(".placeName");
			var markitTitle = document.querySelector(".marketTitle");
			markitTitle.innerHTML = dataGame["current_station_name"] + "站台";
			nextStation.innerHTML = dataGame["next_station"];
			nextStationTime.innerHTML = dataGame["time_left"];

			station_commodities();

			clearInterval(timeTimer);
			timeTimer = setInterval(function() {
				dataGame["time_left"]--;
				nextStationTime.innerHTML = dataGame["time_left"] + "\"";
				if(dataGame["time_left"] <= 0 && dataGame["station_passed"] == 39) {
					//游戏结束
					clearInterval(timeTimer);
					timeTimer = null;
					overRank();
				} else if(dataGame["time_left"] <= 0) {
					tradeDOM.status = 3;
					gamestatus();
				}
			}, 1000);
			placeName.innerHTML = '<span>' + dataGame["pre_station"] + '</span><span>' + dataGame["current_station_name"] + '</span><span>' + dataGame["next_station"] + '</span>';

			if(typeof source != "object") {
				makeSse();
			}
		}
	}, {})
}
var waitTime = 0;

function bePlayer() {
	if(waitTime != 0) {
		occMessage("别急，列车还没到。")
	} else {
		loadXMLDoc("GET", "/game_server/tycoon/train_status/", function(data) {
			var back = JSON.parse(data);
			if(back.ok == true) {
				waitTime = back["train_status"]["time_left"];
				if(waitTime <= 15) {
					var bePlayer = document.querySelector(".bePlayer");
					bePlayer.style.fontSize = "0.68rem";
					bePlayer.innerHTML = "你将在" + waitTime + "s后列车停靠时上车";
					waittimer = setInterval(function() {
						waitTime--;
						if(waitTime <= 0) {
							clearInterval(waittimer);
							bePlayer();
//							loadXMLDoc("GET", "/game_server/tycoon/onboard/", function(data) {
//								var back = JSON.parse(data);
//								if(back["ok"] == true) {
//									location.reload();
//								}
//							}, {})
						}
						bePlayer.innerHTML = "你将在" + waitTime + "s后列车停靠时上车";
					}, 1000);
				} else {
					loadXMLDoc("GET", "/game_server/tycoon/onboard/", function(data) {
						var back = JSON.parse(data);
						if(back["ok"] == true) {
							location.reload();
						}
					}, {})
				}
			}
		}, {})
	}
	//	
	//	
	//	
	//	
	//	
	//	loadXMLDoc("GET","/game_server/tycoon/onboard/",function(data){
	//		var back = JSON.parse(data);
	//		if(back["ok"] == true){
	//			location.reload();
	//		}
	//	},{})
}

function userOrigin() {
	loadXMLDoc("GET", "/game_server/tycoon/online_info/", function(result) {
		var back = JSON.parse(result);
		if(back.ok == true) {
			document.querySelector(".inline").innerHTML = back.obj.online_gamers + "人 在线";
			var strUser = "";
			for(var i = 0; i < back.obj.active_gamers.length; i++) {
				strUser += '<span style="background-image:url(' + back.obj.active_gamers[i].avatar + ')"></span>'
			}
			document.querySelector(".userimg").innerHTML = strUser;
		} else {
			occMessage(back.error)
		}
	}, {})
}

function makeSse() {
	source = new EventSource(baseURL()+'/game_server_sse/train_' + dataGame["community_id"] + '/');
	var inlineDiv = document.querySelector(".inline");
	var userImgDiv = document.querySelector(".userimg");
	var portMessage = document.querySelector(".portMessage");
	source.addEventListener('delta', function(e) {
		var backMessage = JSON.parse(e.data);
		if(backMessage.event_type == "online_number") {
			inlineDiv.innerHTML = backMessage.data.number + "人 在线";
		} else if(backMessage.event_type == "active_user") {
			var strUser = "";
			for(var i = 0; i < backMessage.data.users.length; i++) {
				strUser += '<span style="background-image:url(' + backMessage.data.users[i].avatar + ')"></span>'
			}
			userImgDiv.innerHTML = strUser;
		} else if(backMessage.event_type == "msg") {
			//			console.log(backMessage);
			senMsg(backMessage.data.subtitle);
		}
	}, false);
	source.addEventListener('error', function(e) {
		if(e.readyState == EventSource.CLOSED) {
			console.log(["e.readyState == EventSource.CLOSED", e]);
		} else if(e.readyState == EventSource.OPEN) {
			console.log(["e.readyState == EventSource.OPEN", e]);
		}
	}, false);
}
function baseURL(){
	if(window.IAObj){
		return window.IAObj.getBaseUrl();
	}else {
		return "http://test.engdd.com";
	}
}
var messagePosition = {
	first: true,
	second: true,
	third: true,
	fourth:true
}

function senMsg(str) {
	var div = document.createElement("div");
	var portMessage = document.querySelector(".portMessage");
	div.innerHTML = str;
	div.className = "danmu";
	portMessage.appendChild(div);
	setTimeout(function() {
		if(messagePosition.first == true) {
			div.style.top = 0;
			div.floor = 1;
			messagePosition.first = false;
		} else if(messagePosition.second == true) {
			div.style.top = "2rem";
			div.floor = 2;
			messagePosition.second = false;
		} else if(messagePosition.third == true){
			div.style.top = "4rem";
			div.floor = 3;
			messagePosition.third = false;
		}else {
			div.style.top = "6rem";
			div.floor = 4;
		}
		var timeTrue = 7000 * div.offsetWidth / (window.innerWidth * 2);
		setTimeout(function() {
			switch(div.floor) {
				case 1:
					messagePosition.first = true;
					break;
				case 2:
					messagePosition.second = true;
					break;
				case 3:
					messagePosition.third = true;
					break;
				default:
					break;
			}
		}, timeTrue);
	}, 0);
	div.addEventListener("webkitAnimationEnd", function() {
		div.parentNode.removeChild(div);
	});
}

function loadXMLDoc(method, url, callback, dataSub) {
	var xmlhttp = new XMLHttpRequest();
	var detail = "";
	var arr = [];
	for(var key in dataSub) {
		var row = key + "=" + dataSub[key];
		arr.push(row);
	}
	detail = arr.join("&");
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == XMLHttpRequest.DONE) {
			if(xmlhttp.status == 200) {
				callback(xmlhttp.responseText);
			} else if(xmlhttp.status == 400) {
				occMessage('There was an error 400');
			} else {
				occMessage('something else other than 200 was returned');
			}
		}
	};
	if(method == "GET") {
		if(detail.length > 0) {
			url = url + "?" + detail;
			detail = null;
		}
		xmlhttp.open("GET", baseURL()+url, true);
	} else if(method == "POST") {
		xmlhttp.open("POST", baseURL()+url, true);
	}

	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	if(window.IAObj) {
		xmlhttp.setRequestHeader("Authorization", window.IAObj.getJwt());
	} else {
		xmlhttp.setRequestHeader("Authorization", "Bearer " + getParam('Authorization'));
	}
	xmlhttp.send(detail);
}

function getParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}

function exit() {
	//dir:0发起者，1接受者
	//通讯命令:0开始
	if(checkClient()) {
		var IAMsg = {
			cmd: "24"
		};
		var tJSon = JSON.stringify(IAMsg);
		//jsonz字符串
		IAObj.jsSendCmdJsonStr(tJSon);
	} else {
		alert("未定义客户端桥");
	}
}

function checkClient() {
	var rClient = false;
	if(typeof(IAObj) != "undefined") {
		rClient = true;
	} else {
		rClient = false;
	}
	return rClient;
}

function occMessage(str) {
	var message = document.querySelector(".message");
	message.opacity = 0;
	message.innerHTML = str;
	setTimeout(function() {
		message.style.display = "block";
	}, false)
	message.speed = 0.05;
	message.timer = requestAnimationFrame(render_message);

	function render_message() {
		if(message.opacity <= 1 && message.speed >= 0) {
			message.opacity += message.speed;
			message.style.opacity = message.opacity;
			message.timer = requestAnimationFrame(render_message);
		} else {
			setTimeout(function() {
				message.style.display = "none";
				message.style.opacity = 0;
			}, 200)
		}
	}
}

function takeRank() {
	loadXMLDoc("GET", "/game_server/tycoon/tycoon_rank_no_user/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			var rankMenuSection = document.querySelector(".rankMenu_section");
			var rankstr = "";
			rankMenu.style.display = "block";
			firstPage.style.display = "none";
			for(var i = 0; i < back["obj"]["rank"].length; i++) {
				var str = '<div class="rankSectionCell"><span>' + back["obj"]["rank"][i]["rank"] + '</span><span>' + back["obj"]["rank"][i]["name"] + '</span><span>' + back["obj"]["rank"][i]["best_income"] + '</span></div>';
				rankstr += str;
			}
			rankMenuSection.innerHTML = rankstr;
		}
	}, {});
}

function backMenu() {
	clearInterval(timeTimer);
	timeTimer = null;
	gameEnd.style.display = "none";
	rankMenu.style.display = "none";
	firstPage.style.display = "block";

}

function sendTip() {
	if(dataGame["cash"] < dataGame["debt"]) {
		document.querySelector(".sendTip").style.height = "4.2rem";
		document.querySelector(".sendTipMessage").innerHTML = "你的现金不足以支付全部欠款，还款将会消耗您所有的现金，请谨慎还款!";
	} else if(dataGame["debt"] == 0) {
		occMessage("无债一身轻啊~~~");
	} else if(dataGame["cash"] >= dataGame["debt"]) {
		document.querySelector(".sendTip").style.height = "4.2rem";
		document.querySelector(".sendTipMessage").innerHTML = "你将还清全部债款，请确保你仍有足够本金或商品继续游戏。";
	}
}

function cancelSendTip() {
	document.querySelector(".sendTip").style.height = "0rem";
}

function payDebt() {
	loadXMLDoc("GET", "/game_server/tycoon/" + dataGame.gameid + "/pay_debt/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			//还款成功
			dataGame["cash"] = back["obj"]["game_status"]["cash"];
			dataGame["debt"] = back["obj"]["game_status"]["debt"];
			render();
			cancelSendTip();
		} else {
			occMessage("好像出现了什么问题，重新试下~");
			cancelSendTip();
		}
	}, {})
}

function buyHouseTip() {
	if(dataGame["warehouse_total"] < 110) {
		document.querySelector(".buyHouseTip").style.height = "5.3rem";
	} else {
		occMessage("仓库已经扩充满了哦~");
	}
}

function cancelTip() {
	document.querySelector(".buyHouseTip").style.height = "0rem";
}

function buyhouse() {
	loadXMLDoc("POST", "/game_server/tycoon/buy_warehouse/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			dataGame["warehouse_left"] = back["game_status"]["warehouse_left"];
			dataGame["warehouse_total"] = back["game_status"]["warehouse_total"];
			cancelTip();
			render();
			if(tradeDOM.status == 0) {
				buy(tradeDOM.item, tradeDOM.itemsname);
			}
		} else {
			occMessage("指数不足，无法购买。");
			cancelTip();
		}
	}, {
		count: 1
	});
}

function giveup() {
	loadXMLDoc("GET", "/game_server/tycoon/" + dataGame.gameid + "/end_game/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			//游戏结束
			clearInterval(timeTimer);
			timeTimer = null;
			overRank();
		}
	}, {})
}

function leaveGameTip() {
	var leave = document.querySelector(".leaveGameTip");
	leave.style.height = "4rem";
}

function cancelLeaveTip() {
	var leave = document.querySelector(".leaveGameTip");
	leave.style.height = "0rem";
}

function overRank() {
	loadXMLDoc("GET", "/game_server/tycoon/" + dataGame.gameid + "/tycoon_rank/", function(data) {
		var back = JSON.parse(data);
		if(back["ok"] == true) {
			//游戏结束
			gamePage.style.display = "none";
			var rankSection = document.querySelector(".rankSection");
			var gameMessage = document.querySelector(".gameMesssage");
			if(back["obj"]["in_rank"] == true) {
				var rich = "恭喜你进入富豪榜";
				gameMessage.innerHTML = '<div>列车到达终点，本次赚了<span>' + back["obj"]["income"] + '</span>元</div><div>' + rich + '</div><div>你的最好成绩：<span>' + back["obj"]["best_income"] + '</span>元</div>';
			} else if(back["obj"]["income"] > 0) {
				var rich = "很遗憾未进入富豪榜";
				gameMessage.innerHTML = '<div>列车到达终点，本次赚了<span>' + back["obj"]["income"] + '</span>元</div><div>' + rich + '</div><div>你的最好成绩：<span>' + back["obj"]["best_income"] + '</span>元</div>';
			} else {
				gameMessage.innerHTML = '<div style="font-size:0.65rem">本次经营失败，被乘警赶下火车，无颜回家，露宿街头....</div>';
			}
			var sectionstr = "";
			for(var i = 0; i < back["obj"]["rank"].length; i++) {
				var str = '<div class="rankSectionCell"><span>' + back["obj"]["rank"][i]["rank"] + '</span><span>' + back["obj"]["rank"][i]["name"] + '</span><span>' + back["obj"]["rank"][i]["best_income"] + '</span></div>';
				sectionstr += str;
			}
			rankSection.innerHTML = sectionstr;
			gameEnd.style.display = "block";

		}
	}, {})
}