var dept_selectinput;
var selectednodetemp;

function loadData(nodedata) {
    var pnode = nodedata;
    
    if (edittype == "add") {
        $("#dept_name").val("")
        $('#addModal .modal-title').html('添加部门');
    }
    if (edittype == "edit") {
        selectednodetemp = nodedata[0];
        $("#dept_name").val(nodedata[0].name)
        $("#dept_add_btn").html("保存")
        $('#addModal .modal-title').html('修改部门');
        if (pnode != null && pnode[0].pId && pnode.length > 0) {
            pnode = [dept_tree.getNodeByParam("id", pnode[0].pId, null)]
        }
    }

    dept_selectinput = new TreeSelect({
        element: '#dept_select',
        data: zdata,
        valueKey: "id",
        placeholder: "选择部门",
        selectvalue: pnode.length > 0 ? pnode[0].id : null
    });
}


function addDept() {
    //获取名称
    var name = $("#dept_name").val();
    var pid = dept_selectinput.value;
    var data = {
        "organname": name,
        "parentid": pid
    }

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

        })
    }

    if (edittype == "edit") {
        data["id"] = selectednodetemp.id;
        if (isSelfOrChild(pid, selectednodetemp)) {
            layer.msg('不能添加到自身及自身下的子部门！', {
                time: 2000, //20s后自动关闭
            })
            return;
        }
        DeptEdit(data, function(datare) {
            layer.msg('修改成功！', {
                time: 2000, //20s后自动关闭
            }, function() {
                $('#addModal').modal('hide')
                getDept();
            })
        }, 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;
}