<!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" 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">
    <link rel="stylesheet" href="assets/layuiadmin/style/common.css" media="all">
    <style>
        .layui-btn+.layui-btn {margin: 0}
        .selected-node {margin-right: 10px !important;}
        .selected-node:last-child {margin: 0 !important;}
        .ztree * {font-size: 16px;}
        .layui-btn-xs {font-size: 16px;}
    </style>
</head>
<body>
    <div class="layui-card" style="height:100%;margin-bottom:0;">
        <div class="layui-card-body">
            <fieldset class="layui-elem-field">
                <div class="layui-field-box" style="height: 100px; overflow: auto;">
                    <div id="selectNodes" class="tree-nodes-wrap"></div>
                </div>
            </fieldset>
            <div id="treeWrap" class="tree-wrap">
                <ul id="ztree" class="ztree"></ul>
            </div>
            <div class="layui-form-item layui-layout-admin">
                <div class="layui-footer" style="left: 0;">
                    <button type="button" class="layui-btn" id="submitForm">确定</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="closeBox">关闭</button>
                </div>
            </div>
        </div>
    </div>
    <script src="assets/layuiadmin/layui/layui.js"></script>
    <script type="text/javascript">
        layui.config({
            base: 'assets/layuiadmin/'
        }).extend({
            index: 'lib/index'
        }).use(['index', 'ztree', 'common'], function() {
            var $ = layui.$;
            var common = layui.common;
            var selectTree = top.dialog.dialogTreeData;
            var token = top.token;
            var zTree;
            var defaultNodes = selectTree.selectedNodes;
            var selectedNodes = [];

            $('#treeWrap').css({
                height: $(window).height() - 205,
                overflow: 'auto'
            });

            function initNodes() {
                for(var i = 0; i < defaultNodes.length; i++) {
                    var item = defaultNodes[i];
                    if(typeof(item[selectTree.primaryKey]) != 'undefined' && item[selectTree.primaryKey] != null && item[selectTree.primaryKey] != '') {
                        selectedNodes.push(item);
                    } else {
                        defaultNodes.splice(i, 1);
                        i--;
                    }
                }
            }
            initNodes();
            // 删除选中的节点
            function removeSelectNodes(nodeId) {
                for(var i = 0; i < selectedNodes.length; i++) {
                    var item = selectedNodes[i];
                    if(nodeId == item[selectTree.primaryKey]) {
                        $('#selectNode_'+ nodeId).remove();
                        selectedNodes.splice(i, 1);
                    }
                }
                // 清空树选中状态
                if(selectTree.check.enable) {
                    var nodes = zTree.getCheckedNodes(true);
                    for(var i = 0, item = nodes[i]; item = nodes[i++];) {
                        if(nodeId == item[selectTree.primaryKey]) {
                            zTree.checkNode(item, false, true);
                            break;
                        }
                    }
                }
            }
            $(document.body).on('click', '.item-close', function() {
                removeSelectNodes(this.dataset.id);
            });
            // 初始化选中的节点
            function showSelectNodes() {
                $('#selectNodes').empty();
                for(var i = 0; i < selectedNodes.length; i++) {
                    var item = selectedNodes[i];
                    if(typeof(item[selectTree.primaryKey]) == 'undefined' || item[selectTree.primaryKey] == null || item[selectTree.primaryKey] == '') {
                        selectedNodes.splice(i, 1);
                        i--;
                        continue;
                    }
                    $('#selectNodes').append('<span id="selectNode_'+ item[selectTree.primaryKey] +'" class="layui-btn layui-btn-xs selected-node">'+ item.name +'</span>')
                }
            }
            // 初始化节点
            function initSelectNodes() {
                showSelectNodes();
                var nodes = zTree.getNodes();
                for(var i = 0, item = nodes[i]; item = nodes[i++];) {
                    for(var j = 0, node = selectedNodes[j]; node = selectedNodes[j++];) {
                        if(item[selectTree.primaryKey] == node[selectTree.primaryKey]) {
                            zTree.checkNode(item, true, true);
                            break;
                        }
                    }
                }
            }
            // 节点是否已经选择
            function isNodeSelect(nodeId) {
                for(var i = 0, item = selectedNodes[i]; item = selectedNodes[i++];) {
                    if(nodeId == item[selectTree.primaryKey]) {
                        return true;
                    }
                }
                return false;
            }
            $(function() {
                var apiUri = selectTree.apiUri;
                var isHttp = /^http:\/\/|^https:\/\/.*/i.test(apiUri);
                var otherParams = selectTree.otherParams;
                var requestUrl;
                var requestMethod;
                var autoLoad = false;
                if(isHttp) {
                    requestMethod = 'post';
                    requestUrl = top.restAjax.path('api/tree/listtree/{resultType}', [selectTree.resultType]);
                    otherParams.apiUri = selectTree.apiUri;
                    otherParams.method = selectTree.method;
                    if(selectTree.defaultParams != null) {
                        for(var i in selectTree.defaultParams) {
                            otherParams['defaultKeyAndValue_'+ i] = selectTree.defaultParams[i];
                        }
                    }
                } else {
                    requestUrl = apiUri;
                    requestMethod = selectTree.method;
                    if(selectTree.defaultParams != null) {
                        for (var i in selectTree.defaultParams) {
                            otherParams[i] = selectTree.defaultParams[i];
                        }
                    }
                }
                // 根节点不存在自动加载
                if(typeof(selectTree.rootNode) == 'undefined' || selectTree.rootNode == null) {
                    autoLoad = true;
                }
                var setting = {
                    async: {
                        autoLoad: autoLoad,
                        url: requestUrl,
                        autoParam: selectTree.autoParams,
                        enable: true,
                        type: requestMethod,
                        otherParam: otherParams,
                        dataFilter: selectTree.dataFilter
                    },
                    data: {
                        key: {
                            checked: selectTree.data.checked,
                            children: selectTree.data.children,
                            isParent: selectTree.data.isParent,
                            name: selectTree.data.name,
                            title: selectTree.data.title
                        },
                    },
                    check: selectTree.check,
                    headers: {
                        token: token
                    },
                    callback: {
                        onClick: function(event, treeId, treeNode) {
                            if(!selectTree.check.enable) {
                                if(treeNode[selectTree.primaryKey] == '0') {
                                    selectedNodes.splice(0, 1);
                                } else {
                                    if(selectedNodes.length == 0) {
                                        selectedNodes.push(treeNode);
                                    } else {
                                        selectedNodes.splice(0, 1, treeNode);
                                    }
                                }
                                showSelectNodes();
                            } else {
                                if(treeNode.checked) {
                                    zTree.checkNode(treeNode, false, true);
                                } else {
                                    zTree.checkNode(treeNode, true, true);
                                }
                                if(!isNodeSelect(treeNode[selectTree.primaryKey])) {
                                    if(treeNode[selectTree.primaryKey] == '0') {
                                        zTree.checkNode(treeNode, false, true);
                                        return;
                                    } else {
                                        selectedNodes.push(treeNode);
                                    }
                                    showSelectNodes();
                                } else {
                                    removeSelectNodes(treeNode[selectTree.primaryKey]);
                                }
                            }
                        },
                        onAsyncSuccess: function(event, treeId, treeNode, msg) {
                            var nodes = zTree.getNodes();
                            if(nodes.length == 0) {
                                top.dialog.msg('暂无数据');
                                return;
                            }
                            // 自动打钩
                            if(selectTree.check.enable) {
                                if(typeof(treeNode) != 'undefined') {
                                    var childNodes = treeNode[selectTree.data.children];
                                    if(typeof(childNodes) != 'undefined' && childNodes != null && childNodes.length > 0) {
                                        for(var i = 0, item = childNodes[i]; item = childNodes[i++];) {
                                            for(var j = 0, selectedNode = selectedNodes[j]; selectedNode = selectedNodes[j++];) {
                                                if(item[selectTree.primaryKey] == selectedNode[selectTree.primaryKey]) {
                                                    zTree.checkNode(item, true, true);
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    var rootNodes = zTree.getNodesByFilter(function (node) { return node.level == 0 });
                                    for(var i = 0, item = rootNodes[i]; item = rootNodes[i++];) {
                                        for(var j = 0, selectedNode = selectedNodes[j]; selectedNode = selectedNodes[j++];) {
                                            if(item[selectTree.primaryKey] == selectedNode[selectTree.primaryKey]) {
                                                zTree.checkNode(item, true, true);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        },
                    }
                };
                zTree = $.fn.zTree.init($("#ztree"), setting);
                if(typeof(selectTree.rootNode) != 'undefined' && selectTree.rootNode != null) {
                    if(typeof(selectTree.rootNode[selectTree.primaryKey]) != 'undefined' && selectTree.rootNode[selectTree.primaryKey] != null && selectTree.rootNode[selectTree.primaryKey] != '') {
                        zTree.addNodes(null, selectTree.rootNode);
                    }
                } else {
                    if(!autoLoad) {
                        var rootNode = {pId: '-1', name: '根节点', url: 'javascript:;', isParent: 'true'};
                        rootNode[selectTree.primaryKey] = '0';
                        zTree.addNodes(null, rootNode);
                    }
                }
                common.refreshTree('ztree');
                initSelectNodes();
            }, function(code, data) {
                top.dialog.msg(data.msg);
            }, function() {
                layerIndex = top.dialog.msg(top.dataMessage.loading, {icon: 16, time: 0, shade: 0.3});
            }, function() {
                top.dialog.close(layerIndex);
            });

            function closeBox() {
                top.dialog.closeBox();
            }
            function submitForm() {
                top.dialog.dialogTreeData.selectedNodes = selectedNodes;
                closeBox();
            }

            $('#submitForm').on('click', function() {
                submitForm();
            });
            $('#closeBox').on('click', function() {
                closeBox();
            });
        });
    </script>
</body>
</html>