
 var zdata = [];
 var z_cache ;
 var check_item_tree = null;
 var edittype = "add";
 var cols = [{
     width: 10,
     text: '序号',
     type: 'number',
     flex: false,
     colClass: 'text-center'
 }, {
     width: 160,
     text: '名称',
     type: 'string',
     flex: false,
     sort: 'down',
     colClass: 'text-center'
 }, {
     width: 40,
     text: '分数',
     type: 'string',
     flex: false,
     colClass: 'text-center'
 }, {
     width: 60,
     text: '操作',
     type: 'string',
     flex: false,
     colClass: 'text-center'
 }];
 $(document).ready(function() {

    //  $("#main_content_title").html("考核项管理")

     $('#dashboard').dashboard({ draggable: false });
     var zTreeObj;
     var zNodes = [];
     check_item_tree = $.fn.zTree.init($("#check_rule_tree"), {}, zNodes);

     getCheckItems();

     $("#dept_add").on("click", function() {
         var nodedata = check_item_tree.getSelectedNodes();
         edittype = "add"
         loadData(nodedata);
         $("#add_btn").html("添加");
         $('#addModal').modal('show');
         $(".check_item_score").hide();
     })

     $("#dept_edit").on("click", function() {
         //获取选中的节点
         var nodedata = check_item_tree.getSelectedNodes();
         if (nodedata.length < 1) {
             layer.msg('请先选考核项！', {
                 time: 2000, //20s后自动关闭
             });
             return;
         }
         edittype = "edit"
         loadData(nodedata)
         $("#add_btn").html("修改");
         $('#addModal').modal('show');
         $(".check_item_score").hide();
     });

     $("#dept_delete").on("click", function() {
         var nodedata = check_item_tree.getSelectedNodes();
         if (nodedata.length < 1) {
             layer.msg('请选择考核项！', {
                 time: 2000, //20s后自动关闭
             });
             return;
         }

        deleteItem4Common(nodedata[0].id,"/checkItem/delete",function(){
            layer.msg('删除成功！', {
                    time: 2000, //20s后自动关闭
                });   
            getCheckItems();
            table_init();
        }, function(error){ })
     });

     // 增加考核项
     $("#add_check_item").click(function(){
         var nodedata = check_item_tree.getSelectedNodes();
         edittype = "add"
         $("#add_btn").data("tree_flag",1);
         loadData(nodedata);
         $("#add_btn").html("添加");
         $('#addModal').modal('show');
         $(".check_item_score").show();
         $("#add_btn").data("tree_flag",0);
     })

     $('.datatable').datatable({
         checkable: false,
         sortable: false,
         data: {
             cols: cols,
             rows: []
         }
     });
 });

function table_init(){
    $('.datatable').datatable('load', {
        cols: cols,
        rows: []
    });
}

// 表格点击修改
function modify_check_item( id ){
   post_common_service("/checkItem/getById", {"id":id }, function(data){
        $(".check_item_group").hide();
        $("#check_item_name").val(data.name);
        $("#check_item_score").val(data.score);
        $('#addModal').modal('show');
        $("#add_btn").attr("onclick","addCheckItem_v("+data.id+")");
        $("#add_btn").html("修改");
    }, function(error){ })
}

function addCheckItem_v(id){
    var name = $("#check_item_name").val();
    var score = $("#check_item_score").val();
    var data = {
        "id":id ,
        "name":name,
        "score":score 
    }
    post_common_service( "checkItem/update",data,function(data){
        layer.msg('修改成功！', {
            time: 2000, //20s后自动关闭
        }, function() {
            $('#addModal').modal('hide');
             $("#add_btn").attr("onclick","addCheckItem()");
            getCheckItems();
            table_init();
        })
    },function(error){})

}

// 表格点击删除
function delete_check_item(id ){
     deleteItem4Common(id,"/checkItem/delete",function(){
         layer.msg('删除成功！', {
                time: 2000, //20s后自动关闭
            });   
        getCheckItems();
        table_init();
    }, function(error){ })
} 

 function getCheckItems() {
     function zTreeOnRename(event, treeId, treeNode, isCancel) {
         alert(treeNode.tId + ", " + treeNode.name);
     }

     function zTreeOnRemove(event, treeId, treeNode) {
         alert(treeNode.tId + ", " + treeNode.name);
     }


     function getTreeData(c_obj,id){
        if(c_obj.id == id){
            return c_obj ;
        }else{
            if(c_obj.subCheckItem!=null){
                for(var i=0;i<c_obj.subCheckItem.length;i++){
                    var tmp = getTreeData(c_obj.subCheckItem[i],id);
                    if(tmp != null){
                        return tmp ;
                    }
                }
            }
            return null;
        }
     }

     var seq = 0 ;

     function getTree(obj,rowObj){
        var userdata = {};
        userdata["checked"] = false;
        if(obj.score != null){
            userdata["data"] = [++seq, obj.name, (obj.score!=null?obj.score:""), '<a href="javascript:void(0)" onclick="modify_check_item('+ obj.id +')"  ><i class="icon icon-edit"></i> 修改</a><a href="javascript:void(0)" onclick="delete_check_item('+ obj.id +')" ><i class="icon icon-remove-circle"></i> 删除</a>'];
            rowObj.push(userdata);
        }

        if(obj.subCheckItem!=null){
            for(var i=0; i<obj.subCheckItem.length;i++ ){
                getTree(obj.subCheckItem[i],rowObj);
            }
        }
        return rowObj;
     }

     function zTreeOnClick(event, treeId, treeNode) {

        var rowdata = [];

        seq = 0 ;

        for(var i=0;i<z_cache.length;i++){
            var treeObj = getTreeData(z_cache[i],treeNode.id) ;
            if( treeObj != null){
               rowdata = getTree(treeObj,rowdata);
               break ;
            }
        }

        // 使用data参数更新数据：
        $('.datatable').datatable('load', {
            cols: cols,
            rows: rowdata
        });
     };

     var setting = {
         data: {
             simpleData: {
                 enable: true,
                 idKey: "id",
                 pIdKey: "pId",
                 rootPId: null
             }
         },
         view: { //表示tree的显示状态
             selectMulti: false //表示禁止多选
         },
         check: { //表示tree的节点在点击时的相关设置
             enable: false, //是否显示radio/checkbox
             chkStyle: "checkbox", //值为checkbox或者radio表示
             checkboxType: { p: "", s: "" }, //表示父子节点的联动效果
             radioType: "level" //设置tree的分组
         },
         callback: {
             onRename: zTreeOnRename,
             //  beforeDrop: zTreeBeforeDrop,
             onRemove: zTreeOnRemove,
             onClick: zTreeOnClick
         },
         edit: {
             enable: true,
             drag: {
                 autoExpandTrigger: true,
                 isMove: true,
                 prev: false,
                 next: true,
                 inner: true,
                 autoOpenTime: 0
             },
             showRenameBtn: false,
             showRemoveBtn: false
         }
     };

     post_common_service("/checkItem/getAll","",function(data){
        zdata = [];
        z_cache = data ;
         for (var i = 0; i < data.length; i++) {
             var m = data[i];
             var zdataItem = {};
             zdataItem["id"] = m.id;
             zdataItem["value"] = m.id;
             zdataItem["pId"] = null;
             zdataItem["score"] = m.score ;
             zdataItem["name"] = m.name;
             zdataItem["open"] = true;
             zdataItem["children"] = addobj(m);
              zdataItem.open = true ;
             zdata.push(zdataItem);
         }
         check_item_tree = $.fn.zTree.init($("#check_rule_tree"), setting, zdata)
     },function(error){})
 }

 function addobj(data) {
     var zdata = [];
     if (typeof(data.subCheckItem) != "undefinde" && data.subCheckItem != null &&
         data.subCheckItem.length > 0) {
         for (var i = 0; i < data.subCheckItem.length; i++) {
             var m = data.subCheckItem[i];
             var zdataItem = {};
             if(m.score != null){
                 continue;
             }
             zdataItem["id"] = m.id;
             zdataItem["value"] = m.id;
             zdataItem["pId"] = data.id;
             zdataItem["score"] = m.score ;
             zdataItem["icon"] = "";
             zdataItem["name"] = m.name;
             zdataItem["open"] = true;
             zdataItem["children"] = addobj(m);
             zdataItem.open = true ;
             zdata.push(zdataItem);
         }
         return zdata;
     } else {
         return [];
     }
 }

// 增加和编辑框
var dept_selectinput;
var selectednodetemp;

function loadData(nodedata) {
    var pnode = nodedata;

    if (edittype == "add") {
        $("#check_item_name").val("") ;
        $("#check_item_score").val("")
    }
    if (edittype == "edit") {
        selectednodetemp = nodedata[0];
        $("#check_item_name").val(nodedata[0].name);
        $("#check_item_score").val(nodedata[0].score);
        $("#add_btn").html("保存")
        if (pnode != null && pnode.length > 0) {
            pnode = [check_item_tree.getNodeByParam("id", pnode[0].pId, null)]
        }
    }
    $(".check_item_group").show();

    if(pnode[0] != null){
        dept_selectinput = new TreeSelect({
            element: '#check_item_select',
            data: zdata,
            valueKey: "id",
            placeholder: "选择考核项分类",
            selectvalue: pnode.length > 0 ? pnode[0].id : null
        });
    }else{
        if($("#add_btn").data("tree_flag")==1){
            dept_selectinput = new TreeSelect({
                element: '#check_item_select',
                data: zdata,
                valueKey: "id",
                placeholder: "选择考核项分类"
            });
            $(".check_item_group").show();
        }else{
            $(".check_item_group").hide();
        }
    }
}



function addCheckItem() {
    //获取名称
    var name = $("#check_item_name").val();
    var score = $("#check_item_score").val();

    var pid =   dept_selectinput!=null?dept_selectinput.value:null ;

    if($(".check_item_group").is(":hidden")){
        pid = null ;   
    }

    if(name == ""){
        tip("请填写考核项名称");
        return ;
    }

    if(!$(".check_item_score").is(":hidden")){
        if(pid==null){
            tip("请选择考核项分类");
            return ;
        }
        if(score == ''){
            tip("请选择考核项的分数");
            return ;
        }
    }


    var data = {
        "name": name,
        "score":score,
        "parent_id": pid
    }

    if (edittype == "add") {
        post_common_service( "checkItem/add",data,function(data){
            layer.msg('添加成功！', {
                time: 2000, //20s后自动关闭
            }, function() {
                $('#addModal').modal('hide')
                getCheckItems();
                table_init();
            })
        },function(error){})
    }

    if (edittype == "edit") {
        data["id"] = selectednodetemp.id;
        if (isSelfOrChild(pid, selectednodetemp)) {
            layer.msg('不能添加到自身及自身下的子考核项！', {
                time: 2000, //20s后自动关闭
            })
            return;
        }

         post_common_service( "checkItem/update",data,function(data){
            layer.msg('修改成功！', {
                time: 2000, //20s后自动关闭
            }, function() {
                $('#addModal').modal('hide')
                getCheckItems();
                table_init();
            })
        },function(error){})
    }
}

function isSelfOrChild(id, node) {
    if (id == node.id) return true;
    if (typeof(node.children) == "undefinde" || node.children == null || node.children.length < 1) return false;
    for (var i = 0; i < node.children.length; i++) {
        if (isSelfOrChild(id, node.children[i])) {
            return true;
        }
    }
    return false;
}