<!DOCTYPE html>
<html 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" href="assets/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="assets/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="assets/js/vendor/zTree3/css/metroStyle/metroStyle.css"/>
    <link rel="stylesheet" href="assets/layuiadmin/style/common.css" media="all">
    <style>
        .card-body-left {border-right: 1px dotted silver;}
        .card-body-right {padding: 5px;}
    </style>
</head>
<body>
<div class="layui-anim layui-anim-fadein">
    <div class="layui-row" style="padding-right: 0px;">
        <div class="layui-card">
            <div class="layui-card-body left-tree-wrap">
                <div id="treeBox" class="layui-col-xs6 card-body-left">
                    <ul id="tree" class="ztree"></ul>
                </div>
                <div id="checkedNodeBox" class="layui-col-xs6 card-body-right layui-btn-container"></div>
            </div>
            <div class="layui-form-item layui-layout-admin">
                <div class="layui-input-block">
                    <div class="layui-footer" style="padding: 0px;">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-sm submit">确定</button>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary close">返回</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="assets/layuiadmin/layui/layui.js"></script>
<script>
    var common;
    layui.config({
        base: 'assets/layuiadmin/'
    }).extend({
        index: 'lib/index'
    }).use(['index', 'ztree', 'common'], function() {
        common = layui.common;
        var $ = layui.$;
        var $win = $(window);
        var resizeTimeout = null;
        var zTree;
        var checkedIds = top.dialog.dialogData.checkedIds ? top.dialog.dialogData.checkedIds : [];
        var checkedNodes = [];
        var checkedDepartmentMap = new Map();
        top.dialog.dialogData.checkedNodes = [];

        function closeBox() {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        }

        // 初始化大小
        function initSize() {
            $('#treeBox').css({
                height: $win.height() - 52,
                overflow: 'auto'
            });
            $('#checkedNodeBox').css({
                height: $win.height() - 52,
                overflow: 'auto'
            });
        }

        /**
         * 勾选节点
         * @param id
         * @param name
         * @returns {string}
         */
        function getCheckedNode(id, name) {
            return '<button type="button" class="layui-btn layui-btn-xs">'+ name +' <i class="fa fa-times remove-checked-department" data-department-id="'+ id +'"></i></button>'
        }

        /**
         * 初始化勾选节点
         */
        function initCheckNodes(callback) {
            if(!checkedIds || checkedIds.length == 0) {
                return;
            }
            top.restAjax.post(top.restAjax.path('api/department/list/ids', []), {
                ids: checkedIds
            }, null, function(code, data) {
                $('#checkedNodeBox').empty();
                var checkedNodes = '';
                for(var i = 0, item; item = data[i++];) {
                    checkedNodes += getCheckedNode(item.departmentId, item.departmentName);
                    checkedDepartmentMap.set(item.departmentId, {
                        id: item.departmentId,
                        name: item.departmentName
                    });
                }
                $('#checkedNodeBox').append(checkedNodes);
                callback ? callback() : '';
            }, function(code, data) {
                top.dialog.msg(data.msg);
            });
        }

        // 刷新选择的节点
        function refreshCheckedNodes() {
            var nodes = zTree.getCheckedNodes(true);
            $('#checkedNodeBox').empty();
            var checkedNodes = '';
            for(var i = 0, item; item = nodes[i++];) {
                checkedNodes += getCheckedNode(item.id, item.name);
            }
            $('#checkedNodeBox').append(checkedNodes);
        }
        // 初始化树
        function initThree() {
            var setting = {
                check: {
                    enable: true,
                    chkboxType : {'Y': '', 'N': ''},
                },
                async: {
                    enable: true,
                    autoLoad: true,
                    type: 'get',
                    url: top.restAjax.path('api/department/listztree', []),
                    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: {
                    onAsyncSuccess: function(event, treeId, treeNode) {
                        // 初始化已选则数据
                        checkedDepartmentMap.forEach(function(item) {
                            var node = zTree.getNodeByParam('id', item.id);
                            if(!node) {
                                return;
                            }
                            zTree.checkNode(node, true, false);
                        })
                    },
                    onCheck: function(event, treeId, treeNode) {
                        if(treeNode.checked) {
                            checkedDepartmentMap.set(treeNode.id, {
                                id: treeNode.id,
                                name: treeNode.name
                            });
                        } else {
                            checkedDepartmentMap.delete(treeNode.id);
                        }
                        refreshCheckedNodes();
                    }
                },
            };
            zTree = $.fn.zTree.init($("#tree"), setting);
        }

        function initCheckedDepartmentMap() {
            var checkedDepartments = checkedNodes;
            if(!checkedDepartments) {
                return;
            }
            for(var i = 0, item; item = checkedDepartments[i++];){
                checkedDepartmentMap.set(item.departmentId, item);
            }
        }

        initSize();
        initCheckNodes(function() {
            initCheckedDepartmentMap();
            initThree();
        });

        // 事件 - 页面变化
        $win.on('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                initSize();
            }, 500);
        });

        $('.close').on('click', function() {
            closeBox();
        });

        // 删除
        $(document).on('click', '.remove-checked-department', function() {
            var departmentId = this.dataset.departmentId;
            checkedDepartmentMap.delete(departmentId);
            var node = zTree.getNodeByParam('id', departmentId);
            zTree.checkNode(node, false, false);
            refreshCheckedNodes();
        })

        $('.submit').on('click', function() {
            checkedDepartmentMap.forEach(function(item) {
                checkedNodes.push(item);
            });
            top.dialog.dialogData.checkedNodes = checkedNodes;
            closeBox();
        });
    });
</script>
</body>
</html>