<?php
$csrfField = \Helper::csrfField();
$typeNames = [
    'local' => '本地存储',
    'qiniu' => '七牛云',
    'aliyun' => '阿里云OSS',
    'tencent' => '腾讯云COS'
];

if (!isset($files)) {
    $files = [];
}
?>
<div class="page-header">
    <h1 class="page-title">文件管理</h1>
    <div class="page-actions">
        <a href="<?php echo \Helper::url('admin/storage/browseLocal'); ?>" class="btn btn-sm btn-default">
            <i class="fa fa-folder-open"></i> 浏览本地文件
        </a>
        <button class="btn btn-sm btn-default" onclick="refreshStats()">
            <i class="fa fa-refresh"></i> 刷新统计
        </button>
    </div>
</div>

<!-- 存储统计 -->
<div class="stats-cards" id="storageStats">
    <div class="stat-card">
        <div class="stat-icon"><i class="fa fa-file"></i></div>
        <div class="stat-info">
            <div class="stat-label">总文件数</div>
            <div class="stat-value" id="totalFiles">加载中...</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon"><i class="fa fa-database"></i></div>
        <div class="stat-info">
            <div class="stat-label">总大小</div>
            <div class="stat-value" id="totalSize">加载中...</div>
        </div>
    </div>
</div>

<!-- 筛选表单 -->
<div class="filter-bar">
    <form method="get" class="filter-form inline">
        <select name="type" class="form-select" onchange="this.form.submit()">
            <option value="">全部存储</option>
            <option value="local" <?php echo $type === 'local' ? 'selected' : ''; ?>>本地存储</option>
            <option value="qiniu" <?php echo $type === 'qiniu' ? 'selected' : ''; ?>>七牛云</option>
            <option value="aliyun" <?php echo $type === 'aliyun' ? 'selected' : ''; ?>>阿里云OSS</option>
            <option value="tencent" <?php echo $type === 'tencent' ? 'selected' : ''; ?>>腾讯云COS</option>
        </select>
        
        <select name="file_type" class="form-select" onchange="this.form.submit()">
            <option value="">全部类型</option>
            <option value="image" <?php echo $file_type === 'image' ? 'selected' : ''; ?>>图片</option>
            <option value="video" <?php echo $file_type === 'video' ? 'selected' : ''; ?>>视频</option>
            <option value="attachment" <?php echo $file_type === 'attachment' ? 'selected' : ''; ?>>附件</option>
        </select>
        
        <input type="text" name="keyword" class="form-input" placeholder="搜索文件名" value="<?php echo \Helper::escape($keyword); ?>">
        <button type="submit" class="btn btn-sm btn-primary">搜索</button>
    </form>
</div>

<!-- 文件列表 -->
<div class="data-table">
    <table>
        <thead>
            <tr>
                <th width="40"><input type="checkbox" id="checkAll"></th>
                <th>文件名</th>
                <th width="80">类型</th>
                <th width="100">存储</th>
                <th width="100">大小</th>
                <th width="150">上传时间</th>
                <th width="100">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($files)): ?>
            <tr>
                <td colspan="7" class="empty-cell">
                    <i class="fa fa-inbox"></i>
                    <p>暂无文件记录</p>
                </td>
            </tr>
            <?php else: ?>
            <?php foreach ($files as $file): ?>
            <tr data-id="<?php echo $file['id']; ?>">
                <td><input type="checkbox" class="file-check" value="<?php echo $file['id']; ?>"></td>
                <td>
                    <div class="file-info">
                        <?php if ($file['file_type'] === 'image'): ?>
                        <img src="<?php echo \Helper::uploadUrl($file['path']); ?>" alt="" class="file-thumb">
                        <?php else: ?>
                        <i class="fa fa-file file-icon"></i>
                        <?php endif; ?>
                        <span class="file-name" title="<?php echo \Helper::escape($file['original_name']); ?>"><?php echo \Helper::escape($file['original_name']); ?></span>
                    </div>
                </td>
                <td><span class="tag tag-<?php echo $file['file_type']; ?>"><?php echo $file['file_type']; ?></span></td>
                <td><?php echo $typeNames[$file['storage_type']] ?? $file['storage_type']; ?></td>
                <td><?php echo $file['size_formatted']; ?></td>
                <td><?php echo $file['created_time']; ?></td>
                <td>
                    <a href="<?php echo \Helper::uploadUrl($file['path']); ?>" target="_blank" class="text-primary">查看</a>
                    <a href="javascript:;" onclick="deleteFile(<?php echo $file['id']; ?>)" class="text-danger">删除</a>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- 分页 -->
<?php if (isset($pages) && $pages > 1): ?>
<div class="pagination-wrapper">
    <div class="pagination">
        <?php for ($i = 1; $i <= $pages; $i++): ?>
        <a href="?page=<?php echo $i; ?>&type=<?php echo $type; ?>&file_type=<?php echo $file_type; ?>&keyword=<?php echo \Helper::escape($keyword); ?>" 
           class="<?php echo $i === $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
    </div>
</div>
<?php endif; ?>

<!-- 批量操作 -->
<div class="batch-actions">
    <button class="btn btn-sm btn-danger" onclick="batchDelete()">
        <i class="fa fa-trash"></i> 批量删除
    </button>
    <span class="selected-info">已选择 <span id="selectedCount">0</span> 项</span>
</div>

<style>
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-title { margin: 0; font-size: 20px; font-weight: 500; }
.page-actions { display: flex; gap: 10px; }
.stats-cards { display: flex; gap: 20px; margin-bottom: 20px; }
.stat-card { flex: 1; display: flex; align-items: center; padding: 15px 20px; background: #f8f9fa; border-radius: 8px; }
.stat-icon { width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; background: #fff; border-radius: 50%; margin-right: 15px; color: #1890ff; font-size: 20px; }
.stat-info { flex: 1; }
.stat-label { font-size: 12px; color: #666; margin-bottom: 4px; }
.stat-value { font-size: 20px; font-weight: 600; color: #333; }
.filter-bar { margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px; }
.filter-form { display: flex; gap: 10px; align-items: center; }
.filter-form .form-select, .filter-form .form-input { padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; }
.filter-form .form-select { width: 120px; }
.filter-form .form-input { width: 180px; }
.data-table { background: #fff; border-radius: 8px; overflow: hidden; border: 1px solid #eee; }
.data-table table { width: 100%; border-collapse: collapse; }
.data-table th, .data-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; }
.data-table th { background: #fafafa; font-weight: 500; font-size: 13px; color: #666; }
.data-table tbody tr:hover { background: #f8f9fa; }
.data-table tbody tr:last-child td { border-bottom: none; }
.file-info { display: flex; align-items: center; gap: 10px; }
.file-thumb { width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #eee; }
.file-icon { font-size: 24px; color: #999; }
.file-name { max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tag { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 12px; }
.tag-image { background: #e3f2fd; color: #1976d2; }
.tag-video { background: #fce4ec; color: #c2185b; }
.tag-attachment { background: #fff3e0; color: #f57c00; }
.text-primary { color: #1890ff; text-decoration: none; margin-right: 10px; }
.text-danger { color: #f5222d; text-decoration: none; }
.empty-cell { text-align: center; color: #999; padding: 50px !important; }
.empty-cell i { font-size: 48px; display: block; margin-bottom: 10px; }
.empty-cell p { margin: 0; }
.pagination-wrapper { display: flex; justify-content: center; margin-top: 20px; }
.pagination { display: flex; gap: 5px; }
.pagination a { padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; color: #666; }
.pagination a:hover { background: #f0f0f0; }
.pagination a.active { background: #1890ff; color: #fff; border-color: #1890ff; }
.batch-actions { margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee; display: flex; align-items: center; gap: 15px; }
.selected-info { color: #666; font-size: 13px; }
</style>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
    $('#checkAll').change(function() {
        $('.file-check').prop('checked', this.checked);
        updateSelectedCount();
    });
    
    $('.file-check').change(function() {
        updateSelectedCount();
    });
    
    refreshStats();
});

function updateSelectedCount() {
    var count = $('.file-check:checked').length;
    $('#selectedCount').text(count);
}

function refreshStats() {
    $.get('<?php echo \Helper::url("admin/storage/stats"); ?>', function(res) {
        if (res.code === 0) {
            $('#totalFiles').text(res.data.total_files);
            $('#totalSize').text(res.data.total_size_formatted);
        }
    }, 'json');
}

function formatSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}

function deleteFile(id) {
    if (!confirm('确定要删除这个文件吗？')) return;
    
    $.post('<?php echo \Helper::url("admin/storage/deleteFile"); ?>', {
        id: id,
        csrf_token: $('input[name="csrf_token"]').val()
    }, function(res) {
        if (res.code === 0) {
            $('tr[data-id="' + id + '"]').fadeOut(300, function() {
                $(this).remove();
            });
            alert('删除成功');
            refreshStats();
        } else {
            alert(res.message);
        }
    }, 'json');
}

function batchDelete() {
    var ids = [];
    $('.file-check:checked').each(function() {
        ids.push($(this).val());
    });
    
    if (ids.length === 0) {
        alert('请选择要删除的文件');
        return;
    }
    
    if (!confirm('确定要删除选中的 ' + ids.length + ' 个文件吗？')) return;
    
    $.post('<?php echo \Helper::url("admin/storage/batchDelete"); ?>', {
        ids: ids.join(','),
        csrf_token: $('input[name="csrf_token"]').val()
    }, function(res) {
        if (res.code === 0) {
            $('.file-check:checked').closest('tr').fadeOut(300, function() {
                $(this).remove();
            });
            alert('批量删除成功');
            refreshStats();
        } else {
            alert(res.message);
        }
    }, 'json');
}
</script>
