<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>菜单表单</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
</head>
<style>
    .layui-form-label { padding: 9px 4px; width: unset; }
    .layui-input, .layui-textarea { width: 95%; }
</style>

<body>
    <form class="layui-form" action=""  style="padding: 10px;">
        <input type="hidden" id="id" name="id" value="">
        <div class="layui-form-item">
            <label class="layui-form-label">上级菜单</label>
            <div class="layui-input-block">
                <select id="parent_id" name="parent_id" lay-search="">
                    <option value="0">顶级菜单</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="display: none;">
            <label class="layui-form-label">所属终端</label>
            <div class="layui-input-block">
                <select id="terminal_type" name="terminal_type" lay-search="">
                    <option value="">请选择终端</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">菜单名称</label>
            <div class="layui-input-block">
                <input type="text" id="name" name="name" lay-verify="required" lay-reqText="菜单名称不能为空" placeholder="请输入菜单名称" class="layui-input" autocomplete="off">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">图标</label>
            <div class="layui-input-block">
                <input type="text" id="icon" name="icon" placeholder="选择图标" autocomplete="off" class="layui-input icon-selected1" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">路径</label>
            <div class="layui-input-block">
                <input type="text" id="path" name="path" placeholder="请输入路由路径，如 /admin/user" class="layui-input" autocomplete="off">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">组件</label>
            <div class="layui-input-block">
                <input type="text" id="component" name="component" placeholder="请输入组件路径（可选）" class="layui-input" autocomplete="off">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权限编码</label>
            <div class="layui-input-block">
                <input type="text" id="permission_code" name="permission_code" placeholder="请输入权限编码（可选）" class="layui-input" autocomplete="off">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">类型</label>
            <div class="layui-input-block">
                <select id="type" name="type">
                    <option value="1">目录</option>
                    <option value="2">菜单</option>
                    <option value="3">按钮</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否可见</label>
            <div class="layui-input-block">
                <input type="checkbox" id="visible" name="visible" lay-skin="switch" lay-text="显示|隐藏" checked>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input type="number" id="sort" name="sort" value="0" placeholder="请输入排序，数字越小越靠前" class="layui-input" autocomplete="off">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="checkbox" id="status" name="status" lay-skin="switch" lay-text="正常|禁用" checked>
            </div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit lay-filter="save">
                    <i class="layui-icon layui-icon-ok"></i> 提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                    <i class="layui-icon layui-icon-refresh"></i> 清空
                </button>
            </div>
        </div>
    </form>

    <script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
    <script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
    <script>
        layui.use(['form', 'jquery', 'iconSelectedPlus'], function() {
            var form = layui.form;
            var $ = layui.jquery;
            var iconSelectedPlus = layui.iconSelectedPlus;

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                statusCode: {
                    401: function() {
                        layer.msg('登录已过期，请重新登录', {icon: 2, time: 1500}, function() {
                            window.location.href = '/admin/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        });
                    }
                }
            });

            var editId = new URLSearchParams(window.location.search).get('id');
            var parentId = new URLSearchParams(window.location.search).get('parent_id') || 0;
            var defaultTerminal = new URLSearchParams(window.location.search).get('terminal') || '';
            var isEdit = !!editId;

            var menuData = null;
            var iconRendered = false;
            var currentTerminal = defaultTerminal || '';

            function loadParentMenu(terminal) {
                var url = '/api/admin/menus/tree';
                if (terminal && terminal !== '') {
                    url += '?terminal_type=' + encodeURIComponent(terminal);
                }
                $.ajax({
                    url: url,
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 0 && res.data) {
                            var options = '<option value="0">顶级菜单</option>';
                            function buildOptions(items, level) {
                                if (!items || !items.length) return;
                                items.forEach(function(item) {
                                    if (item.type == 3) return;
                                    var prefix = '';
                                    for (var i = 0; i < level; i++) prefix += '├─ ';
                                    options += '<option value="' + item.id + '">' + prefix + item.name + '</option>';
                                    if (item.children && item.children.length) {
                                        buildOptions(item.children, level + 1);
                                    }
                                });
                            }
                            buildOptions(res.data, 0);
                            $('#parent_id').html(options);

                            if (menuData !== null || !isEdit) {
                                initForm();
                            }
                        }
                    }
                });
            }

            loadParentMenu(currentTerminal);

            function initForm() {
                if (isEdit && menuData) {
                    var d = menuData;
                    $('#id').val(d.id);
                    $('#name').val(d.name);
                    $('#path').val(d.path || '');
                    $('#component').val(d.component || '');
                    $('#permission_code').val(d.permission_code || '');
                    $('#sort').val(d.sort || 0);
                    $('#icon').val(d.icon || '');
                    $('#type').val(d.type || '1');
                    $('#terminal_type').val(d.terminal_type || defaultTerminal || 'admin');

                    if (d.visible == 1) {
                        $('#visible').prop('checked', true);
                    } else {
                        $('#visible').prop('checked', false);
                    }

                    if (d.status == 1) {
                        $('#status').prop('checked', true);
                    } else {
                        $('#status').prop('checked', false);
                    }

                    if (d.parent_id) {
                        $('#parent_id').val(d.parent_id);
                    }
                } else if (!isEdit) {
                    if (defaultTerminal) {
                        $('#terminal_type').val(defaultTerminal);
                    }
                    if (parentId) {
                        $('#parent_id').val(parentId);
                    }
                }

                form.render();

                if (!iconRendered) {
                    iconRendered = true;
                    iconSelectedPlus.render(".icon-selected1");
                }
            }

            $.ajax({
                url: '/api/admin/menus/terminals?per_page=100',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0 && res.data && res.data.items && res.data.items.length > 0) {
                        var html = '<option value="">请选择终端</option>';
                        $.each(res.data.items, function(i, item) {
                            html += '<option value="' + item.type + '">' + item.name + '</option>';
                        });
                        $('#terminal_type').html(html);
                    }

                    form.on('select(terminal_type)', function(data) {
                        currentTerminal = data.value;
                        loadParentMenu(currentTerminal);
                    });

                    if (menuData !== null || !isEdit) {
                        initForm();
                    }
                }
            });

            if (isEdit) {
                $.ajax({
                    url: '/api/admin/menus/' + editId,
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 0 && res.data) {
                            menuData = res.data;
                            initForm();
                        } else {
                            layer.msg(res.message || '数据加载失败', { icon: 2, time: 2000 });
                        }
                    },
                    error: function() {
                        layer.msg('请求失败', { icon: 2, time: 2000 });
                    }
                });
            } else {
                menuData = null;
            }

            form.on('submit(save)', function(data) {
                var formData = data.field;

                formData.visible = formData.visible === 'on' ? 1 : 0;
                formData.status = formData.status === 'on' ? 1 : 0;

                var iconVal = $('.icon-selected-plus-input').val();
                if (iconVal) {
                    formData.icon = iconVal;
                }

                var url = isEdit ? '/api/admin/menus/' + editId : '/api/admin/menus';
                var method = isEdit ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: method,
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res) {
                        if (res.code === 0) {
                            layer.msg(isEdit ? '编辑成功' : '新增成功', { icon: 1, time: 1000 }, function() {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.refresh();
                            });
                        } else {
                            layer.msg(res.message || '操作失败', { icon: 2, time: 1500 });
                        }
                    },
                    error: function() {
                        layer.msg('请求失败', { icon: 2, time: 1500 });
                    }
                });
                return false;
            });

            setTimeout(function() {
                if (menuData === null && !isEdit) {
                    initForm();
                }
            }, 1000);
        });
    </script>
</body>
</html>
