$(document).ready(function() {
    tree();
})

$(".inps").focus(function () {
    $(".xlAdd").css("display", "block");
});
$(".xl").click(function () {
    if ($(".xlAdd").css("display") == "block") {
        $(".xlAdd").css("display", "none");
    } else {
        $(".xlAdd").css("display", "block");
    }
});
$(".addTree").mouseleave(function () {
    $(this).css("display", "none");
});
//清除
$(".Cleans ").click(function () {
    $(".inps").val("");
    $("#PID").val("");
});

function tree() {
    $.get(
        huayi.config.callcenter_url + "Department/GetDeptList",
        {
            token: $.cookie("token"),
            //		"pid": pid
        },
        function (result) {
            result = $.parseJSON(result);
            $.fn.zTree.init($("#addTreeDemo"), setting1, result.data); //实例化树形图
        }
    );
}
var setting1 = {
    data: {
        key: {
            name: "F_DeptName",
        },
        simpleData: {
            enable: true,
            idKey: "F_DeptId",
            pIdKey: "F_PartentId",
            rootPId: 0,
        },
    },
    callback: {
        onClick: zTreeOnClick,
    },
};

function zTreeOnClick(event, treeId, treeNode) {
    if (treeNode.level >= 1) {
        $(".inps").val(treeNode.F_DeptName);
        $("#PID").val(treeNode.F_DeptId);
        $(".Cleans").show();
    }
}

function Close() {
    $(".lyxz").removeClass("cx");
    if ($("audio").length > 0) {
        $("audio")[0].pause();
    }
}

$("#sponsor").on("click", "li", function () {
    $(".selDpart1").css("display", "none");
    $(".inps").val($(this).html());
    $("#PID").val($(this).attr("index"));
    $(".Cleans").show();
});

$(".inps").bind("input propertychange", function() {
    $(".xlAdd").css("display", "none");
    $(".selDpart1").css("display", "block");
    if ($(".inps").val() == "") {
        $(".selDpart1").css("display", "none");
        return
    }
    var debounceDepart = debounce(depart, 500);
    debounceDepart($(".inps").val());
})

///部门
function depart(dept) {
    $("#sponsor").empty();
    $.getJSON(
        huayi.config.callcenter_url + "Department/GetDeptListByDept",
        {
            token: $.cookie("token"),
            dept: dept,
        },
        function (data) {
            if (data.state.toLowerCase() == "success") {
                var content = data.data;
                $(content).each(function (i, n) {
                    $(
                        "<li index='" +
                            n.F_DeptId +
                            "'>" +
                            n.F_DeptName +
                            "</li>"
                    ).appendTo("#sponsor");
                });
            }
        }
    );
}

function debounce (fun, delay) {
    return function(args) {
        var _args = args;
        var that = this;
        clearTimeout(fun.id);
        fun.id = setTimeout(function() {
            fun.call(that, _args);
        }, delay)
    }
}