var ChinaDossier=function(){
    this.updateNow=false;
}
ChinaDossier.prototype= {
    transform: function (json) {
        if (checkERROR(json)) {
            return;
        }
        json['lastUpdate']=0;
        for(var i in json['changes']['pvp']){
            var ch=json['changes']['pvp'][i];
            ch['killship']=ch['frags'];
            ch['killplane']=ch['planes_killed'];
            ch['damage']=ch['damage_dealt'];
            ch['capture']=ch['capture_points'];
            ch['defense']=ch['dropped_capture_points'];
            ch['exp']=ch['xp'];
        }
        for(var i in json['changes']['rank']){
            var ch=json['changes']['rank'][i];
            ch['killship']=ch['frags'];
            ch['killplane']=ch['planes_killed'];
            ch['damage']=ch['damage_dealt'];
            ch['capture']=ch['capture_points'];
            ch['defense']=ch['dropped_capture_points'];
            ch['exp']=ch['xp'];
        }
        return json;
    },
    showRecentBattles: function (update) {
        if(this.updateNow){
            return;
        }
        this.updateNow=true;
        if (update) {
            dossier.refreshDossier();
        }
        var error = false;
        if (checkERROR(config.get('account'))) {
            customAlert('未指定帐号', 'warning');
            return;
        }
        var aid = config.get('account')['active'];
        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)) {
            dossier.syncData(br, aid);
        } else {
            dossier.decodeDossier(br);
        }
        this.updateNow=false;
    },
    refreshDossier: function () {
        $("#battlepage").load("dossierChina.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 tempRate= [];
            var now = new Date().getTime() / 1000;
            var total = dossier.mergeRecordList(br.get('ships')['pvp']);
            var baseBattles = total['battles'];
            var baseWins = total['wins'];
            var testbattles=0;
            if (!checkERROR(br.get('changes'))) {
                dossier.pushChanges(br.get('changes')['pve'], 2);
                dossier.pushChanges(br.get('changes')['pvp'], 0);
                dossier.pushChanges(br.get('changes')['rank'], 4);
            }
            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-testbattles > 50) {
                    testbattles+=battle['battles'];
                    tempRate.push([battle['battle_time'] * 1000, battle['wins'],battle['battles'],battle['damage']]);
                    damage.unshift([battle['battle_time'] * 1000, 1 * Number(battle['damage'] / battle['battles']).toFixed(0)]);
                }
            }
            $("#totalbody").append(dossier.getMergeRow("总计", br.get('ships')['pvp']));
            $("#totalbody").append(dossier.getMergeRow("近1天", day1));
            $("#totalbody").append(dossier.getMergeRow("近7天", day7));
            $("#totalbody").append(dossier.getMergeRow("近30天", day30));
            $("#totalbody").append(dossier.getMergeRow("近20场", battle20));
            $("#totalbody").append(dossier.getMergeRow("近50场", battle50));
            $("#totalbody").append(dossier.getMergeRow("近100场", battle100));
            $("#totalbody").append(dossier.getMergeRow("近500场", battle500));

            if (total['battles'] > 0) {
                damage.sort(sortTime);
                tempRate.sort(sortTime);
                for(var i=tempRate.length-1;i>=0;i--){
                    var b=tempRate[i];
                    winRate.unshift([b[0],1 * Number(baseWins / baseBattles).toFixed(4)]);
                    baseWins -= b[1];
                    baseBattles -= b[2];
                }
                makeChart(damage, winRate);
            }
            refreshClass();
            if ($("#dossierbody").children().length > 0) {
                $("table#dossiertable").tablesorter({
                    sortInitialOrder: "desc",
                    sortList: [
                        [ 0, 1 ],
                        [ 2, 1 ]
                    ]
                });
            }
        });
    },
    pushChanges: function (changes, battletype) {
        for (var i = 0; i < changes.length; i++) {
            if(i>200){
                break;
            }
            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);
            if(battle['type']=='day'){
                div += "<td>" + date2str(d, "yyyy-MM-dd") + "</td>";
            }else{
                div += "<td>" + date2str(d, "yyyy-MM-dd hh:mm:ss") + "</td>";
            }
            div += "<td class='battleType" + battletype + "'>" + (battletype == 0 ? "随机战斗" : (battletype == 2 ? "人机对战" : (battletype == 4 ? "排位战" : 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>";//战果
            if (battle['type']=='battle'&&'power' in battle) {
                var desc="伤害效率:"+Number(battle['dmgpower']*100/ship['weight']).toFixed(0)+"%,防空效率:"+Number(battle['planepower']*100/ship['weight']).toFixed(0)+"%,占领效率:"+Number(battle['capturepower']*100/ship['weight']).toFixed(0)+"%,护旗效率:"+Number(battle['defensepower']*100/ship['weight']).toFixed(0)+"%";
                div += "<td class='china' title='原效率:"+Number((battle['power']-battle['partnerpower'])*100/ship['weight']).toFixed(0)+"%,组队效率:"+Number(battle['partnerpower']*100/ship['weight']).toFixed(0)+"%,胜效加成:"+Number(100*battle['winpower'] / ship['weight']).toFixed(0)+"%\n"+desc+"'>" + Number((battle['power']) * 100 * (1+battle['winpower'] / ship['weight'])/ ship['weight']).toFixed(0) + "%</td>";
            } else if (battle['type']=='day'&&'totalPower' in battle) {
                div += "<td class='china' title='原效率:"+Number((battle['totalPower']-battle['teamPower'])*100/battle['battles']/ship['weight']).toFixed(0)+"%,组队效率:"+Number(battle['teamPower']*100/battle['battles']/ship['weight']).toFixed(0)+"%,胜效加成:"+Number(100*battle['winPower'] /battle['battles']/ ship['weight']).toFixed(0)+"%'>" + Number(battle['totalPower']/battle['battles'] * 100 * (1+battle['winPower'] / battle['battles'] / ship['weight'])/ ship['weight']).toFixed(0) + "%</td>";
            } else{
                div += "<td class='china'>--%</td>";
            }
            div += "<td class='" + type + "'>" + battle['killship'] / battle['battles'] + "</td>";
            div += "<td class='int'>" + battle['damage'] / battle['battles'] + "</td>";
            div += "<td class='" + type + "'>" + battle['killplane'] / battle['battles'] + "</td>";
            div += "<td class='" + type + "'>" + (battle['capture']+checkERROR(battle['capturep'])?0:battle['capturep']) / battle['battles'] + "</td>";
            div += "<td class='" + type + "'>" + (battle['defense']+checkERROR(battle['defensep'])?0:battle['defensep']) / battle['battles'] + "</td>";
            div += "<td class='int'>" + battle['exp'] / battle['battles'] + "</td>";
            div += "</tr>";
            $("#dossierbody").append(div);
        }
    },
    getDiff: function (dat1, dat2, time, id) {
        if (dat1 == null) {
            dat1 = {
                'battles': 0,
                'wins': 0,
                'killship': 0,
                'killplane': 0,
                'damage': 0,
                'capture': 0,
                'defense': 0,
                'capturep': 0,
                'defensep': 0,
                'exp': 0,
                'alive': 0
            }
        }
        var res = {
            'battle_time': time,
            'battles': dat2['battles'] - dat1['battles'],
            'wins': dat2['wins'] - dat1['wins'],
            'killship': dat2['killship'] - dat1['killship'],
            'killplane': dat2['killplane'] - dat1['killplane'],
            'damage': dat2['damage'] - dat1['damage'],
            'capture': dat2['capture'] - dat1['capture'],
            'defense': dat2['defense'] - dat1['defense'],
            'exp': dat2['exp'] - dat1['exp'],
            'alive': dat2['alive'] - dat1['alive'],
            'cd': id
        };
        return res;
    },
    getMergeRow: function (name, datalist) {
        var total = dossier.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>" + total['teambattles'] + "</td>";
            div += "<td class='percent " + getRatClass(rat * 100) + "'>" + rat + "</td>";
            div += "<td class='double'>" + total['killship'] / total['battles'] + "</td>";
            div += "<td class='int'>" + total['damage'] / total['battles'] + "</td>";
            div += "<td class='double'>" + total['killplane'] / total['battles'] + "</td>";
            div += "<td class='int'>" + total['exp'] / total['battles'] + "</td>";
        } else {
            div += "<td>--</td>";
            div += "<td>--</td>";
            div += "<td>--</td>";
            div += "<td>--</td>";
            div += "<td>--</td>";
            div += "<td>--</td>";
        }
        div += "</tr>";
        return div;
    },
    mergeRecordList: function (datalist,total) {
        if(checkERROR(total)) {
            total = {
                'battle_time': 0,
                'battles': 0,
                'wins': 0,
                'draws': 0,
                'killship': 0,
                'killplane': 0,
                'damage': 0,
                'capture': 0,
                'defense': 0,
                'exp': 0,
                'alive': 0,
                'teambattles':0,
                'teamwins':0,
                'maxkillship': 0,
                'maxkillplane': 0,
                'maxexp': 0,
                'maxdamage': 0,
                'totalpower':0,
                'totalweight':0
            }
        };
        for (var i in datalist) {
            var data = datalist[i];
            if (!checkERROR(data['battles']) && !checkERROR(data['damage'])) {
                total['battles'] += Number(data['battles']);
                total['wins'] += Number(data['wins']);
                total['killship'] += Number(data['killship']);
                total['killplane'] += Number(data['killplane']);
                total['damage'] += Number(data['damage']);
                total['capture'] += Number(data['capture']);
                total['defense'] += Number(data['defense']);
                total['exp'] += Number(data['exp']);
                total['alive'] += Number(data['alive']);
                if ('teamwork' in data) {
                    total['teambattles'] += data['teamwork'];
                    total['teamwins']+=data['teamwins'];
                } else if ('teambattles' in data) {
                    total['teambattles'] += data['teambattles'];
                    total['teamwins']+=data['teamwins'];
                }
                if (Number(data['battle_time']) > total['battle_time']) {
                    total['battle_time'] = Number(data['battle_time']);
                }
                if ('maxkillship' in data) {
                    if (Number(data['maxkillship']) > total['maxkillship']) {
                        total['maxkillship'] = Number(data['maxkillship']);
                    }
                    if (Number(data['maxkillplane']) > total['maxkillplane']) {
                        total['maxkillplane'] = Number(data['maxkillplane']);
                    }
                    if (Number(data['maxdamage']) > total['maxdamage']) {
                        total['maxdamage'] = Number(data['maxdamage']);
                    }
                    if (Number(data['maxexp']) > total['maxexp']) {
                        total['maxexp'] = Number(data['maxexp']);
                    }
                }
            }
        }
        return total;
    },
    refreshShipList: function () {
        $("#shipspage").load("dossierChina.html #shipslist", function (data) {
            var aid = config.get('account')['active'];
            if (!fs.existsSync('profile/' + aid + '.db')) {
                customAlert("未找到数据", "danger");
            }
            var br = new Config('profile/' + aid + '.db');
            var total = dossier.mergeRecordList(br.get('ships')['pvp']);
            //total = dossier.mergeRecordList(br.get('ships')['pve'],total);
            //total = dossier.mergeRecordList(br.get('ships')['rank'],total);
            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(dossier.getShipTr(ship, shipData,0));
            }
            for (var i in br.get('ships')['pve']) {
                var shipData = br.get('ships')['pve'][i];
                var ship = shipDict[i];
                $("#shipsbody").append(dossier.getShipTr(ship, shipData,2));
            }
            for (var i in br.get('ships')['rank']) {
                var shipData = br.get('ships')['rank'][i];
                var ship = shipDict[i];
                $("#shipsbody").append(dossier.getShipTr(ship, shipData,4));
            }
            $("#shipsbody").append(dossier.getShipTr(totalShip, total,0));
            refreshClass();
            if ($("#shipsbody").children().length > 0) {
                $("table#shipstable").tablesorter({
                    sortInitialOrder: "desc",
                    sortList: [
                        [ 5, 1 ]
                    ]
                });
            }
            $("#shipspage").show();
        });
    },

    getShipTr: function (ship, shipData,battletype) {
        var div = "<tr>";
        var type = shipData['battles'] > 1 ? "double" : "int";
        div += "<td class='battleType" + battletype + "'>" + (battletype == 0 ? "随机战斗" : (battletype == 2 ? "人机对战" : (battletype == 4 ? "排位战" : battletype))) + "</td>";
        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 class='percent " + getRatClass(100 * shipData['wins'] / shipData['battles']) + "'>" + shipData['wins'] / shipData['battles'] + "</td>";
        if (!checkERROR(shipData['totalPower'])) {
            var totalpower = shipData['totalPower'] / shipData['battles'];
            var movingpower = shipData['movingPower']
            var winpower = shipData['winPower'] / shipData['battles']/ship['weight'];
            var p = Number(totalpower+movingpower)/2*(1+winpower).toFixed(0)
            div += "<td class='int' title='场均战力:" + totalpower.toFixed(0)  + ",校准战力:" + movingpower.toFixed(0) + ",胜效加成:" + (winpower*100).toFixed(0)+ "%'>" + p + "</td>";
            div += "<td class='double2 percent'>" + p / ship['weight'] + "</td>"
        } else {
            div += "<td>0</td>";
            div += "<td>0%</td>";
        }
        div += "<td class='percent'>" + shipData['alive'] / shipData['battles'] + "</td>";
        div += "<td class='" + type + "'>" + shipData['killship'] / shipData['battles'] + "</td>";
        div += "<td class='int'>" + shipData['damage'] / shipData['battles'] + "</td>";
        div += "<td class='" + type + "'>" + shipData['killplane'] / shipData['battles'] + "</td>";
        div += "<td class='int'>" + shipData['exp'] / 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>";
        }
        div += "<td>" + shipData['maxdamage'] + "</td>";
        div += "<td>" + shipData['maxkillship'] + "</td>";
        div += "<td>" + shipData['maxkillplane'] + "</td>";
        div += "<td>" + shipData['maxexp'] + "</td>";
        var d = new Date();
        d.setTime(Number(shipData['battle_time']) * 1000);
        div += "<td>" + date2str(d, "yyyy-MM-dd") + "</td>";
        div += "</tr>";
        return div;
    },

    syncData: function (br, aid) {
        //添加战斗数据
        //根据战斗数据的时间决定是否添加日数据
        //同步船数据
        //检查是否需要整合总数据到临时总数据
        if (checkERROR(br.get("v16"))) {
            br.json = dossier.transform(br.json);
            br.set("v16", true);
        }
        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 ships = br.get('ships');
            for (var i in battleJson) {
                var battle = battleJson[i];
                var type = getBattleType(battle['bi']['battle_type_id']);
                var exist = false;
                //检查是否存在
                for (var j in changes[type]) {
                    var ch = changes[type][j];
                    if (checkERROR(ch)) {
                        continue;
                    }
                    if (ch['type'] != 'battle') {
                        continue;
                    }
                    if ('arena_id' in ch && ch['arena_id'] == battle['bi']['arena_id']) {
                        exist = true;
                        //修正新接口
                        if(!('damagebb' in ch)){
                            for(var i in battle['bi']){
                                ch[i]=battle['bi'][i];
                            }
                            for(var i in battle['bd']){
                                ch[i]=battle['bd'][i];
                            }
                        }
                        break;
                    }
                }
                console.log(exist);

                if (exist) {
                    continue;
                }
                console.log(ch);
                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[type].unshift(rec);
                updated = true;
            }
            if (updated || now.getTime() - d.getTime() > 7 * 24 * 3600 * 1000) {
                var delArray = [];
                for (var j in changes['pvp']) {
                    if (checkERROR(changes['pvp'][j]) || changes['pvp'][j]['type'] == 'temp') {
                        delArray.unshift(j);
                    }
                }
                for (var i in delArray) {
                    changes['pvp'].splice(delArray[i], 1);
                }
                for (var cd in ships['pvp']) {
                    if (checkERROR(ships['pvp'][cd]['battles'])) {
                        ships['pvp'][cd]['tempBattle'] = 0;
                    } else if (ships['pvp'][cd]['tempBattle'] > ships['pvp'][cd]['battles']) {
                        ships['pvp'][cd]['tempBattle'] = ships['pvp'][cd]['battles'];
                    }
                }
                delArray = [];
                for (var j in changes['rank']) {
                    if (checkERROR(changes['rank'][j]) || changes['rank'][j]['type'] == 'temp') {
                        delArray.unshift(j);
                    }
                }
                for (var i in delArray) {
                    changes['rank'].splice(delArray[i], 1);
                }
                for (var cd in ships['rank']) {
                    if (checkERROR(ships['rank'][cd]['battles'])) {
                        ships['rank'][cd]['tempBattle'] = 0;
                    } else if (ships['rank'][cd]['tempBattle'] > ships['rank'][cd]['battles']) {
                        ships['rank'][cd]['tempBattle'] = ships['rank'][cd]['battles'];
                    }
                }
            }
            br.set('ships', ships);
            br.set('changes', changes);
            if (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;
                        var type = getBattleType(day['id']['battleTypeId']);
                        for (var j in changes[type]) {
                            var ch = changes[type][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;
                                //修正新接口
                                if(!('damagebb' in ch)){
                                    for(var i in day){
                                        ch[i]=day[i];
                                    }
                                }
                                break;
                            }
                        }
                        if (!exist) {
                            var rec = day;
                            rec['type'] = 'day';
                            rec['battle_time'] = Number(Number(rec['insert_date']['time'] / 1000).toFixed(0));
                            rec['cd'] = rec['id']['vehicleTypeCd'];
                            changes[type].unshift(rec);
                            changes[type].sort(sortBattle);
                            br.set('changes', changes);
                            updated = true;
                        }
                    }
                });
            }
            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];
                        var type = getBattleType(ship['id']['battleTypeId']);
                        if (type == ship['id']['battleTypeId']) {
                            continue;
                        }
                        ship['exp'] = ship['exp'];
                        ship['alive'] = ship['alive'];
                        ship['battle_time'] = ship['update_date']['time'] / 1000;
                        ship['damage'] = ship['damage'];
                        var cd = ship['id']['vehicleTypeCd'];
                        if (!(cd in record[type])) {
                            record[type][cd] = {
                                tempBattle: 0,
                                tempWin: 0
                            }
                        }
                        var tempBattle = record[type][cd]['tempBattle'];
                        var tempWin = record[type][cd]['tempWin'];
                        record[type][cd] = ship;
                        if (tempBattle < ship['battles']) {
                            tempBattle = ship['battles'];
                        }
                        if (tempWin < ship['wins']) {
                            tempWin = ship['wins'];
                        }
                        record[type][cd]['tempBattle'] = tempBattle;
                        record[type][cd]['tempWin'] = tempWin;
                    }
                    br.set('tempTotalPVP', dossier.mergeRecordList(record['pvp']));
                    br.set('tempTotalRANK', dossier.mergeRecordList(record['rank']));
                    br.set('ships', record);
                    dossier.decodeDossier(br);
                });
            } else {
                dossier.decodeDossier(br);
            }
        });
        br.set("lastUpdate", new Date().getTime())
    },
    decodeDossier: function (br) {
        if (!fs.existsSync(config.get('path') + '/profile/python.log')) {
            return;
        }
        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("danger","缓存文件过大，无法解析，请清理\n"+config.get('path') + '/profile/python.log',0);
                return;
            }
            try {
                var json = JSON.parse(output.replace(/\'/g, "\"").replace(/L/g, ""));
                if (json.length > 0) {
                    if("error" in json){
                        if(json["error"]==1){
                            customAlert("danger","缓存文件过大，无法解析，请清理\n"+config.get('path') + '/profile/python.log',0);
                        }
                        return;
                    }
                    var tempTotalPVP = br.get('tempTotalPVP');
                    var tempTotalRank = br.get('tempTotalRANK');
                    if (checkERROR(tempTotalPVP)) {
                        return;
                    }
                    var updated = false;
                    var ships = br.get('ships');
                    var changes = br.get('changes');
                    for (var i in json) {
                        updated = updated || dossier.updateDossier(json[i], tempTotalPVP, 'pvp', changes, ships);
                        updated = updated || dossier.updateDossier(json[i], tempTotalRank, 'rank', changes, ships);
                    }
                    if (updated) {
                        br.set('tempTotalPVP', tempTotalPVP);
                        br.set('tempTotalRANK', tempTotalRank);
                        br.set('ships', ships);
                        br.set('changes', changes);
                        dossier.refreshDossier();
                    }
                }
            }
            catch (e) {
                console.log(e);
            }
        });
    },
    updateDossier: function (newTotal, tempTotal, type, changes, ships) {

        try {
            if (!('battles' in newTotal[type]) || newTotal[type]['battles'] <= tempTotal['battles']) {
                return false;
            }
            var shipList = [];
            for (var cd in newTotal[type]['list']) {
                if (cd in shipDict) {
                    if (cd in ships[type]) {
                        if (ships[type][cd]['tempBattle'] < newTotal[type]['list'][cd]['battles']) {
                            shipList.push(cd);
                            ships[type][cd]['tempBattle'] = newTotal[type]['list'][cd]['battles'];
                        }
                    } else {
                        shipList.push(cd);
                    }
                }
            }
            if (shipList.length == 1) {
                shipList = Number(shipList[0]);
            } else if (shipList.length == 0) {
                return false;
            }
            var rec = dossier.getDiff(tempTotal, newTotal[type], newTotal['battle_time'], shipList);
            if (typeof(shipList) != 'object') {
                if (!(shipList in ships[type])) {
                    var cd = shipList
                    ships[type][cd] = rec;
                    ships[type][cd]['tempBattle'] = newTotal[type]['list'][cd]['battles'];
                }
            } else {
                for (var j in shipList) {
                    var cd = shipList[j];
                    if (!(cd in ships[type])) {
                        ships[type][cd] = {tempBattle: newTotal[type]['list'][cd]['battles']}
                    }
                }
            }
            for (var j in newTotal[type]) {
                if (j == 'list') {
                    continue;
                }
                tempTotal[j] = newTotal[type][j];
            }
            rec['type'] = 'temp';
            changes[type].unshift(rec);
            return true;
        }
        catch (e) {
            console.log(e);
            return false;
        }
    }
};
function getJsonChange(changes,ship){
    return {
        "cd":ship['cd'],
        "battles":changes['battles'],
        "wins":changes['wins'],
        "damage":changes['damage'],
        "killship":changes['killship'],
        "killplane":changes['killplanes'],
        "capture":changes['capture'],
        "defense":changes['defense'],
        "battle_time":Number(Number(changes['time']/1000).toFixed(0)),
        "exp":changes['exp'],
        "alive":changes['alive']
    }
}
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,
        'killship': data['killship'],
        'killplane': data['killplanes'],
        'damage': data['damage'],
        'capture': data['capture'],
        'defense': data['defense'],
        'exp': data['exp'],
        'alive': data['alive'],
        'maxkillship': data['maxkillship'],
        'maxkillplane': data['maxkillplane'],
        'maxexp': 0,
        'maxdamage': data['maxdamage']
    }
}
function sortTime(a,b){
    return a[0] - b[0];
}
function sortBattle(a,b){
    return b['battle_time']-a['battle_time'];
}

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 getTotalBattles(list,val){
    var b=0;
    for(var i in list){
        b+=list[i][val];
    }
    return b;
}

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;
    }
}

function getBattleType(type){
    switch(type){
        case 0:
            return "pvp";
        case 4:
            return "rank";
        case 2:
            return "pve";
        default:
            return type;
    }
}