function getJsonChange(changes,ship){
    return {
        "cd":ship['cd'],
        "battles":changes['battles'],
        "wins":changes['wins'],
        "damage_dealt":changes['damage'],
        "frags":changes['kills'],
        "planes_killed":changes['killplanes'],
        "capture_points":changes['capture'],
        "dropped_capture_points":changes['defense'],
        "battle_time":Number(Number(changes['time']/1000).toFixed(0)),
        "xp":changes['exp'],
        "survived_battles":changes['survive']
    }
}
function getJsonShip(data,ship){
    return {
        "cd":ship['cd'],
        'battle_time': Number(Number(data['time']/1000).toFixed(0)),
        'battles': data['battles'],
        'wins': data['wins'],
        'draws': 0,
        'frags': data['kills'],
        'planes_killed': data['killplanes'],
        'damage_dealt': data['damage'],
        'capture_points': data['capture'],
        'dropped_capture_points': data['defense'],
        'xp': data['exp'],
        'survived_battles': data['survive'],
        'max_frags_battle': data['maxkills'],
        'max_planes_killed': data['maxkillplanes'],
        'max_xp': 0,
        'max_damage_dealt': data['maxdamage']
    }
}
function transform(json){
    if(checkERROR(json)){
        return;
    }
    var newJson=json;
    if('pvp' in json||'rank' in json||'pve' in json){
        newJson={changes:{
            pvp:[],pve:[],rank:[]
        },ships:{
            pvp:{},pve:{},rank:{}
        }};
        if('pvp' in json){
            if('changes' in json['pvp']) {
                for (var i in json['pvp']['changes']) {
                    var c = json['pvp']['changes'][i];
                    var ship = getShipById(c['id'])
                    newJson['changes']['pvp'].unshift(getJsonChange(c, ship));
                }
            }
            if('ships' in json['pvp']){
                for (var id in json['pvp']['ships']) {
                    var c = json['pvp']['ships'][id];
                    var ship = getShipById(id)
                    newJson['ships']['pvp'][ship['cd']]=getJsonShip(c, ship);
                }
            }
        }
        if('pve' in json){
            if('changes' in json['pve']) {
                for (var i in json['pve']['changes']) {
                    var c = json['pve']['changes'][i];
                    var ship = getShipById(c['id'])
                    newJson['changes']['pve'].unshift(getJsonChange(c, ship));
                }
            }
            if('ships' in json['pve']){
                for (var id in json['pve']['ships']) {
                    var c = json['pve']['ships'][id];
                    var ship = getShipById(id)
                    newJson['ships']['pve'][ship['cd']]=getJsonShip(c, ship);
                }
            }
        }
        if('rank' in json){
            if('changes' in json['rank']) {
                for (var i in json['rank']['changes']) {
                    var c = json['rank']['changes'][i];
                    var ship = getShipById(c['id'])
                    newJson['changes']['rank'].unshift(getJsonChange(c, ship));
                }
            }
            if('ships' in json['rank']){
                for (var id in json['rank']['ships']) {
                    var c = json['rank']['ships'][id];
                    var ship = getShipById(id)
                    newJson['ships']['rank'][ship['cd']]=getJsonShip(c, ship);
                }
            }
        }
    }
    return newJson;
}

//获取显示近期战斗
function showRecentBattles(update) {
    if(update){
        refreshDossier();
    }
    var error=false;
    if(checkERROR(config.get('account'))){
        customAlert('未指定帐号','warning');
        return;
    }
    var aid=config.get('account')['active'];
    if(aid>1500000000&&aid <2000000000){
        var br = new Config('profile/' + config.get('account')['active'] + '.db');
        var now=new Date();
        if(checkERROR(br.get("lastUpdate"))){
            br.json={
                lastUpdate:0,
                changes:{
                    pvp:[],pve:[],rank:[]
                },ships:{
                    pvp:{},pve:{},rank:{}
                }
            }
        }
        var last=new Date();
        last.setTime(br.get("lastUpdate"));
        if(update||now.getTime()-last.getTime()>24*3600*1000||(last.getHours()<14&&now.getHours()>=14)){
            syncDataFromChinaAPI(br,aid);
        }else{
            decodeDossier(br);
        }
    }else {
        syncDataFromOtherAPI();
    }
}

function refreshDossier(){
    $("#battlepage").load("dossier.html #container",function(data){
        if(!fs.existsSync('profile/'+config.get('account')['active']+'.db')){
            return;
        }
        var br=new Config('profile/'+config.get('account')['active']+'.db');
        br.json=transform(br.json);
        var battle20=[];
        var battle50=[];
        var battle100=[];
        var battle500=[];
        var day1=[];
        var day7=[];
        var day30=[];
        var damage=[];
        var winRate=[];
        var now=new Date().getTime()/1000;
        var total=mergeRecordList(br.get('ships')['pvp']);
        var baseBattles=total['battles'];
        var baseWins=total['wins'];
        if(!checkERROR(br.get('changes'))){
            pushChanges(br.get('changes')['pve'],'人机作战');
            pushChanges(br.get('changes')['pvp'],'随机战斗');
            pushChanges(br.get('changes')['rank'],'排名战');
        }
        for(var i=0;i<br.get('changes')['pvp'].length;i++){
            var battle= br.get('changes')['pvp'][i];
            if(checkERROR(battle)){
                continue;
            }
            if(battle20.length<20){
                battle20.push(battle);
            }
            if(battle50.length<50){
                battle50.push(battle);
            }
            if(battle100.length<100){
                battle100.push(battle);
            }
            if(battle500.length<500){
                battle500.push(battle);
            }
            if(now-battle['battle_time']<3600*24){
                day1.push(battle);
            }
            if(now-battle['battle_time']<3600*24*7){
                day7.push(battle);
            }
            if(now-battle['battle_time']<3600*24*30){
                day30.push(battle);
            }
            if(baseBattles>0) {
                winRate.unshift([battle['battle_time']*1000,1*Number(baseWins / baseBattles).toFixed(4)]);
            }
            damage.unshift([battle['battle_time']*1000,1*Number(battle['damage_dealt']/battle['battles']).toFixed(0)]);
            baseWins-=battle['wins'];
            baseBattles-=battle['battles'];
        }
        $("#totalbody").append(getMergeRow("总计",br.get('ships')['pvp']));
        $("#totalbody").append(getMergeRow("近1天",day1));
        $("#totalbody").append(getMergeRow("近7天",day7));
        $("#totalbody").append(getMergeRow("近30天",day30));
        $("#totalbody").append(getMergeRow("近20场",battle20));
        $("#totalbody").append(getMergeRow("近50场",battle50));
        $("#totalbody").append(getMergeRow("近100场",battle100));
        $("#totalbody").append(getMergeRow("近500场",battle500));

        if(total['battles']>0){
            damage.sort(sortTime);
            winRate.sort(sortTime);
            makeChart(damage,winRate);
        }
        refreshClass();
        if($("#dossierbody").children().length>0){
            $("table#dossiertable").tablesorter({
                sortInitialOrder : "desc",
                sortList : [ [ 0, 1 ],[ 2, 1 ] ]
            });
        }
    });
}

function pushChanges(changes,battletype){
    for(var i=0;i<changes.length;i++){
        var battle= changes[i];
        if(checkERROR(battle)){
            continue;
        }
        var div="<tr>";
        var type=battle['battles']>1?"double":"int";
        var d=new Date();
        var ship;
        if(typeof(battle['cd'])=='object'){
            var name='';
            for(var j in battle['cd']){
                if(j!=0){
                    name+=','
                }
                var s=shipDict[battle['cd'][j]];
                name+=s['alias'];
                if(j>=1){
                    name+='等';
                    break;
                }
            }
            ship={
                lvl:'--',
                alias:name
            }
        }else{
            ship=shipDict[battle['cd']];
        }
        if(checkERROR(ship)){
            console.log("ERROR cd:"+battle['cd']);
            continue;
        }
        d.setTime(Number(battle['battle_time'])*1000);
        div+="<td>"+date2str(d,"yyyy-MM-dd hh:mm:ss")+"</td>";
        div+="<td>"+battletype+"</td>";
        div+="<td>"+ship['lvl']+"</td>";
        div+="<td>"+ship['alias']+"</td>";
        var resultclass="";
        var result="";
        if(battle['battles']==1){
            if(battle['wins']==1){
                result="胜";
                resultclass="result1";
            }else if(battle['draws']==1){
                result="平";
                resultclass="result0";
            }else{
                result="负";
                resultclass="result-1";
            }
        }else{
            result=battle['battles']+"战/"+battle['wins']+"胜 ("+Number(battle['wins']*100/battle['battles']).toFixed(1)+"%)";
        }
        div+="<td class='"+resultclass+"'>"+result+"</td>";//战果
        div+="<td class='"+type+"'>"+battle['frags']/battle['battles']+"</td>";
        div+="<td class='int'>"+battle['damage_dealt']/battle['battles']+"</td>";
        div+="<td class='"+type+"'>"+battle['planes_killed']/battle['battles']+"</td>";
        div+="<td class='"+type+"'>"+battle['capture_points']/battle['battles']+"</td>";
        div+="<td class='"+type+"'>"+battle['dropped_capture_points']/battle['battles']+"</td>";
        div+="<td class='int'>"+battle['xp']/battle['battles']+"</td>";
        div+="</tr>";
        $("#dossierbody").append(div);
    }
}

function sortTime(a,b)
{
    return a[0] - b[0];
}
function sortBattle(a,b){
    return b['battle_time']-a['battle_time'];
}

function getDiff(dat1,dat2,time,id){
    if(dat1==null){
        dat1={
            'battles':0,
            'wins':0,
            'frags':0,
            'planes_killed':0,
            'damage_dealt':0,
            'capture_points':0,
            'dropped_capture_points':0,
            'xp':0,
            'survived_battles':0
        }
    }
    var res= {
        'battle_time':time,
        'battles':dat2['battles']-dat1['battles'],
        'wins':dat2['wins']-dat1['wins'],
        'frags':dat2['frags']-dat1['frags'],
        'planes_killed':dat2['planes_killed']-dat1['planes_killed'],
        'damage_dealt':dat2['damage_dealt']-dat1['damage_dealt'],
        'capture_points':dat2['capture_points']-dat1['capture_points'],
        'dropped_capture_points':dat2['dropped_capture_points']-dat1['dropped_capture_points'],
        'xp':dat2['xp']-dat1['xp'],
        'survived_battles':dat2['survived_battles']-dat1['survived_battles'],
        'cd':id
    };
    return res;
}


function makeChart(damage,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 in this.series[1].groupedData) {
                                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: damage
            }]
    });
}

function getMergeRow(name,datalist){
    var total=mergeRecordList(datalist);

    var div="<tr>";
    div+="<td>"+name+"</td>";
    div+="<td>"+total['battles']+"</td>";
    if(total['battles']>0){
        var rat=total['wins']/total['battles'];
        div+="<td class='percent "+getRatClass(rat*100)+"'>"+rat+"</td>";
        div+="<td class='double'>"+total['frags']/total['battles']+"</td>";
        div+="<td class='int'>"+total['damage_dealt']/total['battles']+"</td>";
        div+="<td class='double'>"+total['planes_killed']/total['battles']+"</td>";
        div+="<td class='double'>"+total['capture_points']/total['battles']+"</td>";
        div+="<td class='double'>"+total['dropped_capture_points']/total['battles']+"</td>";
        div+="<td class='int'>"+total['xp']/total['battles']+"</td>";
    }else{
        div+="<td>--</td>";
        div+="<td>--</td>";
        div+="<td>--</td>";
        div+="<td>--</td>";
        div+="<td>--</td>";
        div+="<td>--</td>";
        div+="<td>--</td>";
    }
    div+="</tr>";
    return div;
}
function mergeRecordList(datalist){
    var total={
        'battle_time':0,
        'battles':0,
        'wins':0,
        'draws':0,
        'frags':0,
        'planes_killed':0,
        'damage_dealt':0,
        'capture_points':0,
        'dropped_capture_points':0,
        'xp':0,
        'survived_battles':0,
        'max_frags_battle':0,
        'max_planes_killed':0,
        'max_xp':0,
        'max_damage_dealt':0
    };
    for (var i in datalist){
        var data=datalist[i];
        if(checkERROR(data['battles'])||checkERROR(data['damage_dealt'])){
            continue;
        }
        total['battles']+=Number(data['battles']);
        total['wins']+=Number(data['wins']);
        total['frags']+=Number(data['frags']);
        total['planes_killed']+=Number(data['planes_killed']);
        total['damage_dealt']+=Number(data['damage_dealt']);
        total['capture_points']+=Number(data['capture_points']);
        total['dropped_capture_points']+=Number(data['dropped_capture_points']);
        total['xp']+=Number(data['xp']);
        total['survived_battles']+=Number(data['survived_battles']);
        if(Number(data['battle_time'])>total['battle_time']){
            total['battle_time']=Number(data['battle_time']);
        }
        if ('max_frags_battle' in data){
            if(Number(data['max_frags_battle'])>total['max_frags_battle']){
                total['max_frags_battle']=Number(data['max_frags_battle']);
            }
            if(Number(data['max_planes_killed'])>total['max_planes_killed']){
                total['max_planes_killed']=Number(data['max_planes_killed']);
            }
            if(Number(data['max_damage_dealt'])>total['max_damage_dealt']){
                total['max_damage_dealt']=Number(data['max_damage_dealt']);
            }
        }
    }
    return total;
}

function refreshShipList(){
    $("#shipspage").load("dossier.html #shipslist",function(data){
        var aid=config.get('account')['active'];
        if(!fs.existsSync('profile/'+aid+'.db')){
            customAlert("未找到数据","danger");
        }
        var china=false;
        if(aid>1500000000&&aid<2000000000){
            china=true;
            $('.other').hide();
            $('.china').show();
        }else{
            $('.other').show();
            $('.china').hide();
        }
        var br=new Config('profile/'+aid+'.db');
        var total=mergeRecordList(br.get('ships')['pvp']);
        var totalShip={
            lvl:'--',
            type:'--',
            country:'--',
            alias:'总计'
        }
        for(var i in br.get('ships')['pvp']){
            var shipData= br.get('ships')['pvp'][i];
            var ship=shipDict[i];
            $("#shipsbody").append(getShipTr(ship,shipData,china));
        }
        $("#shipsbody").append(getShipTr(totalShip,total,china));
        refreshClass();
        if($("#shipsbody").children().length>0){
            $("table#shipstable").tablesorter({
                sortInitialOrder : "desc",
                sortList : [ [ 4, 1 ] ]
            });
        }
        $("#shipspage").show();
    });
}

function getShipTr(ship,shipData,china){
    var div="<tr>";
    var type=shipData['battles']>1?"double":"int";
    div+="<td>"+ship['lvl']+"</td>";
    div+="<td>"+getNationName(ship['country'])+"</td>";
    div+="<td>"+getTypeName(ship['type'])+"</td>";
    div+="<td>"+ship['alias']+"</td>";
    div+="<td>"+shipData['battles']+"</td>";
    div+="<td>"+shipData['wins']+"</td>";

    div+="<td class='percent "+getRatClass(100*shipData['wins']/shipData['battles'])+"'>"+shipData['wins']/shipData['battles']+"</td>";
    if(china){
        if(!checkERROR(shipData['totalPower'])){
            var movingpercent=0.2+(shipData['battles']>300?0.6:(1.0*shipData['battles']/300*0.6));
            var totalpower=Number(shipData['totalPower']/shipData['battles']).toFixed(0);
            var winpower=Number(shipData['totalWinPower']/shipData['battles']).toFixed(0);
            var movingpower=Number(shipData['movingPower']).toFixed(0);
            var p=(totalpower/1+winpower/1)*(1-movingpercent)+movingpercent*movingpower;
            div+="<td class='int' title='场均战力:"+totalpower+",胜利战力:"+winpower+",校准战力:"+movingpower+",校准系数:"+Number(movingpercent).toFixed(2)+"'>"+p+"</td>";
            div+="<td class='double2 percent'>"+p/ship['weight']+"</td>"
        }else{
            div+="<td>0</td>";
            div+="<td>0%</td>";
        }
    }
    div+="<td>"+shipData['survived_battles']+"</td>";
    div+="<td class='percent'>"+shipData['survived_battles']/shipData['battles']+"</td>";
    div+="<td class='"+type+"'>"+shipData['frags']/shipData['battles']+"</td>";
    div+="<td class='int'>"+shipData['damage_dealt']/shipData['battles']+"</td>";
    div+="<td class='"+type+"'>"+shipData['planes_killed']/shipData['battles']+"</td>";
    div+="<td class='"+type+"'>"+shipData['capture_points']/shipData['battles']+"</td>";
    div+="<td class='"+type+"'>"+shipData['dropped_capture_points']/shipData['battles']+"</td>";
    div+="<td class='int'>"+shipData['xp']/shipData['battles']+"</td>";
    if(china){
        div+="<td class='int'>"+shipData['credit']/shipData['battles']+"</td>";
        if(!checkERROR(shipData['teambattles'])&&shipData['teambattles']>0){
            div+="<td>"+shipData['teambattles']+"</td>";
            div+="<td class='percent "+getRatClass(100*shipData['teamwins']/shipData['teambattles'])+"'>"+shipData['teamwins']/shipData['teambattles']+"</td>";
        }else{
            div+="<td>0</td>";
            div+="<td>--%</td>";
        }
    }
    if(!china) {
        div += "<td>" + shipData['max_frags_battle'] + "</td>";
        div += "<td>" + shipData['max_damage_dealt'] + "</td>";
        div += "<td>" + shipData['max_planes_killed'] + "</td>";
    }
    var d=new Date();
    d.setTime(Number(shipData['battle_time'])*1000);
    div+="<td>"+date2str(d,"yyyy-MM-dd hh:mm")+"</td>";
    div+="</tr>";
    return div;
}

function getTotalBattles(list,val){
    var b=0;
    for(var i in list){
        b+=list[i][val];
    }
    return b;
}
function syncDataFromChinaAPI(br,aid){
    //添加战斗数据
    //根据战斗数据的时间决定是否添加日数据
    //同步船数据
    //检查是否需要整合总数据到临时总数据
    var d=new Date();
    d.setTime(br.get("lastUpdate"));
    var now=new Date();
    var date= d.getFullYear()+"-"+fillZero(d.getMonth()+1)+"-"+ fillZero(d.getDate());
    $.get("http://rank.kongzhong.com/Data/action/WowsAction/getBattleList?aid="+aid+"&date="+date,function(data) {
        var updated=false;
        var battleJson=JSON.parse(data);
        var changes=br.get('changes');
        var first=false;
        if(changes['pvp'].length==0) {
            first=true;
        }
        for(var i in battleJson){
            var battle=battleJson[i];
            var exist=false;
            //检查是否存在
            for(var j in changes['pvp']){
                var ch=changes['pvp'][j];
                if(checkERROR(ch)||'arena_id' in ch&&ch['arena_id']==battle['bi']['arena_id']){
                    exist=true;
                    break;
                }
            }
            if(exist){
                continue;
            }
            var rec={type:'battle'};
            for(var j in battle['bi']){
                rec[j]=battle['bi'][j];
            }
            for(var j in battle['bd']){
                rec[j]=battle['bd'][j];
            }
            rec['cd']=rec['id']['vehicleTypeCd'];
            rec['battles']=1;
            rec['wins']=(rec['team']==rec['win_team_id']?1:0)
            rec['battle_time']=Number(Number(rec['start_dt']['time']/1000).toFixed(0));
            changes['pvp'].unshift(rec);
            updated=true;
        }
        if(updated||now.getTime() - d.getTime()>7*24*3600*1000){
            var delArray=[];
            for(var j in changes['pvp']){
                if(changes['pvp'][j]['type']=='temp'||checkERROR(changes['pvp'][j])){
                    delArray.unshift(j);
                }
            }
            for(var i in delArray){
                changes['pvp'].splice(i,1);
            }
        }
        br.set('changes',changes);
        if(!first&&now.getTime()- d.getTime()>7*24*3600*1000){
            //超过单场战斗保留天数，尝试日更新
            $.get("http://rank.kongzhong.com/Data/action/WowsAction/getDayInfo?aid="+aid,function(data) {
                var dayJson=JSON.parse(data);
                for(var i in dayJson){
                    var changes=br.get('changes');
                    var day=dayJson[i];
                    var insertTime=day['insert_date']['time']/1000;
                    var exist=false;
                    for(var j in changes['pvp']){
                        var ch=changes['pvp'][j];
                        if(ch['type']=='battle'&&ch['cd']==day['id']['vehicleTypeCd']&&ch.battle_time-insertTime>8*3600 &&ch.battle_time-insertTime<32*3600){
                            exist=true;
                            break;
                        }
                        if(ch['type']=='day'&&ch['cd']==day['id']['vehicleTypeCd']&&Math.abs(ch['battle_time']-insertTime)<1){
                            exist=true;
                            break;
                        }
                    }
                    if(!exist){
                        var rec=day;
                        rec['type']='day';
                        rec['battle_time']=Number(Number(rec['insert_date']['time']/1000).toFixed(0));
                        rec['frags']=rec['ship_killed'];
                        rec['damage_dealt']=rec['damage'];
                        rec['cd']=rec['id']['vehicleTypeCd'];
                        changes['pvp'].unshift(rec);
                        changes['pvp'].sort(sortBattle);
                        br.set('changes',changes);
                    }
                }
            });
        }
        if(updated||now.getTime()- d.getTime()>7*24*3600*1000){
            $.get("http://rank.kongzhong.com/Data/action/WowsAction/getShipInfo?aid="+aid,function(data) {
                var shipJson=JSON.parse(data);
                var record=br.get('ships');
                for(var i in shipJson){
                    var ship=shipJson[i];

                    ship['xp']=ship['exp'];
                    ship['survived_battles']=ship['alive'];
                    ship['frags']=ship['ship_killed'];
                    ship['planes_killed']=ship['plane_killed'];
                    ship['battle_time']=ship['update_date']['time']/1000;
                    ship['damage_dealt']=ship['damage'];
                    var cd=ship['id']['vehicleTypeCd'];
                    if(!(cd in record['pvp'])){
                        record['pvp'][cd]={
                            tempBattle:0,
                            tempWin:0
                        }
                    }
                    var tempBattle=record['pvp'][cd]['tempBattle'];
                    var tempWin=record['pvp'][cd]['tempWin'];
                    record['pvp'][cd]=ship;
                    if(tempBattle<ship['battles']){
                        tempBattle= ship['battles'];
                    }
                    if(tempWin<ship['wins']){
                        tempWin=ship['wins'];
                    }
                    record['pvp'][cd]['tempBattle']=tempBattle;
                    record['pvp'][cd]['tempWin']=tempWin;
                }
                var total=mergeRecordList(record['pvp']);
                br.set('tempTotal',total);
                br.set('ships',record);
                decodeDossier(br);
            });
        }else{
            decodeDossier(br);
        }
    });
    br.set("lastUpdate",new Date().getTime())
}

function decodeDossier(br){
    var es = cp.spawn("apps\\dossier\\analyse.exe", ['dossier',config.get('path')+'/profile/python.log', config.get('account')['active']]);
    var bufs = [];
    var error=false;
    es.stdout.on('data', function (data) {
        bufs.push(data);
    });
    es.stderr.on('data', function (data) {
        customAlert("错误:" + repairCharset(data), 'danger');
        error = true;
    });
    es.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.trim().length == 0) {
            return;
        }
        if (error || output.indexOf('error') != -1) {
            customAlert('更新数据失败', 'warning');
            console.log(output);
            return;
        }
        try {
            var json = JSON.parse(output.replace(/\'/g, "\"").replace(/L:/g, ":"));
            if(json.length>0){
                var tempTotal=br.get('tempTotal');
                if(checkERROR(tempTotal['battles'])){
                    return;
                }
                var updated=false;
                var ships=br.get('ships');
                var changes=br.get('changes');
                for(var i in json){
                    var newTotal=json[i];
                    if(newTotal['pvp'].length==0){
                        continue;
                    }
                    if(newTotal['battles']<=tempTotal['battles']){
                        continue;
                    }
                    if(newTotal['battles']-tempTotal['battles']>100){
                        continue;
                    }
                    var shipList=[];
                    for(var cd in newTotal['pvp']){
                        if(cd in shipDict) {
                            if (cd in ships['pvp']) {
                                if (ships['pvp'][cd]['tempBattle'] < newTotal['pvp'][cd]['battles']) {
                                    shipList.push(cd);
                                    ships['pvp'][cd]['tempBattle'] = newTotal['pvp'][cd]['battles'];
                                }
                            } else {
                                shipList.push(cd);
                            }
                        }
                    }
                    if (shipList.length==1){
                        shipList=Number(shipList[0]);
                    }else if(shipList.length==0){
                        continue;
                    }
                    var rec=getDiff(tempTotal,newTotal,newTotal['battle_time'],shipList);
                    if(typeof(shipList)!='object'){
                        if(!(shipList in ships['pvp'])) {
                            var cd = shipList
                            ships['pvp'][cd] = rec;
                            ships['pvp'][cd]['tempBattle'] = newTotal['pvp'][cd]['battles'];
                        }
                    }else{
                        for(var j in shipList){
                            var cd=shipList[j];
                            if(!(cd in ships['pvp'])) {
                                ships['pvp'][cd] = {tempBattle: newTotal['pvp'][cd]['battles']}
                            }
                        }
                    }
                    for(var j in newTotal){
                        if(j=='pvp'){
                            continue;
                        }
                        tempTotal[j]=newTotal[j];
                    }
                    rec['type']='temp';
                    changes['pvp'].unshift(rec);
                    updated=true;
                }
                if(updated){
                    br.set('tempTotal',tempTotal);
                    br.set('ships',ships);
                    br.set('changes',changes);
                    refreshDossier();
                }
            }
        }
        catch (e) {
            console.log(e);
        }
    });
}

function syncDataFromOtherAPI(){
    var b = 0;
    if (fs.existsSync('profile/' + config.get('account')['active'] + '.db')) {
        var br = new Config('profile/' + config.get('account')['active'] + '.db');
        if (!checkERROR(br.get('ships'))) {
            var total = mergeRecordList(br.get('ships')['pvp']);
            b = total['battles'];
        }
    }
    var es = cp.spawn("apps\\dossier\\analyse.exe", ['update', config.get('account')['active'], b]);
    var bufs = [];
    var error;
    es.stdout.on('data', function (data) {
        bufs.push(data);
    });
    es.stderr.on('data', function (data) {
        customAlert("错误:" + repairCharset(data), 'danger');
        error = true;
    });
    es.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.trim().length == 0) {
            return;
        }
        if (error || output.indexOf('error') != -1) {
            customAlert('更新数据失败', 'warning');
            console.log(output);
            return;
        }
        try {
            var json = JSON.parse(output.replace(/\'/g, "\""));
            var aid = config.get('account')['active'];
            var br = new Config("profile/" + aid + ".db");
            br.json = transform(br.json);
            //var pve=updateByType(br.get('ships')['pve'],'pve',json);
            updateByType(br, 'pvp', json);
            //var rank=updateByType(br.get('ships')['rank'],'rank',json);
            refreshDossier();
        }
        catch (e) {
            console.log(e);
        }
    });
}
function updateByType(br,type,json){
    if(checkERROR(br)){
        br={changes:{
            pvp:[],pve:[],rank:[]
        },ships:{
            pvp:{},pve:{},rank:{}
        }};
    }
    var record=br.get('ships');
    if(checkERROR(record)){
        record={
            pvp:{},pve:{},rank:{}
        };
    }
    var battle=br.get('changes');
    if(checkERROR(battle)){
        battle={
            pvp:[],pve:[],rank:[]
        };
    }
    var shipData=json['data'][config.get('account')['active']];
    for (var i in shipData){
        var s=shipData[i];

        if(s['ship_id'] in record[type]){
            if(Number(record[type][s['ship_id']]['battles'])<Number(s[type]['battles'])){
                battle[type].unshift(getDiff(record[type][s['ship_id']],s[type],s['last_battle_time'],s['ship_id']));
                record[type][s['ship_id']]=s[type];
                record[type][s['ship_id']]['battle_time']=s['last_battle_time'];
            }
        }else{
            if(battle[type].length>0) {
                battle[type].unshift(getDiff(null,s[type],s['last_battle_time'],s['ship_id']));
            }
            record[type][s['ship_id']]=s[type];
            record[type][s['ship_id']]['battle_time']=s['last_battle_time'];
        }
    }
    br.set('changes',battle);
    br.set('ships',record);
}

function getLvl(lvl){
    switch(lvl){
        case 'I':
            return 1;
        case 'II':
            return 2;
        case 'III':
            return 3;
        case 'IV':
            return 4;
        case 'V':
            return 5;
        case 'VI':
            return 6;
        case 'VII':
            return 7;
        case 'VIII':
            return 8;
        case 'IX':
            return 9;
        case 'X':
            return 10;
        default:
            return lvl;
    }
}

function getRatClass(wr) {
    if (wr >= 60)
        return 'ss';
    if (wr >= 56)
        return 's';
    if (wr >= 54)
        return 'a';
    if (wr >= 51)
        return 'b';
    if (wr >= 48)
        return 'c';
    if (wr >= 46)
        return 'd';
    return 'e';
}

function getNationName(nation){
    switch(nation.toLowerCase()){
        case 'japan':
            return '日本';
        case 'usa':
            return '美国';
        case 'germany':
            return '德国';
        case 'ussr':
            return '苏联';
        case 'united_kingdom':
            return '英国';
        default :
            return nation;
    }
}

function getTypeName(type){
    switch (type.toLowerCase()){
        case 'battleship':
            return '战列舰';
        case 'aircarrier':
            return '航空母舰';
        case 'cruiser':
            return '巡洋舰';
        case 'destroyer':
            return '驱逐舰';
        default :
            return type;
    }
}