<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <base th:href="${#request.getContextPath() + '/'} ">
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="assets/fonts/font-awesome/css/font-awesome.css"/>
    <link rel="stylesheet" type="text/css" href="assets/js/vendor/zTree3/css/metroStyle/metroStyle.css"/>
    <link rel="stylesheet" href="assets/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="assets/layuiadmin/style/admin.css" media="all">
    <style>.remove-selected-user {color: #FFF;}</style>
</head>
<body>
<div class="layui-fluid layui-anim layui-anim-fadein" style="padding: 0;">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 0px;">
            <div class="layui-row">
                <div class="layui-col-xs5">
                    <div class="selector-tree-wrapper">
                        <ul id="leftTree" class="ztree"></ul>
                    </div>
                </div>
                <div class="layui-col-xs7">
                    <div class="selector-body-wrapper">
                        <div id="selectUsers" class="selector-body-content-user layui-btn-container"></div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-layout-admin">
                <div class="layui-input-block">
                    <div class="layui-footer" style="left: 0;">
                        <button type="button" class="layui-btn confirm">确认</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="assets/layuiadmin/layui/layui.js"></script>
<script>
    layui.config({
        base: 'assets/layuiadmin/'
    }).extend({
        index: 'lib/index'
    }).use(['index', 'ztree', 'common'], function() {
        var $ = layui.$;
        var $win = $(window);
        var common = layui.common;
        var selectedUsers = top.dialog.dialogData.selectedUsers;

        var selectDepartmentUserArray = [];

        top.dialog.dialogData.selectedDepartmentUsers = [];

        function closeBox() {
            top.dialog.dialogData.selectedUsers = null;
            top.dialog.closeBox();
        }
        // 初始化框架
        function initFrame() {
            var height = $win.height() - 80;
            $('.selector-tree-wrapper').css({
                marginTop: '5px',
                height: height +'px',
                border: '1px dotted silver'
            });
            $('.selector-body-wrapper').css({
                marginTop: '5px',
                height: (height - 10) +'px',
                border: '1px dotted silver'
            });
        }
        // 节点是否已经选择
        function isNodeChecked(userId, departmentId) {
            for(var i = 0, item; item = selectDepartmentUserArray[i++];) {
                if(departmentId == item.departmentId && userId == item.userId) {
                    return true;
                }
            }
            return false;
        }
        // 选择人员
        function addSelectDepartmentUserArray(id, name, title, departmentId) {
            selectDepartmentUserArray.push({
                userId: id,
                userName: name,
                userTitle: title,
                departmentId: departmentId,
            });
            $('#selectUsers').append('<span id="selected_user_'+ id +'" class="layui-btn layui-btn-xs">'+ title +' <a href="javascript:void(0);" class="remove-selected-user" data-userid="'+ id +'" data-departmentid="'+ departmentId +'"><i class="fa fa-times"></i></a></span>');
        }
        // 删除人员
        function removeSelectDepartmentUserArray(userId, departmentId) {
            for(var i = 0, item; item = selectDepartmentUserArray[i++];) {
                if(departmentId == item.departmentId && userId == item.userId) {
                    selectDepartmentUserArray.splice(--i, 1);
                    $('#selected_user_'+ userId).remove();
                    break;
                }
            }
        }
        // 初始化数据
        var initTimeout = null;
        var isInit = false;
        function initSelectNode(zTree) {
            var nodes = zTree.transformToArray(zTree.getNodes());
            for(var i = 0, node = nodes[i]; node = nodes[i++];) {
                for(var j = 0; item = selectDepartmentUserArray[j++]; ) {
                    if(node.id == ('u_'+ item.userId) && node.pId == item.departmentId) {
                        zTree.checkNode(node, true, true);
                        break;
                    }
                }
            }
            top.dialog.dialogData.selectedDepartmentUsers = selectDepartmentUserArray;
        }
        function initCheckData(zTree) {
            if(selectedUsers) {
                if(selectedUsers.length == 0) {
                    return;
                }
                if(!isInit) {
                    var loadLayerIndex;
                    top.restAjax.post(top.restAjax.path('api/user/listdepartmentuserbyuserdepartmentid', []), {
                        selectedUsers: selectedUsers
                    }, null, function(code, data) {
                        for(var i = 0, item; item = data[i++];) {
                            var id = item.userId;
                            var userName = item.userName;
                            var userTitle = ('【'+ item.departmentName +'】'+ item.userName);
                            var departmentId = item.departmentId;
                            addSelectDepartmentUserArray(id, userName, userTitle, departmentId);
                            top.dialog.dialogData.selectedDepartmentUsers.push({
                                userId: id,
                                userName: userName,
                                userTitle: userTitle,
                                departmentId: departmentId,
                            });
                        }
                        initSelectNode(zTree);
                    }, function(code, data) {
                        top.dialog.msg(data.msg);
                    }, function() {
                        loadLayerIndex = top.dialog.msg(top.dataMessage.loading, {icon: 16, time: 0, shade: 0.3});
                    }, function() {
                        top.dialog.close(loadLayerIndex);
                    });
                    isInit = true;
                } else {
                    initSelectNode(zTree);
                }
            }
        }
        // 初始化树
        function initThree() {
            var setting = {
                check: {
                    enable: true
                },
                async: {
                    enable: true,
                    autoLoad: true,
                    type: 'get',
                    url: top.restAjax.path('api/department/listztreedepartmentwithuser', []),
                    autoParam:['id'],
                    otherParam:{},
                    dataFilter: function(treeId, parentNode, childNodes) {
                        if (!childNodes) return null;
                        for (var i=0, l=childNodes.length; i<l; i++) {
                            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
                        }
                        return childNodes;
                    }
                },
                callback: {
                    onCheck: function(event, treeId, treeNode) {
                        var checkedNodes = zTree.getCheckedNodes(true);
                        var unCheckNodes = zTree.getCheckedNodes(false);
                        selectUser(checkedNodes, unCheckNodes);
                        return false;
                    },
                    onAsyncSuccess: function(event, treeId, treeNode) {
                        initCheckData(zTree);
                    }
                },
                view: {
                    fontCss: {'color': 'black'}
                }
            };
            var zTree = $.fn.zTree.init($('#leftTree'), setting);
        }
        initFrame();
        initThree();
        // 选择人员
        function selectUser(checkedNodes, unCheckNodes) {
            // 清空未选中的列表
            for(var i = 0, item; item = unCheckNodes[i++];) {
                if(item.title) {
                    removeSelectDepartmentUserArray(item.id.substring(2, item.id.length), item.pId);
                }
            }
            for(var i = 0, item; item = checkedNodes[i++];) {
                if(item.title) {
                    var userId = item.id.substring(2, item.id.length);
                    if(!isNodeChecked(userId, item.pId)) {
                        addSelectDepartmentUserArray(userId, item.name, item.title, item.pId);
                    }
                }
            }
        }
        $(document).on('click', '.remove-selected-user', function() {
            var zTree = $.fn.zTree.getZTreeObj('leftTree');
            removeSelectDepartmentUserArray(this.dataset.userid, this.dataset.departmentid);
            // 删除选中状态
            var node = zTree.getNodeByParam('id', 'u_'+ this.dataset.userid, null);
            if(node) {
                zTree.checkNode(node, false, true);
            }
        });
        $('.confirm').on('click', function() {
            top.dialog.dialogData.selectedDepartmentUsers = selectDepartmentUserArray;
            closeBox();
        });
        $('.close').on('click', function() {
            closeBox();
        })
    });
</script>
</body>
</html>