configExtList=['.txt','.xc','.xml','.json'];

var ModManager = function () {
    this.db = null;
    this.jsonlist = null;
    this.minver = 0;
    this.loadLocalList();
}
ModManager.prototype = {
    //记录手动安装和沙盘安装的插件
    newModRecord: function (path, modid, name, time) {    //保存位置, modid, 名称, 时间
        if (checkERROR(this.db.json.modlist)) {
            this.db.json.modlist = new Object();
        }
        if (checkERROR(modid)) {
            for (var i in this.db.json.modlist) {
                if (this.db.json.modlist[i].path==path) {
                    modid = this.db.json.modlist[i].id;
                }
            }
        }
        //遍历寻找失败，赋默认值
        if (checkERROR(modid)) {
            modid = --this.minver;
        }
        this.db.json.modlist[modid.toString()] = {
            id: modid,
            path: path,
            name: name,
            time: time
        };
        this.db.update();
    },
    getLocalMod: function(id){
        if(checkERROR(this.db.json)){
            return null;
        }
        return this.db.json.modlist[id];
    },
    //读取本地的安装记录
    loadLocalList: function () {
        this.db = new Config("mod.db");
        for (var i in this.db.json.modlist) {
            if (i < this.minver) {
                this.minver = i;
            }
        }
    },
    getRemoteMod: function(id){
        if(checkERROR(this.jsonlist)){
            return null;
        }
        return this.jsonlist.modlist[id];
    },
    //读取服务器的插件列表
    loadRemoteList: function (callback) {
        var mm = this;
        $.get("http://rank.kongzhong.com/ModDownload/action/ModAction/modList", function (data, status) {
            try {
                mm.jsonlist = JSON.parse(data);
                if (typeof(callback) == "function") {
                    callback();
                }
            }
            catch (e) {
                console.log("getModList error", e);
                customAlert("插件列表错误", "warning");
            }
        });
    },
    //下载插件
    downloadMod: function (id) {
        var mod = this.jsonlist.modlist[id];
        if (mod == null) {
            customAlert("选择的插件不存在", "warning");
            return;
        }
        var url = mod.url;
        var savepath = "download_mods/" + mod.name+mod.ext;
        customAlert(mod.name + "开始下载", "info");
        downloadCenter.add(url, savepath, mod.name, function (path) {
            var id=getUniqueId();
            new CleverInstaller(id, mod.name, path, "install");
            modManager.newModRecord(path, mod.id, mod.name, id);
        });
    }
}

//更新插件列表
function refreshModList() {
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    nowpage="modlist";
    $("#modlist").load("modlist.html #moddiv", function (data) {
        if(nowpage!="modlist"){
            return;
        }
        modManager.loadRemoteList(function(){
            if(nowpage!="modlist"){
                return;
            }
            modLayout();
            var l=config.get("defaultLayout");
            $(".modlayout").hide();
            if(l=="pic") {
                $("#modpiclayout").show();
            }else{
                $("#modlistlayout").show();
            }
            $("#modfilter").after('如果你对插件版权有异议，请在这里反馈<a style="color:red;" href="http://xvm.garphy.com/?p=10585">点击反馈</a>');
        });
        $(".listlayout").click(function(){
            $(".modlayout").hide();
            $("#modlistlayout").show();
            config.set("defaultLayout","list");
            $("#modfilterBy").children(".filterbtn").click();
        });
        $(".piclayout").click(function(){
            $(".modlayout").hide();
            $("#modpiclayout").show();
            config.set("defaultLayout","pic");
            $("#modfilterBy").children(".filterbtn").click();
        });
    });
}

//mod排版
function modLayout(){
    var lasttime=modManager.db.get("lastTime");
    var now=getUniqueId();
    if(checkERROR(lasttime)){
        lasttime=getUniqueId();
    }
    if(now-lasttime>3600*1000) {
        modManager.db.set("lastTime", now);
    }
    var modlist=modManager.jsonlist;
    if (modlist == null) {
        return;
    }
    var tagslist=['#62c462','#4b9eb8','#b37724','#cc524e','#8a9299'];
    var modsort=new Object();
    for (var i in modlist.modlist) {
        var mod = modlist.modlist[i];
        if (mod == null||i==0) {
            continue;
        }
        if(mod.sort==""){
            mod.sort="未分类";
        }
        if (mod.url != "") {
            var newer=false;
            if(lasttime<mod.time){
                newer=true;
            }
            var d=new Date();
            d.setTime(mod.time);
            //pic方式显示
            var info = '<div class="moddiv modpic panel panel-default"><div class="panel-heading modname"><h3 class="panel-title">' + mod.name +(newer?"&nbsp;&nbsp;<span style='color:red;'>New!</span>":"")+ (mod.good>0?'<div class="pull-right"><i class="fa fa-thumbs-o-up"></i></div>':'')+'</h3></div>'
            info+='<div class="panel-body">';
            info+='<div class="modimage"><img src="' + mod.image + '"></div>';
            info+='<div class="">' + date2str(d,"yyyy-MM-dd") + '</div>';
            info+='<div class="pull-right text-right">发布者:'+mod.publisher+'</div>';
            info+='<div class="">作者:' + mod.author + '</div>';
            info+='<div class="pull-right text-right">总下载:' + mod.down + '次</div>';
            info+='<div class="">分类:'+mod.sort+'</div>';
            info+='<div class="bottomright">'
            if(mod.config>0) {
                info += '<button type="button" onclick="window.open(\'configlist.html?modid='+mod.id+'\',\'_blank\')" class="btn btn-sm btn-info modconfig">查看配置</button>&nbsp;&nbsp;';
            }
            info+='<button type="button" class="btn btn-sm btn-success modinstall">下载安装</button></div>';
            info+='<div class="hide url">' + mod.url + '</div>';
            info+='<div class="hide sort">' + mod.sort + '</div>';
            info+='<div class="hide id">' + mod.id + '</div></div>';
            info+='</div>'
            $("#modpiclayout").append(info);

            //list方式显示
            var tr = "<tr onmousemove='showImage(\"" + mod.image
                + "\",\""+mod.description+"\")' onmouseout='hideImage()' class='moddiv modtr' id='" + mod.id + "'>";
            tr += "<td class='name stext'>"+ mod.name +(newer?"&nbsp;&nbsp;<span style='color:red;'>New!</span>":"")+(mod.good>0?'<div class="pull-right"><i class="fa fa-thumbs-o-up"></i></div>':'')+  "</td>";
            tr += "<td class='sort stext'>" + mod.sort + "</td>";
            tr += "<td class='stext'>" + mod.author + "</td>";
            tr += "<td class='stext'>" + mod.down + "</td>";
            tr += '<td class="stext">'+date2str(d,"yyyy-MM-dd hh:mm:ss")+'</td>';
            tr += '<td><button type="button" class="btn btn-sm btn-default moddetail" data-toggle="modal" data-target="#modModal">查看详情</button>&nbsp;&nbsp;<button type="button" class="btn btn-sm btn-success modinstall">下载安装</button>&nbsp;&nbsp;';
            if(mod.config>0) {
                tr += '<button type="button" onclick="window.open(\'configlist.html?modid='+mod.id+'\',\'_blank\')" class="btn btn-sm btn-info modconfig">查看配置</button>&nbsp;&nbsp;';
            }
            tr += '</td>';
            tr += '<td class="hide id">' + mod.id + '</td>';
            tr += "</tr>";
            $("#modbody").append(tr);
            if(mod.sort in modsort){
                modsort[mod.sort]++;
            }else{
                modsort[mod.sort]=1;
            }
        }
    }

    if($("#modbody").children().length>0){
        $("table#modtable").tablesorter({
            sortInitialOrder : "desc",
            sortList : [ [ 4, 1 ] ]
        });
        $("#modfilterBy").children(".btn").children(".badge").text($("#modbody").children().length);
    }
    for (var sort in modsort){
        var button="<button type='button' class='btn btn-sm filterbtn btn-default'>"+sort+"&nbsp;<span class='badge'>"+modsort[sort]+"</span></button>";
        $("#modsortType").append(button);
    }
    //筛选按钮
    $(".filterbtn").click(function(){
        $(".modlayout:visible").find(".moddiv").show();
        var s=$(this).html().split("&nbsp;")[0];
        $(".moddiv:visible").each(function(i,n){
            if(s!="全部"){
                if($(n).find(".sort").text()!=s){
                    $(n).hide();
                }
            }
        });
        $("#modsortType").append($("#modfilterBy").children(".filterbtn"));
        $("#modfilterBy").append(this);
    });
    $(".moddetail").click(function(){
        var id=$(this).parent().parent().attr("id");
        $("#modbody").children(".active").removeClass("active");
        $(this).parent().parent().addClass("active");
        updateDetail(modManager.getRemoteMod(id));
    });

    $("button.modconfig").click(function(){
        var id = $(this).parent().parent().children(".id").text();
        openConfigList(id);
    });
    $("button.modinstall").click(function (i, e) {
        if (checkERROR(config.get('path'))) {
            customAlert("未找到游戏路径，请先设置", 'warning');
            return;
        }
        console.log("install:" + $(this).parent().parent().children(".id").text());
        modManager.downloadMod($(this).parent().parent().children(".id").text());
    });
}

function refreshModDelList() {  //安装记录列表
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    nowpage="moddel";
    $("#modlist").load("modtable.html #modtable", function (data) {
        if(nowpage!="moddel"){
            return;
        }
        for (var i in modManager.db.json.modlist) {
            var mod = modManager.db.json.modlist[i.toString()];
            if(mod==null){
                continue;
            }
            var d=new Date();
            d.setTime(mod.time);
            var info = "<tr id='mod" + mod.id + "'><td class='stext'><input class='modcheckbox' type='checkbox'></td><td class='tablename stext'>" + mod.name + "</td><td class='time stext'>" + date2str(d,"yyyy-MM-dd hh:mm:ss") + "</td><td class='modopr'><button type='button' class='btn btn-sm btn-primary modifyconfig'  data-toggle='modal' data-target='#modModal'>自定设置</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-success update'>更新插件</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-info install'>重安装插件</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-warning del'>卸载插件</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-danger remove' title='"+mod.path+"'><i class='fa fa-times'></i></button></td><td class='hide path'>" + mod.path + "</td></tr>";
            $("#modbody").append(info);
            //存在这个id且时间比本地的大
            if(!checkERROR(modManager.getRemoteMod(i))&&modManager.jsonlist.modlist[i].time>mod.time){
                $("#mod" + mod.id).children('.tablename').append("&nbsp;<span class='label label-success'>更新</span>");
            }else{
                $("#mod" + mod.id).children(".modopr").children(".update").addClass('disabled');
            }
            if(!checkERROR(modManager.getRemoteMod(i))){
                if(modManager.getRemoteMod(i).config>0){
                    $("#mod"+mod.id).children(".modopr").prepend('<button type="button" onclick="window.open(\'configlist.html?modid='+mod.id+'\',\'_blank\')" class="btn btn-sm btn-default modconfig">可选设置</button>&nbsp;&nbsp;');
                }
            }
            var exists=fs.existsSync(mod.path);
            if (!exists) {
                $("#mod" + mod.id).children(".modopr").children(".install").addClass('disabled');
                $("#mod" + mod.id).children(".modopr").children(".del").addClass('disabled');
                $("#mod" + mod.id).children(".modopr").children(".modifyconfig").addClass('disabled');
                $("#mod" + mod.id).children(".modopr").attr("title", "文件不存在");
            }
            if($("#modbody").children().length>0){
                $("table#modtab").tablesorter({
                    sortInitialOrder : "desc",
                    sortList : [ [ 2, 1 ] ]
                });
            }
        }
        //特别设置
        $("#configconfig").click(function(){
            var path=config.get("notepadPath");
            if(checkERROR(path)){
                path="";
            }
            var div='<div class="modal-dialog">';
            div+='<div class="modal-content">';
            div+='<div class="modal-header">';
            div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
            div+='<h4 class="modal-title" id="myModalLabel">文本编辑器路径设置</h4></div>';
            div+='<div class="modal-body">';
            div+='<label for="path" class="control-label">文本编辑器路径</label>';
            div+='<div class="input-group">';
            div+='<input type="text" class="form-control" id="path" value="'+path+'">';
            div+='<span class="input-group-btn">';
            div+='<button type="button" class="btn btn-default" style="display:none;" id="custompath">保存路径</button>';
            div+='<button type="button" class="btn btn-default" id="configpath">设置路径</button>';
            div+='</span></div>';
            div+='</div>';
            div+='</div></div>';
            $("#modModal").html(div);
            $("#path").change(function(){
                $("#custompath").show();
                $("#configpath").hide();
            });
            $("#custompath").click(function(){
                config.set("notepadPath",$("#path").val());
                customAlert("文本编辑器路径设置为"+$("#path").val(),"success");
                $("#custompath").hide();
            });
            $("#configpath").click(function(){
                console.log("configpath");
                chooseFile(function(path){
                    var p=unescape(path);
                    customAlert("文本编辑器路径设置为"+p,"success");
                    config.set("notepadPath",p);
                    $("#path").val(p);
                });
            })
        });

        $("button.modconfig").click(function(){
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            openConfigList(id);
        });

        //自己修改配置
        $("button.modifyconfig").click(function(){
            var name = $(this).parent().parent().children(".tablename").text();
            var path = $(this).parent().parent().children(".path").text();
            var fname=getFileName(path);
            if(fname.lastIndexOf(".")!=-1) {
                var ext = fname.substr(fname.lastIndexOf("."));
                var func = null;
                if (ext.toLowerCase() == ".zip" || ext.toLowerCase() == ".wbp") {
                    func = listZip;
                } else if (ext.toLowerCase() == ".rar") {
                    func = listRar;
                } else if (ext.toLowerCase() == ".7z") {
                    func = list7z;
                } else {
                    customAlert("不支持的压缩包格式");
                }
                if (typeof(func) == "function") {
                    func(path, configExtList, function (list) {
                        var configlist=[];
                        for(var i in list){
                            var file=list[i];
                            if(file.indexOf("res_mods")!=-1){
                                var realpath=config.get("path")+"/res_mods"+file.split("res_mods")[1];
                                if(fs.existsSync(realpath)){
                                    configlist.push(realpath);
                                }
                            }
                        }
                        showConfigList(configlist);
                    })
                }
            }
        });
        $("button.update").click(function () {
            var name = $(this).parent().parent().children(".tablename").text();
            var path = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            customConfirm("更新插件: " + name, function () {
                console.log("update", name);
                modManager.downloadMod(id);
            });
        });
        $("button.install").click(function () {
            var name = $(this).parent().parent().children(".tablename").text();
            var path = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            customConfirm("重新安装插件: " + name, function () {
                console.log("reinstall", name);
                new CleverInstaller(getUniqueId(), name, path, 'install');
            });
        });
        $("button.del").click(function () {
            var name = $(this).parent().parent().children(".tablename").text();
            var path = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            customConfirm("即将卸载插件: " + name, function () {
                console.log("del", name);
                new ConfigManager().delAllModConfig(id,name);
                new CleverInstaller(getUniqueId(), name, path, 'delete');
            });
        });
        $("button.remove").click(function () {
            var name = $(this).parent().parent().children(".tablename").text();
            var path = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            customConfirm("即将删除插件文件和记录: " + name, function () {
                console.log("remove", name);
                delete modManager.db.json.modlist[id];
                modManager.db.update();
                var dm = new DeleteManager(id, name, false, null, null);
                dm.add(path, path);
                dm.start();
                $("#mod" + id).remove();
            });
        });
        $("button.updateall").click(function(){
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.update").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.update").click();
                }
            });
        });
        $("button.reinstallall").click(function(){
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.install").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.install").click();
                }
            });
        });
        $("button.deleteall").click(function(){
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.del").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.del").click();
                }
            });
        });
        $("button.clearall").click(function(){
            customConfirm("确定要删除全部插件文件?",function(){
                var modpath=config.get('path')+"/res_mods";
                deleteFolderRecursive(modpath,1);
            });
        });
        $("button.configall").click(function(){
            var configlist=listFolderRecursive(config.get('path')+"/res_mods/"+newestVersion);
            configlist=configlist.concat(listFolderRecursive(config.get('path')+"/res_mods/xvm"));
            if(checkERROR(configlist)){
                return
            }
            var list=[];
            for (var i in configlist){
                var y=configlist[i].trim();
                var idx=y.lastIndexOf('.')
                if(idx!=-1&&idx> y.length-6&&idx< y.length-2){
                    var ext= y.substr(y.lastIndexOf('.'));
                    for (var x in configExtList){
                        var c=configExtList[x];
                        if(ext==c){
                            list.push(y);
                            console.log(y);
                            break;
                        }
                    }
                }
            }
            showConfigList(list);
        });
        $("button.checkall").click(function(){
            if($(":checkbox").size()==$(":checkbox[checked='checked']").size()){
                $(":checkbox").each(function(){
                    $(this).attr("checked",false);
                });
            }else{
                $(":checkbox").each(function(i,n){
                    $(this).attr("checked",true);
                    $(n)[0].checked="checked";
                });
            }
        });
        $("button.removeall").click(function(){
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.remove").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.remove").click();
                }
            });
        });
    });
}

function showConfigList(configlist){
    var pattern;
    var patterninit=false;
    if(fs.existsSync("apps/index/configPattern.json")){
        try {
            var data = fs.readFileSync("apps/index/configPattern.json", 'utf8');
            pattern = JSON.parse(data);
            patterninit = true;
        }catch(e){
            console.log("pattern error", e);
        }
    }else{
        console.log("no pattern file");
    }
    var div='<div class="modal-dialog modal-lg">';
    div+='<div class="modal-content">';
    div+='<div class="modal-header">';
    div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
    div+='<h4 class="modal-title" id="myModalLabel">'+name+'设置文件列表</h4></div>';
    div+='<div class="modal-body">';
    if(configlist.length==0){
        div+="<div>找不到可进行设置的文件</div>";
    }else{
        div+='<div>点击链接将打开设置文件</div>';
        for(var i in configlist){
            var filepath=configlist[i];
            var alias='res_mods'+filepath.split("res_mods")[1];
            if(patterninit){
                for(var i in pattern){
                    if(alias.indexOf(i)!=-1){
                        alias=pattern[i];
                        break;
                    }
                }
            }
            var fname=getFileName(filepath);
            div+='<div><a href="#" class="configfile" path="'+filepath+'">'+fname+'<span class="pull-right">&nbsp;'+alias+'</span></a></div>';
        }
    }
    div+='</div>';
    div+='</div></div>';
    $("#modModal").html(div);
    $(".configfile").click(function(){
        var file=$(this).attr("path");
        var notepadPath=config.get("notepadPath");
        if(checkERROR(notepadPath)||notepadPath==""){
            notepadPath="notepad.exe";
        }
        cp.exec("\""+notepadPath+"\" "+file,{encoding: 'binary'}, function (err, stdout, stderr) {
            //customAlert(err);
        });
    });
}

function updateDetail(detail){
    if(checkERROR(detail)){
        return;
    }
    var div='<div class="modal-dialog">';
    div+='<div class="modal-content">';
    div+='<div class="modal-header">';
    div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
    div+='<h4 class="modal-title" id="myModalLabel">'+detail.name+'</h4></div>';
    div+='<div class="modal-body">';
    div+='<button type="button" class="btn btn-success modinstall" data-dismiss="modal" id="modalinstall">下载安装</button>&nbsp;&nbsp;';
    if(detail.config>0) {
        div += '<button type="button" onclick="window.open(\'configlist.html?modid='+detail.id+'\',\'_blank\')" class="btn btn-info modconfig">查看配置</button>&nbsp;&nbsp;';
    }
    div+='</div>';
    div+='<div class="modal-footer">';
    div+="<p class='sort'>分类:\t"+detail.sort+"</p>";
    div+="<p>原作者:\t"+detail.author+"</p>";
    div+="<p>发布者:\t"+detail.publisher+"</p>";
    div+="<p>下载量:\t"+detail.down+"</p>";
    var d = new Date();
    d.setTime(detail.time);
    div+="<p>更新时间:\t"+date2str(d,"yyyy-MM-dd hh:mm:ss")+"</p>";
    div+="<p>"+detail.description+"</p>";
    div+="<img class='middleimg' src='" + detail.image + "'>";
    div+='</div>';
    div+='</div></div>';
    $("#modModal").html(div);

    $("#modalinstall").click(function (i, e) {
        if (checkERROR(config.get('path'))) {
            customAlert("未找到游戏路径，请先设置", 'warning');
            return;
        }
        console.log("install:" + detail.url);
        modManager.downloadMod(detail.id);
    });
    $("button.modconfig").click(function(){
        var id = detail.id;
        openConfigList(id);
    });
}

function showImage(img,desc) {
    if(img!=""){
        var t1 = "<div style='margin: 0px auto 0px auto'><img class='middleimg' src='" + img + "'></div><div>"+desc+"</div>";
        $("#a1").html(t1);
        $("#a1").css("top", document.body.scrollTop + event.clientY -200);
        $("#a1").css("left", document.body.scrollLeft + event.clientX -200);
        $("#a1").show();
    }
}
function hideImage() {
    $("#a1").hide();
}

function openConfigList(id){

}

modManager = new ModManager();