var wowpmonitor;
var monitor;
var dossierchart;
//监控文件
function wowpStart() {
	//启动更新程序
	console.log("monitor start");
	wowpmonitor=cp.spawn("apps\\dossier\\main.exe",['wowpmonitor']);
	wowpmonitor.stdout.on('data', function (data) {
		console.log(data.toString())
	});
	wowpmonitor.stderr.on('data', function (data) {
		console.log(data.toString())
	});
}

function wowpStop(){
	if(wowpmonitor){
		console.log("kill wowpmonitor");
		wowpmonitor.kill();
		wowpmonitor=null;
	}
}

function monitorStart() {
	//启动更新程序
	console.log("monitor start");
	monitor=cp.spawn("apps\\dossier\\main.exe",['monitor']);
	monitor.stdout.on('data', function (data) {
		window.setTimeout(function() {
			changeApp("..\\index.html",'wot',true);
		}, 5000);
	});
}
function monitorStop(){
	if(monitor){
		console.log("kill monitor");
		monitor.kill();
		monitor=null;
	}
}

function playerlist(){
	if ($("#playerpage").html().length>0){
		$("#playerpage").html("");
	}
	$("#playerpage").load("playertable.html #playertable",function(data){
		executeSql("select a.aid,a.name from t_planeUser a",'wowpdb',function(data){
			var ret=data.toString().split('\n');
			for (i in ret){
				var info=ret[i].split('|');
				if (info.length<2){
					continue;
				}
				var aid=info[0];
				var name=info[1];
				var server='';
				if (aid>1800000000){
					server='南区';
				}else{
					server='北区';
				}
				var tr="<tr id='"+aid+"'><td class='text server'>"+server+"</td><td class='text name'>"+name+"</td><td class='openplayer'><button type='button' class='btn btn-success dossierdetail'>查看详情</button>&nbsp;&nbsp;<button type='button' class='btn btn-danger dossierdelete' id='"+aid+"'>删除记录</button></td></tr>"
				$("#playerbody").append(tr);
			}
			$(".openplayer").each(function(i,e){
				$(this).children(".dossierdetail").click(function(){
                    console.log('test');
                    getList($(this).parent().parent().attr("id"),$(this).parent().parent().children(".name").text());
				});
				$(this).children(".dossierdelete").click(function(){
					dossierdelete($(this).parent().parent().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("apps\\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.aid,a.lasttime,b.name from t_planeUser b,t_planeTotal a where a.aid=b.aid order by a.lasttime desc limit 1";
	executeSql(sql,'wowpdb',function(data){
		var ret=data.toString().split('|');
		var res=new Array();
		res['aid']=ret[0];
		res['time']=ret[1];
		res['name']=ret[2];
		var server='';
		if (res['aid']>1800000000){
			server='南区';
		}else{
			server='北区';
		}
		//有更新
		if ($("#lasttime").text()!=res['time']){
			if(update){
				$("#user").html('<a target="new" href="http://rank.kongzhong.com/wowpweb/index.html?id='+res['aid']+'" class="username">'+server+':&nbsp;&nbsp;'+res['name']+'</a>');
			}else{
			//更新用户名
				$("#user").html('<a target="new" href="http://rank.kongzhong.com/wowpweb/index.html?id='+res['aid']+'" class="username">'+server+':&nbsp;&nbsp;'+res['name']+'</a><div id="lasttime">'+res['time']+'</div>');
				getChanges(res['aid']);
			}
		}
	},function(){
		//无数据时
		$("#user").html('&nbsp;&nbsp;未找到玩家<div id="lasttime">0</div>');
	});
}

function getList(aid,name){
    if ($("#playerdetailpage").html().length>0){
        $("#playerdetailpage").html("");
    }
    var sql="select * from t_planeList where aid="+aid;
    var totalsql="select * from t_planeTotal where aid="+aid+" order by id desc limit 1;"
    $("#playerdetailpage").load("detail.html .container",function(data) {
        executeSql(totalsql,'wowpdb',function(data){
            var ret=data.toString().split('|');
            var total=new Array();
            total.alias=name;
            total.country="";
            total.type="";
            total.level=Number(ret[26]/ret[2]).toFixed(1);
            updateListTr(ret,total);
            var battles=ret[2];
            executeSql(sql,'wowpdb',function(data){
                var maxlevel;
                var line=data.toString().split('\n');
                for(var i in line) {
                    var ret = line[i].split('|');
                    var plane=getPlaneByPid(ret[1]);
					if(checkERROR(plane)){
						continue;
					}
                    if(plane.level>maxlevel){
                        maxlevel=plane.level;
                    }
                    ret[26] = ret[2];
                    updateListTr(ret,plane);
                }
                var modify=getModify(battles,maxlevel);
				$("#playerdetailpage .eff").each(function(){
                    var v=$(this).text();
                    v=v*modify;
                    $(this).text(v);
                });
                changePage();
                refreshClass();
                $("#playerdetailpage").show();
            });
        });
    });
}

function getChanges(aid){

	if ($("#battlepage").html().length>0){
		$("#battlepage").html("");
	}
	var sql="select * from t_planeChange where aid="+aid+" order by lasttime desc limit "+500;
	var totalsql="select * from t_planeTotal where aid="+aid+" order by id desc limit 1;"
	$("#battlepage").load("dossier.html .container",function(data){
		executeSql(totalsql,'wowpdb',function(data){
			var ret=data.toString().split('|');
			var total=initStat("全局");
			ret.unshift(0);
			pushChangeStat(total,ret);
			//设置eff
			if(total['battle']<=0)
				return
			total['battle2']=ret[27]
			updateStatTr(total);
			refreshClass();
			executeSql(sql,'wowpdb',function(data){
				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();
                var maxlevel;
                var battles=total['battle'];
				for(var i in line){
					var ret=line[i].split('|');
					if(ret.length<10){
						continue;
					}
					var c = new Date();
					c.setTime(Number(ret[20])*1000);
					if(ret[21].trim().length==0){
						ret[21]=date2str(c,"yyyy-MM-dd hh:mm:ss");
					}
					var d = new Date(Date.parse(ret[21].replace(/-/g,   "/")));
					var plane=getPlaneByPid(ret[2]);
					if(plane==null){
						continue;
					}
                    if(plane.level>maxlevel){
                        maxlevel=plane.level;
                    }
					var tr="<tr>";
					tr+="<td title='初次使用:"+date2str(c,"yyyy-MM-dd")+"'>"+date2str(d,"yyyy-MM-dd hh:mm:ss")+"</td>";
					tr+="<td>"+plane.alias+"</td>";
					if(ret[3]==1){
						tr+="<td class='"+(ret[5]>0?"team":"")+" "+(ret[4]==1?"win":"lose")+"'>"+(ret[4]==1?"胜":"负")+"</td>";
					}else{
						tr+="<td class='"+(ret[5]>0?"team":"")+"'>"+ret[3]+"战/"+ret[4]+"胜("+Number(ret[4]*100/ret[3]).toFixed(0)+"%)</td>";
					}
					tr+="<td class='eff int "+getEFFColor(ret[23]/ret[3])+"'>"+ret[23]/ret[3]+"</td>";
					tr+="<td class='eff int "+getEFFColor(ret[23]/ret[3])+"'>"+ret[24]/ret[3]+"</td>";
					tr+="<td class='eff int "+getEFFColor(ret[23]/ret[3])+"'>"+ret[25]/ret[3]+"</td>";
					tr+="<td class='eff int "+getEFFColor(ret[23]/ret[3])+"'>"+ret[26]/ret[3]+"</td>";
					tr+="<td class='"+(ret[3]>1?"double":"")+"'>"+ret[9]/ret[3]+"</td>";
					tr+="<td class='"+(ret[3]>1?"double":"")+"'>"+ret[11]/ret[3]+"</td>";
					tr+="<td class='int'>"+ret[10]/ret[3]+"</td>";
					tr+="<td class='"+(ret[3]>1?"double":"")+"'>"+(ret[12]/ret[3]+ret[13]/ret[3])+"</td>";
					tr+="<td class='"+(ret[3]>1?"double":"")+"'>"+ret[15]/ret[3]+"</td>";
					tr+="<td class='int'>"+ret[14]/ret[3]+"</td>";
					tr+="<td class='int'>"+ret[22]/ret[3]+"</td>";
					tr+="</tr>";
					$("#dossierbody").append(tr);
					eff.unshift({color:getEFFColorCode(ret[23]/ret[3]),x:d.getTime(),y:Number(Number(ret[23]/ret[3]).toFixed(0))});
					winrate.unshift([d.getTime(),Number(Number(total['win']*100/total['battle']).toFixed(3))]);
					total['battle']-=Number(ret[3]);
					total['win']-=Number(ret[4]);
					battleAll=pushChangeStat(battleAll,ret);
					if(now- d.getTime()<1*24*60*60*1000){
						day1=pushChangeStat(day1,ret);
					}
					if(now-d.getTime()<7*24*60*60*1000){
						day7=pushChangeStat(day7,ret);
					}
					if(now-d.getTime()<30*24*60*60*1000){
						day30=pushChangeStat(day30,ret);
					}
					if(Number(battle20['battle'])<20){
						battle20=pushChangeStat(battle20,ret);
					}
					if(Number(battle50['battle'])<50){
						battle50=pushChangeStat(battle50,ret);
					}
					if(Number(battle100['battle'])<100){
						battle100=pushChangeStat(battle100,ret);
					}
				}
				if($("#dossierbody").text().trim().length>0){
					$("#dossiertable").tablesorter({
						sortInitialOrder : "desc",
						sortList : [ [ 0, 1 ] ]
					});
				}
				makeChart(eff,winrate);
				updateStatTr(battle20);
				updateStatTr(battle50);
				updateStatTr(battle100);
				updateStatTr(battleAll);
				updateStatTr(day1);
				updateStatTr(day7);
				updateStatTr(day30);
                var modify=getModify(battles,maxlevel);
                $("#battlepage .eff").each(function(){
                    var v=$(this).text();
                    v=v*modify;
                    $(this).text(v);
                });
                refreshClass();
				//dossierchart.series[1].setData({"data":eff});
			});
		});
	});
}
function initStat(name){
	var stat=new Array();
	stat['name']=name;
	stat['battle']=0;
	stat['battle2']=0;
	stat['win']=0;
	stat['eff']=0;
	stat['dmgeff']=0;
	stat['killeff']=0;
	stat['desteff']=0;
	stat['airkill']=0;
	stat['airast']=0;
	stat['airdmg']=0;
	stat['groundkill']=0;
	stat['groundast']=0;
	stat['grounddmg']=0;
	stat['exp']=0;
	return stat;
}
function pushChangeStat(stat,ret){
	stat['battle']+=Number(ret[3]);
	stat['battle2']+=Number(ret[3]);
	stat['win']+=Number(ret[4]);
	stat['eff']+=Number(ret[23]);
	stat['dmgeff']+=Number(ret[24]);
	stat['killeff']+=Number(ret[25]);
	stat['desteff']+=Number(ret[26]);
	stat['airkill']+=Number(ret[9]);
	stat['airast']+=Number(ret[11]);
	stat['airdmg']+=Number(ret[10]);
	stat['groundkill']+=Number(ret[12])+Number(ret[13]);
	stat['groundast']+=Number(ret[15]);
	stat['grounddmg']+=Number(ret[14]);
	stat['exp']+=Number(ret[22]);
	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='eff int "+getEFFColor(stat['eff']/stat['battle2'])+"'>"+stat['eff']/stat['battle2']+"</td>";
		tr+="<td class='eff int "+getEFFColor(stat['eff']/stat['battle2'])+"'>"+stat['dmgeff']/stat['battle2']+"</td>";
		tr+="<td class='eff int "+getEFFColor(stat['eff']/stat['battle2'])+"'>"+stat['killeff']/stat['battle2']+"</td>";
		tr+="<td class='eff int "+getEFFColor(stat['eff']/stat['battle2'])+"'>"+stat['desteff']/stat['battle2']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['airkill']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['airast']/stat['battle']+"</td>";
		tr+="<td class='int'>"+stat['airdmg']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['groundkill']/stat['battle']+"</td>";
		tr+="<td class='"+(stat['battle']>1?"double":"")+"'>"+stat['groundast']/stat['battle']+"</td>";
		tr+="<td class='int'>"+stat['grounddmg']/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 updateListTr(ret,plane){
    if(plane==null){
        return;
    }
    var tr="<tr>";
    tr+="<td>"+plane.alias+"</td>";
    tr+="<td>"+plane.country+"</td>";
    tr+="<td>"+plane.type+"</td>";
    tr+="<td>"+plane.level+"</td>";
    tr+="<td title='组队场次:"+ret[4]+"'>"+ret[2]+"</td>";
    tr+="<td title='组队胜率:"+(ret[4]>0?Number(100.0*ret[5]/ret[4]).toFixed(1):"-")+"%' class='"+getWinRatingColor(100.0*ret[3]/ret[2])+"'>"+Number(100.0*ret[3]/ret[2]).toFixed(1)+"%</td>";
    tr+="<td class='eff int "+getEFFColor(ret[22]/ret[26])+"'>"+ret[22]/ret[26]+"</td>";
    tr+="<td class='eff int "+getEFFColor(ret[22]/ret[26])+"'>"+ret[23]/ret[26]+"</td>";
    tr+="<td class='eff int "+getEFFColor(ret[22]/ret[26])+"'>"+ret[24]/ret[26]+"</td>";
    tr+="<td class='eff int "+getEFFColor(ret[22]/ret[26])+"'>"+ret[25]/ret[26]+"</td>";
    tr+="<td class='"+(ret[2]>1?"double":"")+"'>"+ret[8]/ret[2]+"</td>";
    tr+="<td class='"+(ret[2]>1?"double":"")+"'>"+ret[10]/ret[2]+"</td>";
    tr+="<td class='int'>"+ret[9]/ret[2]+"</td>";
    tr+="<td class='"+(ret[2]>1?"double":"")+"'>"+(1*ret[11]+1*ret[12])/ret[2]+"</td>";
    tr+="<td class='"+(ret[2]>1?"double":"")+"'>"+ret[14]/ret[2]+"</td>";
    tr+="<td class='int'>"+ret[13]/ret[2]+"</td>";
    /*
    if(ret[16]>0) {
        tr += "<td class='percent'>" + ret[17] / ret[16] + "</td>";
    }else{
        tr += "<td>-</td>";
    }*/
    tr+="<td class='int'>"+ret[21]/ret[2]+"</td>";
    tr+="<td>"+ret[20]+"</td>";
    tr+="</tr>";
    $("#detailbody").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 %temp%\\wargaming.net\\wowp\\cache\\*');
	 ls.stdout.on('data', function (data) {
    console.log('clearDossier out: ' + data);
  });

  ls.stderr.on('data', function (data) {
    console.log('clearDossier err: ' + data);
  });

  ls.on('exit', function (code) {
    console.log('clearDossier exit: ' + code);
  });
}


function getModify(battles,level){
    var levelModify=0;
    var battleModify=0;
    //基于最大等级
    if(level==1){
        levelModify=0.1;
    }
    else if(level==2){
        levelModify=0.2;
    }
    else if(level==3){
        levelModify=0.3;
    }
    else if(level==4){
        levelModify=0.5;
    }
    else if(level==5){
        levelModify=0.8;
    }
    else if(level==6){
        levelModify=0.94;
    }
    else if(level==7){
        levelModify=0.98;
    }
    else levelModify=1;
    //基于场次
    if(battles>=1000)
        battleModify=1;
    else if(battles>=900)
        battleModify=0.98;
    else if(battles>=800)
        battleModify=0.96;
    else if(battles>=700)
        battleModify=0.94;
    else if(battles>=600)
        battleModify=0.92;
    else if(battles>=500)
        battleModify=0.9;
    else if(battles>=400)
        battleModify=0.8;
    else if(battles>=300)
        battleModify=0.7;
    else if(battles>=200)
        battleModify=0.6;
    else if(battles>=100)
        battleModify=0.4;
    else
        battleModify=0.2;

    if (levelModify<battleModify){
        return levelModify;
    }else{
        return battleModify;
    }
}