var click_id = "";//选中节点的标识
var click_name = "";//选中节点的名称
var click_type = "";//选中节点的类型
var click_remark = "";//选中节点的备注

var treeNode_ = {};//鼠标点击的节点
var tree_nodes = {};//整个树形对象

var tree_oper = {};//需要操作的节点对象
$(document).ready(function(){
    showTree("div_tree_box");
});

/**
 * 加载数据字典结构树
 */
function showTree(ele_class){
    var setting = {
        async: {
            enable: true,
            url: "/claim-risk/dictionary/findDictionaryTree.do"
        },
        check: {
            enable:false
        },
        data:{
            key: {
                children:"child",
                name: "name"
            },
            simpleData: {
                idKey: "id"
            }
        },
        callback: {
            onClick: function(event, treeId, treeNode){
                gridLoad(event,treeNode);
            }
        }
    };
    tree_nodes = new Tree($("#"+ele_class),true,setting);
}

/**
 * 便利点击节点，并加载右侧列表负责人
 * @param event
 * @param treeNode 节点
 */
function gridLoad(event,treeNode){
    treeNode_ = treeNode;
    if(treeNode == null || treeNode == undefined){
        $("#context_body_manager").html("");
        return false;
    }
    click_id = treeNode.id;
    click_name = treeNode.name;
    click_remark = treeNode.remark;

    if(treeNode.child == null || treeNode.child == undefined || treeNode.child.length == 0){
        $.ajax({
            url : "treeClickFindDictData.do",
            async : false,
            dataType:"json",
            type : "post",
            data : {
                id:click_id
            },
            success : function(data) {
                if(data.result == "success"){
                    var context = "";
                    var data = data.data;
                    if(data != null){
                        for (var j = 0; j < data.length; j++) {
                            var array_element = data[j];
                            var id = array_element.id == null?"":array_element.id;
                            var name = array_element.name == null?"":array_element.name;
                            var code = array_element.code == null?"":array_element.code;
                            var val = array_element.val == null?"":array_element.val;
                            var status = array_element.status == null?"":array_element.status;
                            var remark = array_element.remark == null?"":array_element.remark;
                            var pid = array_element.pId == null?"":array_element.pId;

                            remark = remarkReplac(remark, val);

                            var serialnum = j+1;
                            var name_ = name ;
                            var code_ = code;
                            var val_ = val;
                            var ramark_ = remark;
                            var pid_ = pid;
                            var status_ = status;
                            if(code.length > 20){
                                code = code.substring(0, 19) + "……";
                            }
                            if(val.length > 20){
                                val = val.substring(0, 19) + "……";
                            }
                            if(name.length > 16){
                                name = name.substring(0, 15) + "……";
                            }
                            if(remark.length > 12){
                                remark = remark.substring(0,11) + "……";
                            }
                            if(status == 1){
                                status = "有效";
                            }else{
                                status = "失效";
                            }
                            context += "<tr onclick='mousClick(this)' _id='"+id+"' name='"+name_+"' code='"+code_+"' val='"+val_+"' status='"+status_+"' remark='"+ramark_+"' serialnum='"+serialnum+"'>"+
                                "<td style='text-align: center;'>"+serialnum+"</td>"+
                                "<td style='text-align: center;' title='"+name_+"'>"+name+"</td>"+
                                "<td style='text-align: center;' title='"+code_+"'>"+code+"</td>"+
                                "<td style='text-align: center;' title='"+val_+"'>"+val+"</td>"+
                                "<td style='text-align: center;' title='"+ramark_+"'>"+remark+"</td>"+
                                "<td style='text-align: center;'>"+status+"</td>"+
                                "</tr>";
                        }

                        $("#context_body_manager").html(context);
                    }
                }
            }
        });
    }else{
        $.ajax({
            url : "treeClickFindDictData.do",
            async : false,
            dataType:"json",
            type : "post",
            data : {
                pid:click_id
            },
            success : function(data) {
                if(data.result == "success"){
                    var context = "";
                    var data = data.data;
                    if(data != null){
                        for (var j = 0; j < data.length; j++) {
                            var array_element = data[j];
                            var id = array_element.id == null?"":array_element.id;
                            var name = array_element.name == null?"":array_element.name;
                            var code = array_element.code == null?"":array_element.code;
                            var val = array_element.val == null?"":array_element.val;
                            var status = array_element.status == null?"":array_element.status;
                            var remark = array_element.remark == null?"":array_element.remark;
                            var pid = array_element.pId == null?"":array_element.pId;
                            var serialnum = j+1;

                            remark = remarkReplac(remark, val);

                            var name_ = name ;
                            var code_ = code;
                            var val_ = val;
                            var ramark_ = remark;
                            var status_ = status;
                            var pid_ = pid;

                            if(code.length > 20){
                                code = code.substring(0, 19) + "……";
                            }
                            if(val.length > 20){
                                val = val.substring(0, 19) + "……";
                            }
                            if(name.length > 16){
                                name = name.substring(0, 15) + "……";
                            }
                            if(remark.length > 12){
                                remark = remark.substring(0,11) + "……";
                            }
                            if(status == 1){
                                status = "有效";
                            }else{
                                status = "失效";
                            }
                            context += "<tr onclick='mousClick(this)' _id='"+id+"' name='"+name_+"' code='"+code_+"' val='"+val_+"' status='"+status_+"' remark='"+ramark_+"' serialnum='"+serialnum+"'>"+
                                "<td style='text-align: center;'>"+serialnum+"</td>"+
                                "<td style='text-align: center;' title='"+name_+"'>"+name+"</td>"+
                                "<td style='text-align: center;' title='"+code_+"'>"+code+"</td>"+
                                "<td style='text-align: center;' title='"+val_+"'>"+val+"</td>"+
                                "<td style='text-align: center;' title='"+ramark_+"'>"+remark+"</td>"+
                                "<td style='text-align: center;'>"+status+"</td>"+
                                "</tr>";
                        }

                        $("#context_body_manager").html(context);
                    }
                }
            }
        });
    }
}

/**
 * 行事件点击
 * @param ele
 */
function mousClick(ele){
    $(ele).addClass("success").siblings().removeClass("success");
}

/**
 * 新增
 */
function addDictData(){
    if(click_id == ""){
//		alertui("请选择一个节点");
        $(".modal-body").html("请选择一个节点");
        $("#myModal").modal("show");
        return false;
    }
    $("#edit_dn").modal_n({
        title: "新增字典数据",
        width:"35%",
        resizable: true,
        buttons: [
            {
                text: "确定",
                click: function (){
                    var c_unit_name = $(".unit_name").val();
                    var c_unit_code = $(".unit_code").val();
                    var c_unit_val = $(".unit_val").val();
                    // var unit_serialnum = $(".unit_serialnum").val();
                    var c_unit_status = $("#unit_status").val();//id选择
                    var c_unit_remark = $(".unit_remark").val();

                    if(c_unit_name == null || c_unit_name == ""){
                        showErrorMsg("名称有误，请检查");
//						alertui();
                        return false;
                    }
                    if(c_unit_name.length > 80){
                        showErrorMsg("名称太长");
                        return false;
                    }
                    if(c_unit_code == null || c_unit_code == ""){
                        showErrorMsg("编码不能为空");
                        return false;
                    }
                    if(c_unit_code.length > 50){
                        showErrorMsg("编码太长");
                        return false;
                    }
                    if(c_unit_val == null || c_unit_val == ""){
                        showErrorMsg("数值有误，请检查");
                        return false;
                    }
                    /*	if(unit_serialnum == null || unit_serialnum == "" || isNaN(unit_serialnum)){
                            showErrorMsg("序列号有误，请检查");
                            return false;
                        }*/

                    if(c_unit_status == null || c_unit_status == ""){
                        showErrorMsg("状态为空，请检查");
                        return false;
                    }
                    var flag = false;
                    $.ajax({
                        url : "addDictData.do",
                        async : false,
                        dataType:"json",
                        type : "post",
                        data : {
                            name:c_unit_name,
                            code:c_unit_code,
                            val:c_unit_val,
                            remark:c_unit_remark,
                            pid:click_id,
                            status:c_unit_status

                        },
                        success : function(data) {
                            var result = data.result;
                            if(result == "success"){
                                flag = true;
//								alertui("添加成功");
                                $(".modal-body").html("添加成功");
                                $("#myModal").modal("show");
                                var new_node = {};//创建新的节点
                                for(var el in treeNode_){
                                    if(el == "id"){
                                        new_node.id = data.id;
                                    }else if(el == "name"){
                                        new_node.name = c_unit_name;
                                    }else if(el == "code"){
                                        new_node.code = c_unit_code;
                                    }else if(el == "val"){
                                        new_node.val = c_unit_val;
                                    }else if(el == "serialnum"){
                                        new_node.serialnum = unit_serialnum;
                                    }else if(el == "remark"){
                                        new_node.remark = c_unit_remark;
                                    }else if(el == "pid"){
                                        new_node.pid = treeNode_.id;
                                    }else{
                                        new_node[el] = treeNode_[el];
                                    }
                                }

                                new_node.child = null;
                                new_node.isParent = null;
                                new_node.isOpen = true;
                                if(treeNode_.child == null || treeNode_.child == undefined){
                                    treeNode_.child = [];
                                }
                                treeNode_.child.push(new_node);
                                tree_nodes.tree.refresh();
                                tree_nodes.tree.selectNode(treeNode_);
                                //先增加子节点，再加载子节点下的数据
                                gridLoad(null,treeNode_);
                            }else if(result == "fail"){
//								alertui("添加失败");
                                flag = false;
                                $(".modal-body").html("添加失败");
                                $("#myModal").attr("style","display: block;z-index: 9999;");
                                $("#myModal").modal("show");
                            }else{
//								alertui("编码冲突");
                                flag = false;
                                $(".modal-body").html("编码冲突");
                                $("#myModal").attr("style","display: block;z-index: 9999;");
                                $("#myModal").modal("show");
                            }
                        },
                        error:function (data){
//							alertui("添加失败");
                            flag = false;
                            $(".modal-body").html("添加失败");
                            $("#myModal").attr("style","display: block;z-index: 9999;");
                            $("#myModal").modal("show");
                        }
                    });
                    if(flag){
                        $(this).close();
                    }
                }
            },
            {
                text: "取消",
                click: function (){
                    $(this).close();
                }
            }
        ],
        afterCreate:function(){
            $("#f_unit_name").html(click_name);//弹框上显示父节点名称

            var data_s = '[ ';
            data_s += "{id : '1',text :'有效'},";
            data_s += "{id : '0',text :'失效'},";
            data_s += ']';
            $("#unit_status").select2({
                placeholder : "----请选择状态----",
                allowClear : true,
                data : eval(data_s)
            });
        }
    });
}

/**
 * 修改
 */
function updateDictData(){
    var m_id = $(".success").attr("_id");
    var m_name = $(".success").attr("name");
    var m_code = $(".success").attr("code");
    var m_val = $(".success").attr("val");
    var m_status = $(".success").attr("status");
    var m_remark = $(".success").attr("remark");
    var m_serialnum = $(".success").attr("serialnum");

    if(m_id == "" || m_id == undefined || m_id == null){
//		alertui("请选择一条记录");
        $(".modal-body").html("请选择一条记录");
        $("#myModal").modal("show");
        return false;
    }
    $("#edit_dn").modal_n({
        title: "修改字典数据",
        width:"35%",
        resizable: true,
        buttons: [
            {
                text: "确定",
                click: function (){
                    var c_unit_name = $(".unit_name").val();
                    var c_unit_code = $(".unit_code").val();
                    var c_unit_val = $(".unit_val").val();
                    var unit_serialnum = $(".unit_serialnum").val();
                    var c_unit_status = $("#unit_status").val();
                    var c_unit_remark = $(".unit_remark").val();
                    c_unit_remark = remarkReplac(c_unit_remark, "1");
                    if(c_unit_name == null || c_unit_name == ""){
                        showErrorMsg("名称有误，请检查");
                        return false;
                    }
                    if(c_unit_name.length > 80){
                        showErrorMsg("名称太长");
                        return false;
                    }
                    if(c_unit_code == null || c_unit_code == ""){
                        showErrorMsg("编码不能为空");
                        return false;
                    }
                    if(c_unit_code.length > 50){
                        showErrorMsg("编码太长");
                        return false;
                    }
                    if(c_unit_val == null || c_unit_val == ""){
                        showErrorMsg("数值有误，请检查");
                        return false;
                    }
                    if(c_unit_status == null || c_unit_status == ""){
                        showErrorMsg("状态为空，请检查");
                        return false;
                    }

                    var flag = false;
                    $.ajax({
                        url : "updateDictData.do",
                        async : false,
                        dataType:"json",
                        type : "post",
                        data : {
                            id:m_id,
                            name:c_unit_name,
                            code:c_unit_code,
                            val:c_unit_val,
                            remark:c_unit_remark,
                            status:c_unit_status
                        },
                        success : function(data) {
                            var result = data.result;
                            if(result == "success"){
                                flag = true;
//								alertui("修改成功");
                                $(".modal-body").html("修改成功");
                                $("#myModal").modal("show");
                                gridLoad(null,treeNode_);

                                var treeNode_childs = treeNode_.child;
                                if(treeNode_.child != null && treeNode_.child != undefined && treeNode_.child.length > 0){
                                    for (var j = 0; j < treeNode_childs.length; j++) {
                                        var child_id = treeNode_childs[j].id;
                                        if(m_id == child_id){
                                            tree_oper = treeNode_childs[j];
                                        }
                                    }
                                }else{
                                    tree_oper = treeNode_;
                                }

                                tree_oper.name = c_unit_name;
                                tree_oper.code = c_unit_code;
                                tree_oper.val = c_unit_val;
                                tree_oper.serialnum = unit_serialnum;
                                tree_oper.remark = c_unit_remark;

                                tree_nodes.tree.refresh();
                                tree_nodes.tree.selectNode(treeNode_);
                            }else if(result == "fail"){
//								alertui("修改失败");
                                flag = false;
                                $(".modal-body").html("修改失败");
                                $("#myModal").attr("style","display: block;z-index: 9999;");
                                $("#myModal").modal("show");
                            }else{
//								alertui("编码冲突");
                                $(".modal-body").html("编码冲突");
                                $("#myModal").attr("style","display: block;z-index: 9999;");
                                $("#myModal").modal("show");
                            }
                        },
                        error:function (data){
//							alertui("修改失败");
                            flag = false;
                            $(".modal-body").html("修改失败");
                            $("#myModal").attr("style","display: block;z-index: 9999;");
                            $("#myModal").modal("show");
                        }
                    });
                    if(flag){
                        $(this).close();
                    }
                }
            },
            {
                text: "取消",
                click: function (){
                    $(this).close();
                }
            }
        ],
        afterCreate:function(){
//			$(".ui-dialog-buttonpane").find("button").css("background","#428BCA;");

            $(".unit_code").attr("readonly","readonly");
            $("#f_unit_name").html(click_name);//弹框上显示父节点名称

            $(".unit_name").val(m_name);
            $(".unit_code").val(m_code);
            $(".unit_val").val(m_val);
            $(".unit_serialnum").val(m_serialnum);
//			$(".unit_status").val(m_status);
            $(".unit_remark").val(m_remark);

            var data_s = '[ ';
            data_s += "{id : '1',text :'有效'},";
            data_s += "{id : '0',text :'失效'},";
            data_s += ']';
            $("#unit_status").select2({
                placeholder : "----请选择状态----",
                allowClear : true,
                data : eval(data_s)
            });

            $("#unit_status").val(m_status).trigger("change");

            if(m_id == CHAN_FAT){
                $(".unit_code").attr("readonly","readonly");

                var data_s1 = '[ ';
                data_s1 += "{id : '1',text :'有效'},";
                data_s1 += ']';
                $("#unit_status").select2({
                    placeholder : "----请选择状态----",
                    allowClear : true,
                    data : eval(data_s1)
                });
                $("#mes_title").html("注：渠道父节点编码和状态不能修改");
            }

            if(m_id == ZX_ID || m_id == DX_ID || m_id == KF_ID || m_id == HF_ID){
                $(".unit_val").attr("readonly","readonly");
                if(m_id == ZX_ID){
                    var data_s1 = '[ ';
                    data_s1 += "{id : '1',text :'有效'},";
                    data_s1 += ']';
                    $("#unit_status").select2({
                        placeholder : "----请选择状态----",
                        allowClear : true,
                        data : eval(data_s1)
                    });

                    $("#mes_title").html("注：中心渠道基础数据值和状态不能修改");
                }else{
                    $("#mes_title").html("注：渠道基础数据值不能修改");
                }
            }

        }
    });
}

/**
 * 删除
 */
function delDictData(){
    var m_id = $(".success").attr("_id");
    if(m_id == "" || m_id == undefined || m_id == null){
//		alertui("请选择一条记录");
        $(".modal-body").html("请选择一条记录");
        $("#myModal").modal("show");
        return false;
    }


    confirmui("是否删除？", function () {
        $.ajax({
            url : "delDictData.do",
            dataType : "json",
            async : false,
            type : "post",
            data : {
                id : m_id
            },
            success : function(data) {
                var result = data.result;
                if(result == "success"){
//					alertui("删除成功");
                    $(".modal-body").html("删除成功");
                    $("#myModal").modal("show");
                    var treeNode_childs = treeNode_.child;

                    if(treeNode_.child != null && treeNode_.child != undefined && treeNode_.child.length > 0){
                        for (var j = 0; j < treeNode_childs.length; j++) {
                            var child_id = treeNode_childs[j].id;
                            if(m_id == child_id){
                                tree_oper = treeNode_childs[j];
                            }
                        }
                    }else{
                        tree_oper = treeNode_;
                    }
                    tree_nodes.tree.removeNode(tree_oper);
                    gridLoad(null,treeNode_);
                }else if(result == "fail"){
//					alertui("删除失败");
                    $(".modal-body").html("删除失败");
                    $("#myModal").modal("show");
                }
            },
            error:function (data){
//				alertui("删除失败");
                $(".modal-body").html("删除失败");
                $("#myModal").modal("show");
            }
        });
    });
}

/**
 * 点击查询
 */
function findDictData(){
    var f_m_val = $("#m_val").val();
    $.ajax({
        url : "findDictData.do",
        dataType : "json",
        async : false,
        type : "post",
        data : {
            pid : click_id,
            name:f_m_val
        },
        success : function(data) {
            if(data.result == "success"){
                var context = "";
                var data = data.data;
                if(data != null){
                    for (var j = 0; j < data.length; j++) {
                        var array_element = data[j];
                        var id = array_element.id == null?"":array_element.id;
                        var name = array_element.name == null?"":array_element.name;
                        var code = array_element.code == null?"":array_element.code;
                        var val = array_element.val == null?"":array_element.val;
                        var status = array_element.status == null?"":array_element.status;
                        var remark = array_element.remark == null?"":array_element.remark;
                        var serialnum = j+1;

                        remark = remarkReplac(remark, val);

                        var name_ = name ;
                        var code_ = code;
                        var val_ = val;
                        var ramark_ = remark;
                        var status_ = status;
                        if(code.length > 20){
                            code = code.substring(0, 19) + "……";
                        }
                        if(val.length > 20){
                            val = val.substring(0, 19) + "……";
                        }
                        if(name.length > 16){
                            name = name.substring(0, 15) + "……";
                        }
                        if(remark.length > 12){
                            remark = remark.substring(0,11) + "……";
                        }
                        if(status == 1){
                            status = "有效";
                        }else{
                            status = "失效";
                        }
                        context += "<tr onclick='mousClick(this)' _id='"+id+"' name='"+name_+"' code='"+code_+"' val='"+val_+"' status='"+status_+"' remark='"+ramark_+"' serialnum='"+serialnum+"'>"+
                            "<td style='text-align: center;'>"+serialnum+"</td>"+
                            "<td style='text-align: center;' title='"+name_+"'>"+name+"</td>"+
                            "<td style='text-align: center;' title='"+code_+"'>"+code+"</td>"+
                            "<td style='text-align: center;' title='"+val_+"'>"+val+"</td>"+
                            "<td style='text-align: center;' title='"+ramark_+"'>"+remark+"</td>"+
                            "<td style='text-align: center;'>"+status+"</td>"+
                            "</tr>";
                    }
                    $("#context_body_manager").html(context);
                }
            }
        },
        error:function(data){
//			alertui("查询失败");
            $(".modal-body").html("查询失败");
            $("#myModal").modal("show");
        }
    });
}


/**
 * 清空全局变量
 * @param type 清除左侧选中的节点信息
 */
function clearVal(type){
    click_id = "";
    click_name = "";
    click_type = "";
    click_remark = "";
}


/**
 * 错误信息
 * @param text
 */
function showErrorMsg(text){
    $("#err_msg_li_cont").html(text);
    $("#err_msg_tr").show();
}

function alertui_(html) {
    $(".ui-dialog-titlebar").removeClass("ui-dialog-titlebar").addClass("alertui_sho_title_ui");
    $(".ui-draggable").removeClass("ui-draggable").addClass("alertui_sho_title_ui");


    if (!document.getElementById("message-basic-modal-content")) {
        $("body").append("<div id='message-basic-modal-content' style='display:none;overflow: visible;'></div>")
    }
    var showmodal = true;
    if ($(".ui-widget-overlay").get(0)) {
        showmodal = false;
    }
    var ops = $.extend(true, {
        modal: showmodal,
        resizable: false,
        width: "250",
        clear: true,
        title:"提示!",
        beforeClose: function () {
            $("#message-basic-modal-content").html("").hide();
            if (!isparent) {
                if (showmodal) {
                    crossdomain("closebgmodel", "");
                }
            }
        },
        buttons: [
            {
                text: "确定",
                click: function () {
                    $("#message-basic-modal-content").dialog("close")
                    if (!isparent) {
                        if (showmodal) {
                            crossdomain("closebgmodel", "");
                        }
                    }
                }
            }
        ]
    }, {});
    if (!isparent && showmodal) {
        crossdomain("showbgmodel", "");
    }
    $("#message-basic-modal-content").html("<div>"+html+"</div>");
    $("#message-basic-modal-content").dialog(ops);
    return false;
}



function clearSelected(){
    if(tree_nodes.tree.getSelectedNodes() != null && tree_nodes.tree.getSelectedNodes().length > 0){
        click_id = "";
        click_name = "";
        click_type = "";
        click_remark = "";
        tree_nodes.tree.refresh();
    }
}


function remarkReplac(remark, val){
    if(remark.indexOf("{") != -1 && remark.indexOf("}") != -1){
        var pattern =/{(.+?)}/g;
        var text=remark.match(pattern);
        var str = text.toString();
        //将对应的val替换到对应的remark中的'{1}'字符串处
        if(remark.indexOf(str) !== -1){
            remark = remark.replace(str, "{"+ val +"}");
        }
    }
    return remark;
}

