<!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>
        .user-search {width: 188px !important; display: inline;}
        .user-selected {border-left: 2px solid #009688 !important;}
    </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-xs12">
                    <div id="selectUsers" class="layui-btn-container selector-title-wrapper"></div>
                </div>
            </div>
            <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 class="selector-body-search">
                            <input type="text" id="searchUser" class="layui-input user-search" placeholder="快捷检索当前列表"/>
                            <div class="layui-btn-group">
                                <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" lay-click-select-all-user>全选</button>
                                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" lay-click-clear-all-user>清空</button>
                            </div>
                        </div>
                        <div id="users" class="selector-body-content list-group">
                            <div id="userWrapper"></div>
                        </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>
                        <button type="button" class="layui-btn layui-btn-primary close">关闭</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', 'flow', 'ztree', 'common'], function() {
        var $ = layui.$;
        var $win = $(window);
        var common = layui.common;
        var flow = layui.flow;
        var selectedUserIds = top.dialog.dialogData.selectedUserIds;
        var selectDepartmentUserOldArray = [];
        var selectDepartmentUserArray = [];
        var selectedParentId = 0;
        var searchTimeout;
        top.dialog.dialogData.selectedDepartmentUsers = [];

        function closeBox() {
            top.dialog.closeBox();
        }
        function initFrame() {
            var height = $win.height() - 160;
            $('.selector-tree-wrapper').css({
                height: height +'px',
                border: '1px dotted silver'
            });
            $('.selector-body-wrapper').css({
                height: (height - 10) +'px',
                border: '1px dotted silver'
            });
            $('.selector-body-content').css({
                height: ($('.selector-body-wrapper').height() - 30) +'px'
            });
        }
        // 初始化树
        function initThree() {
            var setting = {
                async: {
                    enable: true,
                    autoLoad: false,
                    type: 'get',
                    url: top.restAjax.path('api/department/listztreedepartment', []),
                    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: {
                    onClick: function(event, treeId, treeNode) {
                        parentId = treeNode.id;
                        $('#searchUser').val('');
                        initUsers(treeNode.id);
                        return false;
                    }
                },
                view: {
                    fontCss: {'color': 'black'}
                }
            };
            var zTree = $.fn.zTree.init($('#leftTree'), setting);
            zTree.addNodes(null, {id: '0', pId: '-1', name: '未划分人员', url: 'javascript:void(0);', isParent: 'true'});
            common.refreshTree('leftTree');
        }
        // 添加人员dom
        function addUserDom(data) {
            var userDom = '';
            for(var i = 0, item; item = data[i++];) {
                var avatarDom;
                if(null == item.userAvatar || '' == item.userAvatar) {
                    avatarDom = '<img class="user-avatar" src="assets/images/profile-photo.jpg"/> '
                } else {
                    avatarDom = '<img class="user-avatar" src="route/file/downloadfile/false/'+ item.userAvatar +'"/> ';
                }
                userDom += '<a id="user_'+ item.userId +'" href="javascript:void(0);" class="users list-group-item '+ (isUserSelected(item.userId) ? 'user-selected' : '') +'" lay-click-user data-userid="'+ item.userId +'" data-username="'+ item.userName +'" data-user-username="'+ item.userUsername +'">'+ avatarDom + item.userName +' ['+ item.userUsername +']</a>';
            }
            $('#userWrapper').append(userDom);
        }
        function addSearchUserDom(data) {
            if(data.length < 1) {
                return;
            }
            var users = $('.users');
            for(var i = 0; i < data.length; i++) {
                var user = data[i];
                for(var j = 0, userItem; userItem = users[j++];) {
                    if(user.userId === userItem.dataset.userid) {
                        data.splice(i, 1);
                        i--;
                        break;
                    }
                }
            }
            var userDom = '';
            for(var i = 0, item; item = data[i++];) {
                var avatarDom;
                if(null == item.userAvatar || '' == item.userAvatar) {
                    avatarDom = '<img class="user-avatar" src="assets/images/profile-photo.jpg"/> '
                } else {
                    avatarDom = '<img class="user-avatar" src="route/file/downloadfile/false/'+ item.userAvatar +'"/> ';
                }
                userDom += '<a id="user_'+ item.userId +'" href="javascript:void(0);" class="users search-users list-group-item '+ (isUserSelected(item.userId) ? 'user-selected' : '') +'" lay-click-user data-userid="'+ item.userId +'" data-username="'+ item.userName +'" data-user-username="'+ item.userUsername +'">'+ avatarDom + item.userName +' ['+ item.userUsername +']</a>';
            }
            $('#userWrapper').append(userDom);
        }
        // 初始化懒加载
        function initUserFlowLoad() {
            flow.load({
                elem: '#users',
                scrollElem: '#users',
                isAuto: false,
                done: function(page, next) {
                    var loadLayerIndex;
                    top.restAjax.get(top.restAjax.path('api/user/listpageselectdepartmentuser/{parentId}', [selectedParentId]), {
                        page: page,
                        rows: 20
                    }, null, function(code, data) {
                        next(addUserDom(data.rows), page < (parseInt(data.total / 20) + 1));
                    }, 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);
                    });
                }
            });
        }
        function listSearchUser(searchUser) {
            if(!searchUser) {
                return;
            }
            var loadLayerIndex;
            top.restAjax.get(top.restAjax.path('api/user/listselectdepartmentuser/{parentId}', [selectedParentId]), {
                keywords: searchUser
            }, null, function(code, data) {
                addSearchUserDom(data);
            }, 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);
            });
        }
        // 初始化人员列表
        function initUsers(parentId) {
            selectedParentId = parentId;
            $('#userWrapper').empty();
            $('.layui-flow-more').remove();
            initUserFlowLoad();
        }
        // 初始化选择的人员
        function initSelectedUsers(callback) {
            if(typeof(selectedUserIds) != 'undefined' && selectedUserIds != null && selectedUserIds != '') {
                var loadLayerIndex;
                top.restAjax.post(top.restAjax.path('api/user/listuserbyids', []), {
                    selectedUserIds: selectedUserIds
                }, null, function(code, data) {
                    for(var i = 0, item; item = data[i++]; ) {
                        selectUser(item.userId, item.userName, item.userUsername);
                        selectDepartmentUserOldArray.push({
                            userId: item.userId,
                            userUsername: item.userUsername,
                            userName: item.userName
                        });
                    }
                    callback();
                }, 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);
                });
            } else {
                callback();
            }
        }
        initFrame();
        initThree();
        initSelectedUsers(function() {
            initUsers(0);
        });
        $('#searchUser').on('keyup', function() {
            var value = $(this).val();
            if(value) {
                $('.layui-flow-more').hide();
            } else {
                $('.layui-flow-more').show();
            }
            $('.users').hide().filter(":contains('" + value + "')").show();
            $('.search-users').remove();
            if(searchTimeout) {
                clearTimeout(searchTimeout);
            }
            searchTimeout = setTimeout(function() {
                listSearchUser(value);
            }, 1000);
        });
        // 人员是否已经选择
        function isUserSelected(userId) {
            var isSelected = false;
            for(var i = 0, item; item = selectDepartmentUserArray[i]; i++) {
                if(item.userId == userId) {
                    isSelected = true;
                    break;
                }
            }
            return isSelected;
        }
        // 删除已经选择的人员
        function removeSelectedUser(userId) {
            for(var i = 0, item; item = selectDepartmentUserArray[i]; i++) {
                if(item.userId == userId) {
                    selectDepartmentUserArray.splice(i, 1);
                    var selectedUserDom = $('#selected_user_'+ userId);
                    selectedUserDom.focus();
                    selectedUserDom.remove();
                    $('#user_'+ userId).removeClass('user-selected');
                    break;
                }
            }
        }
        // 选择人员
        function selectUser(userId, userName, userUsername, isOnlySelect) {
            if(!isUserSelected(userId)) {
                $('#user_'+ userId).addClass('user-selected');
                selectDepartmentUserArray.push({
                    userId: userId,
                    userUsername: userUsername,
                    userName: userName
                });
                $('#selectUsers').append('<a id="selected_user_'+ userId +'" href="javascript:void(0);" class="layui-btn layui-btn-xs">'+ userName +' <i class="fa fa-close" lay-click-removeuser data-userid="'+ userId +'"></i></a>');
                $('#selected_user_'+ userId).focus();
            } else {
                if(!isOnlySelect) {
                    removeSelectedUser(userId);
                }
            }
        }
        $(document.body).on('click', '*[lay-click-user]', null, function() {
            var data = this.dataset;
            selectUser(data.userid, data.username, data.userUsername);
        });
        $(document.body).on('click', '*[lay-click-removeuser]', null, function() {
            var data = this.dataset;
            removeSelectedUser(data.userid);
        });
        $(document.body).on('click', '*[lay-click-select-all-user]', null, function() {
            $('#userWrapper').children().each(function() {
                var data = this.dataset;
                selectUser(data.userid, data.username, data.userUsername, true);
            });
        });
        $(document.body).on('click', '*[lay-click-clear-all-user]', null, function() {
            $('#userWrapper').children().each(function() {
                var data = this.dataset;
                removeSelectedUser(data.userid);
            });
        });
        $('.close').on('click', function() {
            // 关闭按钮返回之前的数据
            top.dialog.dialogData.selectedDepartmentUsers = selectDepartmentUserOldArray;
            top.dialog.dialogData.selectedUserIds = null;
            closeBox();
        });
        $('.confirm').on('click', function() {
            top.dialog.dialogData.selectedDepartmentUsers = selectDepartmentUserArray;
            top.dialog.dialogData.selectedUserIds = null;
            closeBox();
        });
    });
</script>
</body>
</html>