<!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%; }
    .image-upload-wrap { display: flex; align-items: center; gap: 10px; }
    .image-upload-wrap .preview-img { width: 60px; height: 60px; object-fit: cover; border: 1px solid #e6e6e6; border-radius: 4px; display: none; }
    .image-upload-wrap .preview-img.active { display: block; }
</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">
            <label class="layui-form-label">绑定模型</label>
            <div class="layui-input-block">
                <select id="model_id" name="model_id" 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="（可选）" class="layui-input" autocomplete="off">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">图片</label>
            <div class="layui-input-block">
                <div class="image-upload-wrap">
                    <input type="hidden" id="image" name="image" value="">
                    <img id="imagePreview" class="preview-img" src="" alt="">
                    <button type="button" class="layui-btn layui-btn-sm" id="chooseImageBtn">
                        <i class="layui-icon layui-icon-upload"></i> 选择图片
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="removeImageBtn" style="display:none;">
                        <i class="layui-icon layui-icon-delete"></i> 移除
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea id="description" name="description" placeholder="分类描述（可选）" class="layui-textarea"></textarea>
            </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="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="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'], function() {
            var form = layui.form;
            var $ = layui.jquery;

            $.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 isEdit = !!editId;
            var categoryData = null;
            var treeLoaded = false;
            var modelsLoaded = false;

            function loadCategoryTree() {
                $.ajax({
                    url: '/api/admin/content-categories/tree',
                    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) {
                                    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);
                            treeLoaded = true;
                            tryInitForm();
                        }
                    }
                });
            }

            function loadModels() {
                $.ajax({
                    url: '/api/admin/content-models?per_page=100',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 0 && res.data && res.data.items) {
                            var options = '<option value="">不绑定模型</option>';
                            res.data.items.forEach(function(item) {
                                options += '<option value="' + item.id + '">' + item.name + '</option>';
                            });
                            $('#model_id').html(options);
                            modelsLoaded = true;
                            tryInitForm();
                        }
                    }
                });
            }

            loadCategoryTree();
            loadModels();

            function tryInitForm() {
                if (!treeLoaded || !modelsLoaded) return;
                if (isEdit && categoryData) {
                    initFormData();
                } else if (!isEdit) {
                    if (parentId) {
                        $('#parent_id').val(parentId);
                    }
                    form.render();
                }
            }

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

            function initFormData() {
                var d = categoryData;
                $('#id').val(d.id);
                $('#name').val(d.name);
                $('#icon').val(d.icon || '');
                $('#description').val(d.description || '');
                $('#sort').val(d.sort || 0);
                $('#image').val(d.image || '');

                if (d.parent_id) {
                    $('#parent_id').val(d.parent_id);
                }
                if (d.model_id) {
                    $('#model_id').val(d.model_id);
                }

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

                if (d.image) {
                    $('#imagePreview').attr('src', d.image).addClass('active');
                    $('#removeImageBtn').show();
                }

                form.render();
            }

            $('#chooseImageBtn').on('click', function() {
                layer.open({
                    type: 2,
                    title: '选择图片',
                    maxmin: true,
                    success: function(layero, idx){
    layer.full(idx); // 立即最大化
  },
                    area: ['90%', '80%'],
                    content: '/admin/attachment?picker=1',
                    end: function() {
                        var selectedUrl = sessionStorage.getItem('selectedAttachmentUrl');
                        if (selectedUrl) {
                            $('#image').val(selectedUrl);
                            $('#imagePreview').attr('src', selectedUrl).addClass('active');
                            $('#removeImageBtn').show();
                            sessionStorage.removeItem('selectedAttachmentUrl');
                        }
                    }
                });
            });

            $('#removeImageBtn').on('click', function() {
                $('#image').val('');
                $('#imagePreview').attr('src', '').removeClass('active');
                $(this).hide();
            });

            form.on('submit(save)', function(data) {
                var formData = data.field;
                formData.status = formData.status === 'on' ? 1 : 0;
                if (!formData.parent_id) formData.parent_id = 0;
                if (!formData.model_id) formData.model_id = null;

                var url = isEdit ? '/api/admin/content-categories/' + editId : '/api/admin/content-categories';
                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;
            });
        });
    </script>
</body>
</html>
