var zdata = [];
var z_cache;
var all_data = [];
var check_rule_id;
var check_item_tree = null;

var check_rule_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() {
    addBreadMenu("/view/assess_management/assess_way_edit.html", "考核项");
    //  $("#main_content_title").html("<span><a href='#'>考核项管理</a></span><span> / </span><span>考核项</span>");

    $('#dashboard').dashboard({ draggable: false });
    var zTreeObj;
    var zNodes = [];
    check_item_tree = $.fn.zTree.init($("#department_tree"), {}, zNodes);
    check_rule_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')
    })

    $("#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');
    });

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

        if (nodedata[0].children.length > 0) {
            layer.msg('请删除具体考核项！', {
                time: 2000, //20s后自动关闭
            });
            return;
        }

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

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


function delete4CheckRuleItem(param, url, okCb) {
    //询问框
    layer.confirm('确定删除记录？', {
        btn: ['删除', '取消'] //按钮
    }, function() {
        no_return_common_service(url, param, function(data) {
            okCb(); //重新加载表格数据
            layer.msg(data, {
                time: 2000 //20s后自动关闭
            });
        }, function(error) {
            // alert(error);
        });
    }, function(index) {
        layer.close(index);
    });
}

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) {
    delete4CheckRuleItem({ "rule_id": check_rule_id, "id": 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="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
        }
    };

    $("#check_rule_item_name").html($.zui.store.get("check_rule_name"));

    check_rule_id = $.zui.store.get("check_rule_id");

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

    // 查询所有的考核项
    post_common_service("/checkItem/getAll", "", function(data) {
        all_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["children"] = addobj(m);
            zdataItem.open = true;
            all_data.push(zdataItem);
        }
        check_rule_tree = $.fn.zTree.init($("#check_rule_tree"), setting2, all_data)
    }, 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["children"] = addobj(m);
            zdataItem.open = false;
            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("")
    }

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


function addCheckItem() {
    //获取名称 所有已经勾选的
    var nodedata = check_rule_tree.getCheckedNodes();
    var datas = [];
    for (var i = 0; i < nodedata.length; i++) {
        if (nodedata[i].children.length > 0) {
            continue;
        }
        datas.push({ "rule_id": check_rule_id, "id": nodedata[i].id });
    }

    if (edittype == "add") {
        post_common_service("checkRuleItem/add/list", datas, 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;
}


var setting2 = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: null
        }
    },
    view: { //表示tree的显示状态
        selectMulti: false //表示禁止多选
    },
    check: { //表示tree的节点在点击时的相关设置
        enable: true, //是否显示radio/checkbox
        chkStyle: "checkbox", //值为checkbox或者radio表示
        checkboxType: { p: "", s: "" }, //表示父子节点的联动效果
        radioType: "level" //设置tree的分组
    },
    callback: {

    },
    edit: {
        enable: true,
        drag: {
            autoExpandTrigger: true,
            isMove: true,
            prev: false,
            next: true,
            inner: true,
            autoOpenTime: 0
        },
        showRenameBtn: false,
        showRemoveBtn: false
    }
};