var replayMonitor;
//监控文件
function replayStart() {
	//启动更新程序
	if(!checkERROR(config.get('replay'))&&config.get('replay')){
		//console.log("replay monitor start:"+config.get('path'));
		replayMonitor=cp.spawn(baseurl+"dossier\\main.exe",['replay',config.get('path')+"/replays/"]);
	}
}

function replayList(){
	if ($("#replaypage").html().length>0){
		$("#replaypage").html("");
	}
    nowpage="replaypage";
	$("#replaypage").load("replaypage.html #replayContent",function(data){
        if(nowpage!="replaypage"){
            return;
        }
		executeSql("select a.arena_id, a.account_db_id, a.vehicle_type_cd, a.battle_type_id, a.map_type_id, a.battle_level_id, a.game_type_id, a.win_type_id, a.win_team_id, a.duration, a.start_dt, a.team_id, a.frags, a.spotted, a.damage_deal, a.damage_assist, a.capture_point, a.dropped_capture_point,a.remained_hp, a.life_time_sec, a.credit, a.xp, a.mark, b.filename, b.account_db_id, b.vehicle_type_cd, b.battle_type_id, b.game_type, b.battle_time, b.player_name, b.map_id, b.server_name, b.arena_id,b.version from t_replay b left join t_battleResult a on a.arena_id=b.arena_id and a.account_db_id=b.account_db_id",'db',function(data){
            if(nowpage!="replaypage"){
                return;
            }
			var ret=data.toString().split('\n');
			var maplist=new Array();
			var playerlist=new Array();
			var tanklist=new Array();
			var versionlist=new Array();
			var resultlist=new Array();
			var marklist=new Array();
			var tanktypelist=new Array();
			var tanktierlist=new Array();
			var tankcountrylist=new Array();
			for (var i in ret){
				var result=ret[i].split('|');
				if (result.length<32){
					continue;
				}
				var tmpreplay=getReplay(result)
				var tr="<tr class='replaytr'>";
				var d = new Date(tmpreplay['battle_time']*1000)
				var tank=getTankByVid(tmpreplay['vehicle_type_cd']);
				var map=getMapByMid(tmpreplay['map_type_id']);
				if(tank==null){
					console.log("err vid:"+tmpreplay['vehicle_type_cd']);
					continue;
				}
				if(map==null){
					console.log("err mid:"+tmpreplay['map_type_id']);
					continue;
				}
				tr+="<td><input type='checkbox'></td>";
				tr+="<td class='date' style='width:80px;'>"+date2str(d,"yyyy-MM-dd hh:mm:ss")+"</td>";
				tr+="<td class='version visible-md visible-lg'>"+tmpreplay['version']+"</td>";
				tr+="<td class='player'>"+tmpreplay['server_name']+":"+tmpreplay['player_name']+"</td>";
				tr+="<td class='tank'>"+tank["alias"]+"</td>";
				tr+="<td class='map visible-md visible-lg'>"+getGameTypeById(tmpreplay['game_type'])+":"+map.mapname+"</td>";
				if(tmpreplay['arena_id']!=0){
					var battleresult=(tmpreplay['win_team_id']==tmpreplay['team_id']?1:(tmpreplay['win_team_id']==0?0:-1));
					var winresult=""
					if(battleresult==1){
						winresult="胜";
					}else if(battleresult==0){
						winresult="平";
					}else{
						winresult="负";
					}
					tr+="<td class='result result"+battleresult+"'>"+winresult+"</td>";
					
					tr+="<td class='damagedeal'>"+tmpreplay['damage_deal']+"</td>";
					tr+="<td class='frags'>"+tmpreplay['frags']+"</td>";
					tr+="<td class='damageassist'>"+tmpreplay['damage_assist']+"</td>";
					tr+="<td class='spotted visible-md visible-lg'>"+tmpreplay['spotted']+"</td>";
					tr+="<td class='capture visible-lg'>"+tmpreplay['capture_point']+"</td>";
					tr+="<td class='defense visible-lg'>"+tmpreplay['dropped_capture_point']+"</td>";
					tr+="<td class='credit visible-md visible-lg'>"+tmpreplay['credit']+"</td>";
					tr+="<td class='xp visible-md visible-lg'>"+tmpreplay['xp']+"</td>";
					
					var mark=getMarkByTier(tmpreplay['mark']);
					tr+="<td class='mark'>"+mark+"</td>";
					
					
					if(winresult in resultlist){
						resultlist[winresult]++;
					}else{
						resultlist[winresult]=1;
					}
					if(mark in marklist){
						marklist[mark]++;
					}else{
						marklist[mark]=1;
					}
				}else{
					tr+="<td class='result'>-</td>";
					tr+="<td class='damagedeal'>-</td>";
					tr+="<td class='frags'>-</td>";
					tr+="<td class='damageassist'>-</td>";
					tr+="<td class='spotted visible-md visible-lg'>-</td>";
					tr+="<td class='capture visible-lg'>-</td>";
					tr+="<td class='defense visible-lg'>-</td>";
					tr+="<td class='credit visible-md visible-lg'>-</td>";
					tr+="<td class='xp visible-md visible-lg'>-</td>";
					tr+="<td class='mark'>-</td>";
				}
				//操作
				tr+="<td>"+(tmpreplay['arena_id']!=0?"<button type='button' class='btn btn-primary btn-xs replaydetail'>详情</button>&nbsp;":"")+"<button type='button' class='btn btn-primary btn-xs playreplay'>播放</button></td>";//<button type='button' class='btn btn-primary btn-xs playsim'>模拟</button>
				tr+="<td class='hidetd filename'>"+tmpreplay['filename']+"</td>";
				tr+="<td class='hidetd accountdbid'>"+tmpreplay['account_db_id']+"</td>";
				tr+="<td class='hidetd arenaid'>"+tmpreplay['arena_id']+"</td>";
				tr+="<td class='hidetd tanktype'>"+tank["type"]+"</td>";
				var tier=tank["level"]+"级";
				tr+="<td class='hidetd tanktier'>"+tier+"</td>";
				tr+="<td class='hidetd tankcountry'>"+tank['country']+"</td>";
				tr+="</tr>"
				$("#replaybody").append(tr);
				
				//添加过滤
				var player=tmpreplay['server_name']+":"+tmpreplay['player_name']
				if(getGameTypeById(tmpreplay['game_type'])+":"+map.mapname in maplist){
					maplist[getGameTypeById(tmpreplay['game_type'])+":"+map.mapname]++;
				}else{
					maplist[getGameTypeById(tmpreplay['game_type'])+":"+map.mapname]=1;
				}
				if(player in playerlist){
					playerlist[player]++;
				}else{
					playerlist[player]=1;
				}
				if(tank['alias'] in tanklist){
					tanklist[tank['alias']]++;
				}else{
					tanklist[tank['alias']]=1;
				}
				if(tmpreplay['version'] in versionlist){
					versionlist[tmpreplay['version']]++;
				}else{
					versionlist[tmpreplay['version']]=1;
				}
				if(tank['type'] in tanktypelist){
					tanktypelist[tank['type']]++;
				}else{
					tanktypelist[tank['type']]=1;
				}
				if(tier in tanktierlist){
					tanktierlist[tier]++;
				}else{
					tanktierlist[tier]=1;
				}
				if(tank['country'] in tankcountrylist){
					tankcountrylist[tank['country']]++;
				}else{
					tankcountrylist[tank['country']]=1;
				}
			}
			$(".playreplay").click(function(){
				playReplay($(this).parent().parent().children(".filename").text());
			});
			$(".replaydetail").click(function(){
				window.open("battledetail.html?arenaid="+$(this).parent().parent().children(".arenaid").text()+"&aid="+$(this).parent().parent().children(".accountdbid").text());
			});
			$(".playsim").click(function(){
				window.open("..\\replaySim\\index.html?"+config.get('path')+"\\replays\\"+$(this).parent().parent().children(".filename").text());
			});

			if($("#replaybody").length>0){
				$("table#replaytable").tablesorter({
					sortInitialOrder : "desc",
					sortList : [ [ 1, 1 ] ]
				});
			}
			replayRefreshPage();
			createFilterLabel(maplist,"map","primary");
			createFilterLabel(playerlist,"player","info");
			createFilterLabel(tanklist,"tank","warning");
			createFilterLabel(versionlist,"version","default");
			createFilterLabel(resultlist,"result","primary");
			createFilterLabel(marklist,"mark","danger");
			createFilterLabel(tanktypelist,"tanktype","default");
			createFilterLabel(tanktierlist,"tanktier","danger");
			createFilterLabel(tankcountrylist,"tankcountry","info");
			$(".filterbtn").click(function(){
				if($(this).parent().hasClass("tab-pane")){
					$("#filterBy").append(this);
				}else{
					$("#"+$(this).attr("for")).append(this);
				}
			});
		});
		$("#checkall").click(function(){
			if($(":checkbox:visible").size()==$(":checkbox:visible[checked='checked']").size()){
				$(":checkbox:visible").each(function(){
					$(this).attr("checked",false);
				});
			}else{
				$(":checkbox:visible").each(function(i,n){
					$(this).attr("checked",true);
					$(n)[0].checked="checked";
				});
			}
		});
		$("#delCheckedReplay").click(function(){
			customConfirm("确认删除选中的录像记录及文件",function(){
                var dm=new DeleteManager();
				$(":checkbox:visible").each(function(i,n){
					if($(n)[0].checked){
						var tr=$(this).parent().parent();
						var aid=tr.children(".accountdbid").text();
						var file=tr.children(".filename").text();
						executeSql("delete from t_replay where filename='"+file+"' and account_db_id='"+aid+"'",'db');
                        var paths=config.get('path')+"\\replays\\"+file;
                        dm.add(paths,paths);
						tr.remove();
					}
				});
                dm.start();
			});
		});
		$("#copyReplay").click(function(){
			customConfirm("确认复制选中的录像文件到<span style='color:red'>沙盘目录/copyreplay</span>",function(){
                var cm=new CopyManager(getUniqueId(),"复制录像",false);

                if(!fs.existsSync("copyreplay")) {
                    fs.mkdirSync("copyreplay", 0755);  //位置不存在时创建
                }
				$(":checkbox:visible").each(function(i,n){
					if($(n)[0].checked){
						var tr=$(this).parent().parent();
						var file=tr.children(".filename").text();
						cm.add(config.get('path')+"\\replays\\"+file,"copyreplay\\"+file);
					}
				});
                cm.start();
			});
		});
		$("#filterReplay").click(function(){
			$(".replaytr").show();
			var accept=[];
			var condition=new Array();
			$("#filterBy").children(".filterbtn").each(function(i,n){
				var text=$(n).html();
				accept.push(text.split("&nbsp;")[0]);
				condition[$(n).attr("for")]=0;
			})
			for(var cond in condition){
				$(".replaytr:visible").each(function(i,n){
					$(n).hide();
					for(var key in accept){
						if(accept[key]==$(n).children("."+cond).text()){
							$(n).show();
						}
					}
				})
			}
			replayRefreshPage();
		});
		$("#filterCancel").click(function(){
			$(".replaytr").show();
			replayRefreshPage();
		});
        $("#refreshall").click(function(){
            customConfirm('刷新功能用于将录像数据支持新功能时使用，耗时较长，请确认你要执行该功能',function(e){
                var refresh=cp.spawn(baseurl+"dossier\\main.exe",['replayrefresh',config.get('path')+"/replays/"]);
                if(fs.existsSync(config.get('path')+"/wsbreplays/")) {
                    var refresh2 = cp.spawn(baseurl + "dossier\\main.exe", ['replayrefresh', config.get('path') + "/wsbreplays/"]);
                }
            })
        });
	});
	$("#repalypage").append('<iframe style="display: none;" src="http://rank.kongzhong.com/wsbreplay.html"></iframe>');
}

function playReplay(paths) {
    if (checkERROR(config.get('path'))) {
        customAlert("请先设置游戏路径", 'warning');
        return;
    }
    if (fs.existsSync(config.get('path') + "\\replays\\" + paths)) {
        customAlert("开始播放录像", "success");
        cp.spawn(config.get('path')+"\\WorldOfTanks.exe",[config.get('path') + "\\replays\\" + paths]);
    }
    else {
        customAlert("录像文件不存在!<br>" + config.get('path') + "\\replays\\" + paths, 'warning');
    }
}

var perpage=50;
function replayRefreshPage(){
	var maxindex=0;
	
	$(".replaytr").each(function(index,element){
		$(this).removeAttr("pageindex");
	});
	$(".replaytr:visible").each(function(index,element){
		$(this).attr("pageindex",index);
		maxindex=index;
	});
	$("#pagefilter").html('');
	for(var i=1;(i-1)*perpage<=maxindex;i++){
		var button="<button type='button' page="+i+" class='btn btn-primary btn-xs replaypage'>"+i+"</button>&nbsp;"
		$("#pagefilter").append(button);
	}
	$("#pagefilter").append("总共"+(maxindex+1)+"个录像")
	$("button.replaypage").click(function(){
		var page=Number($(this).attr("page"));
		replayChangePage(page);
	});
	replayChangePage(1);
}
function replayChangePage(page){
	$(".replaytr").each(function(index,element){
		$(this).hide();
		if($(this).attr("pageindex")){
			var i=Number($(this).attr("pageindex"));
			if(i>=(page-1)*perpage&&i<page*perpage){
				$(this).show();
			}
		}
	});
}

function getReplay(result){
	var tmpreplay = new Array();
	tmpreplay['filename']=result[23];
	tmpreplay['account_db_id']=result[24];
	tmpreplay['vehicle_type_cd']=result[25];
	tmpreplay['battle_type_id']=result[26];
	tmpreplay['game_type']=result[27];
	tmpreplay['battle_time']=result[28];
	tmpreplay['player_name']=result[29];
	tmpreplay['map_type_id']=result[30];
	tmpreplay['server_name']=result[31];
	tmpreplay['arena_id']=result[32];
	tmpreplay['version']=result[33];
	if(tmpreplay['arena_id']!=0){
		tmpreplay['account_db_id']=result[1];
		tmpreplay['battle_level_id']=result[5];
		tmpreplay['game_type_id']=result[6];
		tmpreplay['win_type_id']=result[7];
		tmpreplay['win_team_id']=result[8];
		tmpreplay['duration']=result[9];
		tmpreplay['start_dt']=result[10];
		tmpreplay['team_id']=result[11];
		tmpreplay['frags']=result[12];
		tmpreplay['spotted']=result[13];
		tmpreplay['damage_deal']=result[14];
		tmpreplay['damage_assist']=result[15];
		tmpreplay['capture_point']=result[16];
		tmpreplay['dropped_capture_point']=result[17];
		tmpreplay['remained_hp']=result[18];
		tmpreplay['life_time_sec']=result[19];
		tmpreplay['credit']=result[20];
		tmpreplay['xp']=result[21];
		tmpreplay['mark']=result[22];
	}
	return tmpreplay;
}

function createFilterLabel(labelArray,cls,type){
	for (var label in labelArray){
		var label="<button type='button' for='"+cls+"' class='btn btn-md filterbtn btn-"+type+"'>"+label+"&nbsp;<span class='badge'>"+labelArray[label]+"</span></button>";
		$("#"+cls).append(label);
	}
}

function getMarkByTier(mark){
	if(mark==0){
		return "无";
	}
	if(mark==1){
		return "三级";
	}
	if(mark==2){
		return "二级";
	}
	if(mark==3){
		return "一级";
	}
	if(mark==4){
		return "特级";
	}
	return "未知";
}

function getGameTypeById(id){
	if(id=="ctf"){
		return "标准";
	}
	if(id=="nations"){
		return "国战";
	}
	if(id=="domination"){
		return "夺旗";
	}
	if(id=="assault"){
		return "攻防";
	}
	return "未知类型";
}

function getCountryById(cid){
	if (cid==-1){
		return "未知";
	}
	if (cid==0){
		return "苏联";
	}
	if (cid==1){
		return "德国";
	}
	if (cid==2){
		return "美国";
	}
	if (cid==3){
		return "中国";
	}
	if (cid==4){
		return "法国";
	}
	if (cid==5){
		return "英国";
	}
	if (cid==6){
		return "日本";
	}
	return "";
}

function getPremium(id){
	if(id==-1){
		return "未知";
	}
	if (id==0){
		return "银币车";
	}
	if (id==1){
		return "金币车";
	}
	return "";
}