var wowpmonitor;
var monitor;
var dossierchart;
//监控文件
function monitorStart() {
	//启动更新程序
	console.log("monitor start");
	monitor=cp.spawn(baseurl+"dossier\\main.exe",['monitor']);
	monitor.stdout.on('data', function (data) {
	});
	monitor.stderr.on('data', function (data) {
	});
}
function wowpStart() {
	//启动更新程序
	console.log("wowpmonitor start");
	wowpmonitor=cp.spawn("apps\\dossier\\main.exe",['wowpmonitor']);
	wowpmonitor.stdout.on('data', function (data) {
		window.setTimeout(function() {
			changeApp("wowp\\index.html",'wowp',true);
		}, 5000);
	});
	wowpmonitor.stderr.on('data', function (data) {
	});
}

function playerlist(){
	if ($("#playerpage").html().length>0){
		$("#playerpage").html("");
	}
    nowpage="playerlist";
	$("#playerpage").load("playertable.html #playertable",function(data){
        if(nowpage!="playerlist"){
            return;
        }
		executeSql("select server,name,id from t_fileId",'db',function(data){
            if(nowpage!="playerlist"){
                return;
            }
			var ret=data.toString().split('\n');
			for (var i in ret){
				var info=ret[i].split('|');
				if (info.length<2){
					continue;
				}
				var server='';
				if (info[0]=='south'){
					server='南区';
				}else if (info[0]=='north'){
					server='北区';
				}else {
					server=info[0];
				}
				var tr="<tr><td class='text server'>"+server+"</td><td class='text name'>"+info[1]+"</td><td class='openplayer'><button type='button' class='btn btn-success dossierdetail'>查看详情</button>&nbsp;&nbsp;<button type='button' class='btn btn-danger dossierdelete' id='"+info[2]+"'>删除记录</button></td><td class='hide url'>"+info[0]+"."+info[1]+".html</td></tr>"
				$("#playerbody").append(tr);
			}
			$(".openplayer").each(function(i,e){
				$(this).children(".dossierdetail").click(function(){
					window.open("..\\dossier\\"+$(this).parent().parent().children(".url").text(),"_blank");
				});
				$(this).children(".dossierdelete").click(function(){
					dossierdelete($(this).attr("id"));
				});
			});
			$("#playerpage").show();
		});
	});
}

function dossierdelete(id){
	customConfirm("确认删除"+$("#"+id).parent().parent().children(".server").text()+":"+$("#"+id).parent().parent().children(".name").text(),function(){
		var spawn=cp.spawn(baseurl+"dossier\\main.exe",['dossierdelete',id]);
		spawn.stdout.on('data', function (data) {
			console.log(repairCharset(data));
		});
		spawn.stderr.on('data', function (data) {
			console.log(repairCharset(data));
		});
		$("#"+id).parent().parent().remove();
		clearDossier();
	});
}

//获取显示近期战斗
function showRecentBattles(update) {
	//1.读取当前用户信息
	var sql="select a.*,b.lasttime from (select fileid,lasttime from t_tankList where lasttime=(select max(lasttime) from t_tankList)) b,t_fileId a where a.id=b.fileid limit 1";
	executeSql(sql,'db',function(data){
		var ret=data.toString().split('|');
		res['id']=ret[0];
		res['name']=ret[1];
		res['server']=ret[2];
		var server='';
		if (res['server']=='south'){
			server='南区';
		}else if (res['server']=='north'){
			server='北区';
		}else {
			server=res['server'];
		}
		res['aid']=ret[3];
		res['time']=ret[4];
		//有更新
		if ($("#lasttime").text()!=res['time']){
			if(update){
				$("#user").html('<a target="_blank" href="javascript:window.open(\'http://rank.kongzhong.com/index.html?name='+res['name']+'&area='+res['server']+'\',\'_new\')" class="username">'+server+':&nbsp;&nbsp;'+res['name']+'</a>');
			}else{
			//更新用户名
				$("#user").html('<a target="_blank" href="javascript:window.open(\'http://rank.kongzhong.com/index.html?name='+res['name']+'&area='+res['server']+'\',\'_new\')" class="username">'+server+':&nbsp;&nbsp;'+res['name']+'</a><div id="lasttime">'+res['time']+'</div>');
				
				getChanges(res['id']);
			}
		}
	},function(){
		//无数据时
		$("#user").html('&nbsp;&nbsp;未找到玩家<div id="lasttime">0</div>');
	});
}

function getChanges(fileid){

	if ($("#battlepage").html().length>0){
		$("#battlepage").html("");
	}
	var sql="select * from t_tankChange where fileid="+fileid+" order by lasttime desc limit "+500;
	var totalsql="select * from t_tankList where fileid="+fileid+" and name='total' order by id desc limit 1;"
	$("#battlepage").load("dossier.html .container",function(data){
	
		executeSql(totalsql,'db',function(data){
			var ret=data.toString().split('|');
			var total=initStat("全局");
			ret.unshift(0);
			pushStat(total,ret);
			//设置eff
			if(total['battle']<=0)
				return
				
			if (ret[23]>0){
				ret[17]=1.0*ret[15]/ret[23];
			}
			var capPoint=Math.round(1.0*ret[19]/ret[6]*1000)/1000*0.05
			if (capPoint>0.1)
				capPoint=0.1
			var defPoint=Math.round(1.0*ret[20]/ret[6]*1000)/1000*0.15
			if (defPoint>0.375)
				defPoint=0.375
			total['dmgeff']=800*ret[17]
			if (ret[25]>0)
				total['spoteff']=Math.round(1.0*ret[18]/ret[6]*1000)/1000*ret[24]/ret[25]
			total['capeff']=(capPoint+defPoint)*(total['dmgeff']+total['spoteff'])
			total['eff']=total['dmgeff']+total['spoteff']+total['capeff'];
			
			total['eff']*=total['battle'];
			total['dmgeff']*=total['battle'];
			total['spoteff']*=total['battle'];
			total['capeff']*=total['battle'];
			updateStatTr(total);
			refreshClass();
			executeSql(sql,'db',function(data){
				//id,fileid,name,arena_id,level,type,battle,wins,lose,sur,eff,dameff,spoteff,steff,frag ,damage ,damagerec ,damPoint ,spot ,capture ,defense ,xp ,lasttime ,damStand ,spotPoint ,spotStand ,countryid ,assist
				var line=data.toString().split('\n');
				var eff=[];
				var winrate=[];
				var battle20=initStat("近20场");
				var battle50=initStat("近50场");
				var battle100=initStat("近100场");
				var battleAll=initStat("全记录");
				var day1=initStat("近1日");
				var day7=initStat("近7日");
				var day30=initStat("近30日");
				var now=new Date().getTime()/1000;
				for(var i in line){
					var ret=line[i].split('|');
					if(ret.length<10){
						continue;
					}
					var d = new Date()
					d.setTime(Number(ret[22])*1000);
					var tr="<tr>";
					tr+="<td>"+date2str(d,"yyyy-MM-dd hh:mm:ss")+"</td>";
						tr+="<td>"+ret[2]+"</td>";
					if(ret[6]==1){
						tr+="<td class='"+(ret[7]==1?"win":"lose")+"'>"+(ret[7]==1?"胜":"负")+"</td>";
					}else{
						tr+="<td>"+ret[6]+"战/"+ret[7]+"胜("+Number(ret[7]*100/ret[6]).toFixed(0)+"%)</td>";
					}
					tr+="<td class='int "+getEFFColor(ret[10]/ret[6])+"'>"+ret[10]/ret[6]+"</td>";
					tr+="<td class='int "+getEFFColor(ret[10]/ret[6])+"'>"+ret[11]+"</td>";
					tr+="<td class='int "+getEFFColor(ret[10]/ret[6])+"'>"+ret[12]+"</td>";
					tr+="<td class='int "+getEFFColor(ret[10]/ret[6])+"'>"+ret[13]+"</td>";
					tr+="<td class='"+(ret[6]>1?"double":"")+"'>"+ret[14]/ret[6]+"</td>";
					tr+="<td class='int'>"+ret[15]/ret[6]+"</td>";
					tr+="<td class='"+(ret[6]>1?"double":"")+"'>"+ret[18]/ret[6]+"</td>";
					tr+="<td class='int'>"+ret[27]/ret[6]+"</td>";
					tr+="<td class='int'>"+ret[16]/ret[6]+"</td>";
					tr+="<td class='"+(ret[6]>1?"double":"")+"'>"+ret[19]/ret[6]+"</td>";
					tr+="<td class='"+(ret[6]>1?"double":"")+"'>"+ret[20]/ret[6]+"</td>";
					tr+="<td class='int'>"+ret[21]/ret[6]+"</td>";
					tr+="</tr>";
					$("#dossierbody").append(tr);
					eff.unshift({color:getEFFColorCode(ret[10]/ret[6]),x:Number(ret[22])*1000,y:Number(Number(ret[10]/ret[6]).toFixed(0))});
					winrate.unshift([Number(ret[22])*1000,Number(Number(total['win']*100/total['battle']).toFixed(3))]);
					total['battle']-=Number(ret[6]);
					total['win']-=Number(ret[7]);
					battleAll=pushStat(battleAll,ret);
					if(now-ret[22]<1*24*60*60){
						day1=pushStat(day1,ret);
					}
					if(now-ret[22]<7*24*60*60){
						day7=pushStat(day7,ret);
					}
					if(now-ret[22]<30*24*60*60){
						day30=pushStat(day30,ret);
					}
					if(Number(battle20['battle'])<20){
						battle20=pushStat(battle20,ret);
					}
					if(Number(battle50['battle'])<50){
						battle50=pushStat(battle50,ret);
					}
					if(Number(battle100['battle'])<100){
						battle100=pushStat(battle100,ret);
					}
				}
				$("#dossiertable").tablesorter({
					sortInitialOrder : "desc",
					sortList : [ [ 0, 1 ] ]
				});
				makeChart(eff,winrate);
				updateStatTr(battle20);
				updateStatTr(battle50);
				updateStatTr(battle100);
				updateStatTr(battleAll);
				updateStatTr(day1);
				updateStatTr(day7);
				updateStatTr(day30);
				refreshClass();
				//dossierchart.series[1].setData({"data":eff});
			});
		});
	});
}
function initStat(name){
	var stat=new Array();
	stat['name']=name;
	stat['battle']=0;
	stat['win']=0;
	stat['eff']=0;
	stat['dmgeff']=0;
	stat['spoteff']=0;
	stat['capeff']=0;
	stat['kill']=0;
	stat['dmg']=0;
	stat['spot']=0;
	stat['ast']=0;
	stat['cap']=0;
	stat['def']=0;
	stat['exp']=0;
	return stat;
}
function pushStat(stat,ret){
	stat['battle']+=Number(ret[6]);
	stat['win']+=Number(ret[7]);
	stat['eff']+=Number(ret[10]);
	stat['dmgeff']+=Number(ret[11])*Number(ret[6]);
	stat['spoteff']+=Number(ret[12])*Number(ret[6]);
	stat['capeff']+=Number(ret[13])*Number(ret[6]);
	stat['kill']+=Number(ret[14]);
	stat['dmg']+=Number(ret[15]);
	stat['spot']+=Number(ret[18]);
	stat['ast']+=Number(ret[27]);
	stat['cap']+=Number(ret[19]);
	stat['def']+=Number(ret[20]);
	stat['exp']+=Number(ret[21]);
	return stat;
}

function updateStatTr(stat){
	var tr="<tr>";
	tr+="<td>"+stat['name']+"</td>";
	tr+="<td>"+stat['battle']+"</td>";
	if(stat['battle']>0){
		tr+="<td class='"+getWinRatingColor(100.0*stat['win']/stat['battle'])+"'>"+Number(100.0*stat['win']/stat['battle']).toFixed(1)+"%</td>";
		tr+="<td class='int "+getEFFColor(stat['eff']/stat['battle'])+"'>"+stat['eff']/stat['battle']+"</td>";
		tr+="<td class='int "+getEFFColor(stat['eff']/stat['battle'])+"'>"+stat['dmgeff']/stat['battle']+"</td>";
		tr+="<td class='int "+getEFFColor(stat['eff']/stat['battle'])+"'>"+stat['spoteff']/stat['battle']+"</td>";
		tr+="<td class='int "+getEFFColor(stat['eff']/stat['battle'])+"'>"+stat['capeff']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['kill']/stat['battle']+"</td>";
		tr+="<td class='int'>"+stat['dmg']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['spot']/stat['battle']+"</td>";
		tr+="<td class='int'>"+stat['ast']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['cap']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['def']/stat['battle']+"</td>";
		tr+="<td class='int'>"+stat['exp']/stat['battle']+"</td>";
	}else{
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
		tr+="<td>"+"-"+"</td>";
	}
	tr+="</tr>";
	$("#totalbody").append(tr);
}

function makeChart(eff,winrate){
	//初始化图表	
	$('#stockChart').highcharts('StockChart', {
		chart:{
			backgroundColor: 'rgba(0,0,0,0)',
			height: 250,
			events:{
				load:	function(){
							try{
							if(this.series[1].groupedData){
								for (var i = 0; i < this.series[1].groupedData.length; i++) {
									for (var j in this.series[1].groupedData[i].pointAttr){
										if(this.series[1].groupedData[i].pointAttr[j].fill=="#2f7ed8"){
											this.series[1].groupedData[i].update({ color: getEFFColorCode(this.series[1].groupedData[i].y)}, false, false);
										}
										break;
									}
								}
							}
							} catch(e){
							}
						},
				redraw:	function(){
							try{
								if(this.series[1].groupedData!=null){
									for (var i = 0; i < this.series[1].groupedData.length; i++) {
										for (var j in this.series[1].groupedData[i].pointAttr){
											if(this.series[1].groupedData[i].pointAttr[j].fill=="#2f7ed8"){
												this.series[1].groupedData[i].update({ color: getEFFColorCode(this.series[1].groupedData[i].y)}, false, false);
											}
											break;
										}
									}
								}
							} catch(e){
								console.log(e);
							}
						}
			}
		},
		title: {
			text: '',
			x: -20 //center
		},
		navigator:{
			maskFill : 'rgba(0,0,0,0.4)',
			series: {
				type: 'line',
				fillOpacity: 1,
				dataGrouping: {
					smoothed: true
				},
				lineWidth: 1,
				marker: {
					enabled: false
				}
			},
			xAxis: {
				labels: {
					align: 'left',
					style: {
						color: '#888'
					},
					x: 3,
					y: -4
				}
			}
		},
		xAxis: {
        	type: 'datetime',
			labels:{
				maxStaggerLines:1
			},
        	dateTimeLabelFormats: {
				second: '%H:%M:%S',
				minute: '%H:%M',
				hour: '%H:%M',
				day: '%m月%d日',
				week: '%m月%d日',
				month: '%Y年%m月',
				year: '%Y'
			}
    	},
		plotOptions: {
			column: {
				dataGrouping: {
					smoothed:true,
					approximation:'average',
					dateTimeLabelFormats:{
						millisecond: ['%m月%d日, %H:%M:%S.%L', '%m月%d日, %H:%M:%S.%L', '-%H:%M:%S.%L'],
						second: ['%m月%d日 %H:%M:%S', '%m月%d日 %H:%M:%S', '-%H:%M:%S'],
						minute: ['%m月%d日 %H:%M', '%m月%d日 %H:%M', '-%H:%M'],
						hour: ['%m月%d日 %H:%M', '%m月%d日 %H:%M', '-%H:%M'],
						day: ['%Y-%m月%d日', '%Y-%m月%d日', '-%m月%d日'],
						week: ['%Y', '%Y', '-%Y'],
						month: ['%B %Y', '%B', '-%B %Y'],
						year: ['%Y', '%Y', '-%Y']
					},
					units: [[
						'minute',
						[15, 30]
					], [
						'hour',
						[1, 2, 4, 8, 12]
					], [
						'day',
						[1,2,4,8]
					]]
				},
				borderWidth: 0
			},
			
			line: {
				dataGrouping: {
					smoothed:true,
					approximation:'average',
					dateTimeLabelFormats:{
						millisecond: ['%m月%d日, %H:%M:%S.%L', '%m月%d日, %H:%M:%S.%L', '-%H:%M:%S.%L'],
						second: ['%m月%d日 %H:%M:%S', '%m月%d日 %H:%M:%S', '-%H:%M:%S'],
						minute: ['%m月%d日 %H:%M', '%m月%d日 %H:%M', '-%H:%M'],
						hour: ['%m月%d日 %H:%M', '%m月%d日 %H:%M', '-%H:%M'],
						day: ['%Y-%m月%d日', '%Y-%m月%d日', '-%m月%d日'],
						week: ['%Y', '%Y', '-%Y'],
						month: ['%B %Y', '%B', '-%B %Y'],
						year: ['%Y', '%Y', '-%Y']
					},
					units: [[
						'minute',
						[15, 30]
					], [
						'hour',
						[1, 2, 4, 8, 12]
					], [
						'day',
						[1,2,4,8]
					]]
				},
				borderWidth: 0
			}
		},
		rangeSelector: {
			labelStyle:{
				color:'#ddd'
			},
			buttonSpacing: 2,
			buttons: [{
				type: 'hour',
				count: 1,
				text: '1H'
			}, {
				type: 'hour',
				count: 8,
				text: '8H'
			}, {
				type: 'day',
				count: 1,
				text: '1D'
			}, {
				type: 'day',
				count: 7,
				text: '7D'
			}, {
				type: 'month',
				count: 1,
				text: '1M'
			}, {
				type: 'all',
				text: 'ALL'
			}],
			inputEnabled:false
		},
		yAxis: [{
			title: {
				text: ''
			},
			gridLineColor:'#dddddd',
			labels:{
				style: {
					color: '#dddddd'
				}
			},
			id: '1',
			opposite: false
		},
		{
			title: {
				text: ''
			},
			gridLineColor:'#dddddd',
			labels:{
				style: {
					color: '#dddddd'
				}
			},
			id: '2',
			opposite: true
		}],
		tooltip: {
			valueDecimals: 2,
			style: {
				color: '#ccc',
				fontSize: '12px',
				padding: '8px'
			},
			backgroundColor: 'rgba(0,0,0,0.5)',
			dateTimeLabelFormats:{
				second: '%H:%M:%S',
				minute: '%H:%M',
				hour: '%H:%M',
				day: '%m月%d日',
				week: '%m月%d日',
				month: '%Y年%m月',
				year: '%Y年'
			}
		},
		legend: {
			enabled: false
		},
		series: [
		{
			name: '胜率走势',
			color: '#eeeeee',
			yAxis: '2',
			marker:{
				enabled:false
			},
			data: winrate
		},
		{
			name: '单场效率',
			type: 'column',
			marker:{
				enabled:false
			},
			yAxis: '1',
			data: eff
		}]
	});
	dossierchart = $('#stockChart').highcharts();
}

function clearDossier(){
	var ls=cp.exec('del /Q/F "%appdata%\\wargaming.net\\worldoftanks\\dossier_cache\\*"',{encoding: 'binary'},function(err, stdout, stderr){
		if (err){
			message.send("del fail "+repairCharset(err),"danger");
		}
		if (stdout){
			console.log("stdout",repairCharset(stdout));
		}
		if (stderr){
			console.log("1",repairCharset(stderr));
		}
	});  
}