<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/zTree3/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="/static/zTree3/js/jquery.ztree.excheck.js"></script>
<script type="text/javascript" src="/static/zTree3/js/jquery.ztree.exedit.js"></script>

<div class="layui-row">
    <div style="margin: 10px 20px">
        <blockquote class="layui-elem-quote">
            说明：新增权限，请直接填写相关数据保存即可；修改和删除，请点击左侧权限树选择要修改的权限节点
        </blockquote>
    </div>

    <div class="layui-col-md5 zTreeDemoBackground" style="margin-left: 20px;margin-right: 0px">
        <ul id="treeDemo" class="ztree" style="height:320px; width: auto; margin-bottom: 10px;">
        </ul>
    </div>
    <div class="layui-col-md7">
        <div class="layui-layout layui-layout-admin" style="padding-left: 40px;margin-top: 20px;">
            <form class="layui-form" action="" onsubmit="javascript:;" name="form" method="post">

                <div class="layui-form-item">
                    <label class="layui-form-label">权限名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="auth_name" lay-verify="required" autocomplete="off" placeholder="请输入权限名称" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux"></div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">上级权限</label>
                    <div class="layui-input-inline" style="width: 210px;">
                        <input type="text" name="pname" lay-verify="required" autocomplete="off" placeholder="请选择" disabled value="所有权限" class="layui-input" id="pname">

                    </div>
                    <div class="layui-input-inline" style="width: 50px;">
                        <input type="text" name="pid" autocomplete="off" placeholder="0" id="pid" class="layui-input" readonly value="1">
                    </div>
                    <div class="layui-form-mid layui-word-aux">

                        <button id="menuBtn" type="button" class="layui-btn layui-btn-xs layui-btn-normal" >选择顶级分类</button>
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">菜单地址</label>
                    <div class="layui-input-inline">
                        <input type="text" name="auth_url" lay-verify="required" autocomplete="off" placeholder="/home" class="layui-input" value="/">
                    </div>
                    <div class="layui-form-mid layui-word-aux"></div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">图标字体</label>
                    <div class="layui-input-inline">
                        <input type="text" name="icon" autocomplete="off" placeholder="fa-bar-chart-o" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux"><a href="http://fontawesome.dashgame.com" target="_blank">点击这里参考</a></div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">排序</label>
                    <div class="layui-input-inline">
                        <input type="text" name="sort" lay-verify="required" autocomplete="off" placeholder="999" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux"></div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">是否显示</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="is_show" value="0" title="隐藏" checked>
                        <input type="radio" name="is_show" value="1" title="显示">
                    </div>
                    <div class="layui-form-mid layui-word-aux">是否左侧导航栏显示</div>
                </div>

                <input type="hidden" name="id" class="layui-input" id="id" value="0">

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit="" lay-filter="add">新增</button>
                        <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="edit">修改</button>
                        <a class="layui-btn layui-btn-danger" href="javascript:;" id="del" lay-submit="">删除</a>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>



<div id="menuContent" class="menuContent" style="display:none; position: absolute;">
    <ul id="treeMenu" class="ztree" style="margin-top:0; width:200px; height: 200px"></ul>
</div>

<script>
    var $,form;
    layui.use(['form','element','layer'],function(){
        form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
        $ = layui.$;

        var error_info = "{{.flash.error}}";
        if(error_info){
            layer.msg(error_info,{icon: 2,shade:0.3},function () {
                window.history.go(-1)
            })
            return;
        }
        form.on("submit",function(data) {
            var sub_type = data.elem.getAttribute("lay-filter")
            console.log(sub_type)
            if(sub_type=="add"){
                $("#id").val(0);
            }else{
                if($("#id").val()=="0"){
                    layer.msg("修改先请在左侧权限树选择节点")
                    return false
                }
            }
            console.log($("form").serialize());

            $.post('{{urlfor "AuthController.AjaxSave"}}', $("form").serialize(), function (out) {

                if (out.status == 0) {
                    // layer.msg("操作成功")
                    layer.msg('你成功了', {icon: 1,shade:0.3,time:2000},function(index){
                        window.location.reload();
                    });
                } else {
                    layer.msg(out.message)
                }
            }, "json");
            return false;
        });

        form.render();
        //但是，如果你的HTML是动态生成的，自动渲染就会失效
        //因此你需要在相应的地方，执行下述方法来手动渲染，跟这类似的还有 element.init();

    });
</script>

<script type="text/javascript">
    var zNodes = [{ id:1, pId:0, name:"数据错误"}];
    $(document).ready(function(){
        // $("form[name=form]").parent().find("input[type=radio]").eq(1).attr("checked", true);
        var setting = {
            // edit: {
            //  enable: true
            // },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeDrag: beforeDrag,
                onClick: editOnClick
            }
        };

        function editOnClick(e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    nodes = zTree.getSelectedNodes();
            if(nodes[0].id==1){
                alert('不允许修改根节点');
                return;
            }

            if(nodes[0].parentTId){
                var parentInfo = zTree.getNodeByTId(nodes[0].parentTId);
                pid     = parentInfo.id;
                pname   = parentInfo.name;
            }

            var id = nodes[0].id;

            $("#pid").val(nodes[0].pId);
            $("#id").val(nodes[0].id);
            $("#pname").val(pname);
            $("form[name=form]").find("input[name=auth_name]").val(nodes[0].name);

            $.ajax({
                type: "POST",
                url: "/auth/getnode",
                data: {id:id},
                dataType: 'json',
                success: function(data) {

                    if(data.code==0){
                        $("form[name=form]").find("input[name=auth_url]").val(data.data.auth_url);
                        $("form[name=form]").find("input[name=icon]").val(data.data.icon);
                        $("form[name=form]").find("input[name=sort]").val(data.data.sort);
                        var is_show = data.data.is_show
                        $("form[name=form]").find("input[type=radio][value="+is_show+"]").attr("checked", true);
                        $("form[name=form]").find("input[type=radio][value="+is_show+"]").click();
                        form.render();
                    }
                }
            });

        }

        function beforeDrag(treeId, treeNodes) {
            return false;
        }

        function setEdit() {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        }
        // //增加节点
        var newCount = 1;
        var maxId = 0;
        function add(e) {
            var maxId = $('#max_id').val();
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    isParent = e.data.isParent,
                    nodes = zTree.getSelectedNodes(),
                    treeNode = nodes[0];

            if (treeNode) {
                treeNode = zTree.addNodes(treeNode, {id:(maxId -(-newCount)), pId:treeNode.id, isParent:isParent, name:"new node" + treeNode.id + (newCount++)});
            } else {
                treeNode = zTree.addNodes(null, {id:(maxId -(-newCount)), pId:0, isParent:isParent, name:"new node" + (newCount++)});
            }

            if (treeNode) {
                zTree.editName(treeNode[0]);
            } else {
                alert("叶子节点被锁定，无法增加子节点");
            }
        };
        function showCode(str) {
            var code = $("#code");
            code.empty();
            for (var i=0, l=str.length; i<l; i++) {
                code.append("<li>"+str[i]+"</li>");
            }
        }
        //加载树
        refresh_tree();


        function refresh_tree()
        {

            var time   = Date.parse(new Date());
            $.ajax({
                type: "POST",
                url: "/auth/getnodes",
                data: {time:time},
                dataType: 'json',
                success: function(data) {
                    if(data.code==0){
                        zNodes = data.data;
                        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                        $.fn.zTree.init($("#treeMenu"), menu, zNodes);
                    }
                }
            });
            setEdit();
            $("#remove").bind("change", setEdit);
            $("#rename").bind("change", setEdit);
            $("#removeTitle").bind("propertychange", setEdit)
                    .bind("input", setEdit);
            $("#renameTitle").bind("propertychange", setEdit)
                    .bind("input", setEdit);
        }

        // //新增 type=1
        // $('#submit_add_button').on('click',function(){
        //     var data = $('form[name=form_add]').serialize();

        //     ajaxRequest({'nodes':data,'type':1},'/auth/auth/save_auth','submit_add_button','POST',0);
        // });

        // //新增 type=2
        // $('#submit_edit_button').on('click',function(){
        //     var data = $('form[name=form_add]').serialize();

        //     ajaxRequest({'nodes':data,'type':2},'/auth/auth/save_auth','submit_edit_button','POST',0);
        // });

        //删除
        $('#del').on('click',function(){
            var id = $("#id").val();
            if (id==0) {
                layer.msg('请在左侧权限树选择节点');
                return false;
            }
            layer.confirm('确认要删除吗？', {icon: 3, title:'提示'}, function(index){
                $.post('{{urlfor "AuthController.AjaxDel"}}', {id:id}, function (out) {
                    if (out.status == 0) {
                        // layer.msg("操作成功")
                        layer.alert('你删除成功了', {icon: 1},function(index){
                            window.location.reload();
                        });
                    } else {
                        layer.msg(out.message)
                    }
                }, "json");
            });
            return false;
        });

        // //清空
        // $('#submit_cancel_button').on('click',function(){
        //     var fields = ['id','pid','pname','name','menu_url','sort'];
        //     $.each(fields,function(k,v) {
        //         $("form[name=form_add]").find("input[name="+v+"]").val('');
        //     });

        // });

        //以下是下拉选择框
        var menu = {
            view: {
                dblClickExpand: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                // beforeClick: beforeClick,
                onClick: onClick
            }
        };


        function beforeClick(treeId, treeNode) {
            var check = (treeNode && !treeNode.isParent);
            if (!check) alert("不能选择");
            return check;
        }

        function onClick(e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("treeMenu"),
                    nodes = zTree.getSelectedNodes(),
                    v = "";

            nodes.sort(function compare(a,b){return a.id-b.id;});
            for (var i=0, l=nodes.length; i<l; i++) {
                v += nodes[i].name + ",";
            }
            if (v.length > 0 ) v = v.substring(0, v.length-1);
            var pid = $("#pid");

            $("#pid").val(nodes[0].id);
            $("#pname").val(v);

            hideMenu()
        }

        $("#menuBtn").on("click",function(){
            showMenu()
        })

        function showMenu() {
            var pname = $("#pname");
            var paOffset = $("#pname").offset();
//            var sideOffset = $("#left_side").width();
//            console.log(sideOffset.left)
            $("#menuContent").css({left:(paOffset.left) + "px", top:(paOffset.top - pname.outerHeight()+70) + "px"}).slideDown("fast");

            $("body").bind("mousedown", onBodyDown);
        }
        function hideMenu() {
            $("#menuContent").fadeOut("fast");
            $("body").unbind("mousedown", onBodyDown);
        }
        function onBodyDown(event) {
            if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
                hideMenu();
            }
        }

    });
</script>