// 运行目录功能
?>
<?php elseif ($gn == 'yxml'):?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?php echo L('run_dir', 'menu'); ?></h3>
    </div>
    <div class="card-body">
        <div class="alert alert-info d-flex align-items-center mb-4">
            <i class="fas fa-info-circle mr-2"></i>
            <div>设置网站的运行目录，通常用于 Laravel, ThinkPHP 等框架项目。</div>
        </div>
        <form id="yxmlForm">
            <div class="form-group mb-4">
                <label class="font-weight-bold" for="rundir">运行目录</label>
                <div class="input-group">
                    <input type="text" name="rundir" id="rundir" class="form-control" placeholder="/" value="/">
                    <div class="input-group-append">
                        <button type="button" class="btn btn-outline-secondary" data-action="browse-directory">
                            <i class="fas fa-folder-open mr-1"></i> 浏览
                        </button>
                    </div>
                </div>
            </div>
            <button type="button" class="btn btn-success" data-action="set-yxml">
                <i class="fas fa-check mr-1"></i> 确认设置
            </button>
        </form>
    </div>
</div>

<!-- 目录浏览模态框 -->
<div class="modal fade" id="directoryModal" tabindex="-1" role="dialog" aria-labelledby="directoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="directoryModalLabel"><?php echo L('file_manager', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb bg-light" id="directoryBreadcrumb">
                        <li class="breadcrumb-item"><a href="#" data-path="/">/</a></li>
                    </ol>
                </nav>
                <div class="list-group" id="directoryList" style="max-height: 400px; overflow-y: auto;">
                    <div class="text-center p-4">
                        <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
                        <div class="text-muted">加载中...</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" data-action="select-directory">选择当前目录</button>
            </div>
        </div>
    </div>
</div>

<style>
#directoryList .directory-item {
    cursor: pointer;
    transition: background-color 0.2s;
}
#directoryList .directory-item:hover {
    background-color: #f8f9fa;
}
#directoryList .directory-item i {
    color: #ffc107;
}
</style>

<script>
// 页面加载完成后获取当前运行目录设置
$(document).ready(function() {
    loadCurrentRunDir();
});

// 获取服务器中已有的运行目录设置
function loadCurrentRunDir() {
    console.log('加载当前运行目录设置开始');
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getyxml',
        dataType: 'json',
        success: function(data) {
            console.log('加载当前运行目录设置成功，返回数据:', data);
            if(data.code == 'success' && data.rundir) {
                $('#rundir').val(data.rundir);
                console.log('设置当前运行目录设置成功:', data.rundir);
            } else {
                console.log('加载当前运行目录设置失败，错误信息:', data.code);
            }
        },
        error: function(xhr, status, error) {
            console.log('加载当前运行目录设置AJAX错误:', status, error);
        }
    });
}

var currentDirectory = '/';

function browseDirectory() {
    currentDirectory = '/';
    loadDirectory(currentDirectory);
    $('#directoryModal').modal('show');
}

function loadDirectory(path) {
    currentDirectory = path;
    $('#directoryList').html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>');
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getdirectory&path=' + encodeURIComponent(path),
        dataType: 'json',
        success: function(data) {
            console.log('加载目录响应:', data);
            if (data.status === true && data.files && Array.isArray(data.files)) {
                // 过滤出目录
                var directories = data.files.filter(function(f) { return f.is_dir === true || f.type === 'dir'; });
                if (directories.length > 0) {
                    var $container = $('<div></div>');
                    directories.forEach(function(dir) {
                        var $a = $('<a href="#" class="list-group-item list-group-item-action directory-item"></a>');
                        $a.data('path', dir.path);
                        $a.append('<i class="fas fa-folder mr-2"></i> ');
                        $a.append(document.createTextNode(dir.name || dir.path.split('/').pop() || ''));
                        // 点击目录项进入子目录
                        $a.on('click', function(e) {
                            e.preventDefault();
                            var path = $(this).data('path');
                            console.log('点击目录:', path);
                            loadDirectory(path);
                        });
                        $container.append($a);
                    });
                    $('#directoryList').empty().append($container);
                } else {
                    $('#directoryList').html('<div class="list-group-item text-center text-muted">当前目录为空</div>');
                }
                updateBreadcrumb(path);
            } else {
                $('#directoryList').html('<div class="list-group-item text-center text-danger">' + (data.msg || data.code || '加载失败') + '</div>');
            }
        },
        error: function(xhr) {
            $('#directoryList').html('<div class="list-group-item text-center text-danger">加载失败，请重试</div>');
            console && console.error && console.error('loadDirectory error', xhr);
        }
    });
}

function navigateToDirectory(path) {
    loadDirectory(path);
}

function updateBreadcrumb(path) {
    var parts = path.split('/').filter(function(part) { return part !== ''; });
    var $bc = $('<div></div>');
    var $root = $('<a href="#" class="breadcrumb-item" data-path="/">/</a>');
    $root.on('click', function(e) {
        e.preventDefault();
        loadDirectory('/');
    });
    $bc.append($root);
    var currentPath = '/';

    parts.forEach(function(part) {
        currentPath += part + '/';
        var $a = $('<a href="#" class="breadcrumb-item"></a>');
        $a.text(part);
        $a.attr('data-path', currentPath);
        $a.on('click', function(e) {
            e.preventDefault();
            loadDirectory(currentPath);
        });
        $bc.append($a);
    });

    $('#directoryBreadcrumb').html($bc.children());
}

// 目录选择：将当前目录应用到输入框并关闭模态框
function selectCurrentDirectory() {
    try {
        if (typeof currentDirectory !== 'undefined') {
            $('#rundir').val(currentDirectory);
        }
        $('#directoryModal').modal('hide');
    } catch (e) {
        console && console.error && console.error('selectCurrentDirectory error', e);
    }
}

// 保存运行目录
function setyxml(btn) {
    console.log('setyxml函数被调用');
    var $btn = $(btn);
    var originalText = $btn.html();
    var rundir = $('#rundir').val();
    console.log('rundir值:', rundir);
    
    $btn.addClass('btn-loading').prop('disabled', true);

    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=setyxml&rundir=' + encodeURIComponent(rundir),
        dataType: 'json',
        success: function(data) {
            console.log('保存响应数据:', data);
            layer.close(ii);
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            if (data.status) {
                layer.msg(data.msg || '设置成功');
                setTimeout(function(){ location.reload(); }, 1000);
            } else {
                layer.alert(data.msg || '设置失败');
            }
        },
        error: function(xhr, status, error) {
            console.log('保存失败:', status, error);
            layer.close(ii);
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            layer.msg('网络错误，请重试');
        }
    });
}

// 兼容性：有些按钮使用驼峰或短横混合命名，确保 set-yxml 也能被代理处理
$(document).on('click', '[data-action="set-yxml"]', function(e){ e.preventDefault(); setyxml(this); });

</script>