var OtherDossier=function(){

};
OtherDossier.prototype= {
    showRecentBattles: function (update) {
        if (update) {
            dossier.refreshDossier();
        }
        var error = false;
        if (checkERROR(config.get('account'))) {
            customAlert('未指定帐号', 'warning');
            return;
        }
        dossier.syncData();
    },
    refreshDossier: function () {
        $("#battlepage").load("dossierOther.html #container", function (data) {
            if (!fs.existsSync('profile/' + config.get('account')['active'] + '.db')) {
                return;
            }
            var br = new Config('profile/' + config.get('account')['active'] + '.db');
            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);
            }
            $(".china").remove();
            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);
            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 ('power' in battle) {
                div += "<td class='china'>" + Number((battle['power'] + battle['winpower']) * 100 / ship['weight']).toFixed(0) + "%</td>";
            } else {
                div += "<td class='china'>--%</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);
        }
    },
    getDiff: function (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;
    },
    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 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;
    },
    mergeRecordList: function (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;
    },
    refreshShipList: function () {
        $("#shipspage").load("dossierOther.html #shipslist", function (data) {
            var aid = config.get('account')['active'];
            if (!fs.existsSync('profile/' + aid + '.db')) {
                customAlert("未找到数据", "danger");
            }
            var china = false;
            var br = new Config('profile/' + aid + '.db');
            var total = dossier.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(dossier.getShipTr(ship, shipData, china));
            }
            $("#shipsbody").append(dossier.getShipTr(totalShip, total, china));
            refreshClass();
            if ($("#shipsbody").children().length > 0) {
                $("table#shipstable").tablesorter({
                    sortInitialOrder: "desc",
                    sortList: [
                        [ 4, 1 ]
                    ]
                });
            }
            $("#shipspage").show();
        });
    },
    getShipTr: function (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;
    },
    syncData: function () {
        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 = dossier.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);
                dossier.updateByType(br, 'pvp', json);
                //var rank=updateByType(br.get('ships')['rank'],'rank',json);
                dossier.refreshDossier();
            }
            catch (e) {
                console.log(e);
            }
        });
    },
    updateByType:function(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(dossier.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(dossier.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);
    }
};