<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宇之然内容创作平台 - 素材库</title>
    <link rel="stylesheet" href="element-plus.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background: #f5f7fa; }
        .navbar { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 16px 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .navbar-content { display: flex; justify-content: space-between; align-items: center; max-width: 1400px; margin: 0 auto; }
        .navbar-title { font-size: 20px; font-weight: 600; }
        .navbar-user { display: flex; align-items: center; gap: 16px; }
        .user-info { display: flex; align-items: center; gap: 8px; }
        .avatar { width: 32px; height: 32px; border-radius: 50%; background: rgba(255,255,255,0.2); display: flex; align-items: center; justify-content: center; font-size: 14px; }
        .main-content { display: flex; flex: 1; max-width: 1400px; margin: 0 auto; }
        .sidebar { width: 180px; background: white; padding: 12px; box-shadow: 2px 0 8px rgba(0,0,0,0.05); }
        .content-area { flex: 1; padding: 24px; overflow-y: auto; }
        .card { background: white; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        .mobile-nav { display: none; position: fixed; bottom: 0; left: 0; right: 0; background: white; box-shadow: 0 -2px 8px rgba(0,0,0,0.1); padding: 8px 0; z-index: 1000; }
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .mobile-nav { display: flex; }
            .content-area { padding: 16px; padding-bottom: 80px; }
        }
        .asset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; }
        .asset-item { border: 1px solid #ebeef5; border-radius: 8px; padding: 12px; transition: all 0.3s; cursor: pointer; }
        .asset-item:hover { border-color: #409eff; box-shadow: 0 2px 12px rgba(64,158,255,0.2); }
        .asset-thumb { width: 100%; height: 120px; border-radius: 4px; object-fit: cover; background: #f5f7fa; display: flex; align-items: center; justify-content: center; font-size: 32px; margin-bottom: 8px; }
        .asset-name { font-size: 14px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .asset-meta { font-size: 12px; color: #909399; margin-top: 4px; }
        .asset-tags { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 8px; }
        .upload-area { border: 2px dashed #dcdfe6; border-radius: 12px; padding: 40px; text-align: center; cursor: pointer; transition: all 0.3s; }
        .upload-area:hover { border-color: #409eff; background: #f0f9eb; }
        .upload-icon { font-size: 48px; color: #c0c4cc; }
        .filter-bar { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
    </style>
    <script src="navigation-component.js"></script>
    <script src="navbar-component.js"></script>
</head>
<body>
    <div id="app">
        <navbar-component title="素材库" :username="currentUser.username" :is-admin="isAdmin" @logout="handleLogout"></navbar-component>
        <navigation-component current-page="assets" :is-admin="isAdmin" @navigate="redirectToPage"></navigation-component>
        <div class="main-content">
            <main class="content-area">
                <h2 style="font-size: 24px; font-weight: 700; margin-bottom: 24px; color: #303133;">🖼️ 素材库</h2>
                <div class="card">
                    <div class="filter-bar">
                        <el-input v-model="searchKeyword" placeholder="搜索素材..." style="width: 200px;" clearable @clear="loadAssets" @keyup.enter="loadAssets">
                            <template #prefix><span>🔍</span></template>
                        </el-input>
                        <el-select v-model="filterType" placeholder="文件类型" style="width: 120px;" clearable @change="loadAssets">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="图片" value="image"></el-option>
                            <el-option label="视频" value="video"></el-option>
                            <el-option label="文档" value="document"></el-option>
                        </el-select>
                        <el-select v-model="filterTag" placeholder="标签筛选" style="width: 150px;" clearable @change="loadAssets">
                            <el-option v-for="tag in allTags" :key="tag" :label="tag" :value="tag"></el-option>
                        </el-select>
                        <el-button @click="loadAssets">🔄 刷新</el-button>
                        <el-button type="primary" @click="showUploadDialog = true">📤 上传素材</el-button>
                    </div>
                    <div style="margin-bottom: 16px; display: flex; gap: 20px; font-size: 14px; color: #606266;">
                        <span>总计: {{ assetStats.total }} 个</span>
                        <span v-for="(count, type) in assetStats.by_type" :key="type">{{ getTypeName(type) }}: {{ count }}</span>
                    </div>
                    <div v-if="loading" style="text-align: center; padding: 40px;">加载中...</div>
                    <div v-else-if="assets.length === 0" style="text-align: center; padding: 40px; color: #909399;">
                        <div style="font-size: 48px; margin-bottom: 16px;">📂</div>
                        <div>暂无素材，点击上方按钮上传</div>
                    </div>
                    <div v-else class="asset-grid">
                        <div v-for="asset in assets" :key="asset.id" class="asset-item" @click="previewAsset(asset)">
                            <div class="asset-thumb">
                                <template v-if="asset.file_type === 'image'">🖼️</template>
                                <template v-else-if="asset.file_type === 'video'">🎬</template>
                                <template v-else>📄</template>
                            </div>
                            <div class="asset-name">{{ asset.filename }}</div>
                            <div class="asset-meta">{{ formatSize(asset.size) }} | {{ formatDate(asset.created_at) }}</div>
                            <div class="asset-tags">
                                <el-tag v-for="tag in (asset.tags || [])" :key="tag" size="small" type="info">{{ tag }}</el-tag>
                            </div>
                            <div style="margin-top: 8px; display: flex; gap: 4px; justify-content: flex-end;">
                                <el-button size="small" type="primary" @click.stop="copyUrl(asset)">复制</el-button>
                                <el-button size="small" type="danger" @click.stop="deleteAsset(asset.id)">删除</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
        <el-dialog v-model="showUploadDialog" title="上传素材" width="500px">
            <el-upload ref="uploadRef" drag :auto-upload="false" :limit="10" :on-change="handleFileChange" multiple accept="image/*,.pdf,.doc,.docx,.ppt,.pptx,.mp4,.mov,.avi">
                <div class="upload-area">
                    <div class="upload-icon">📤</div>
                    <div style="margin-top: 12px; color: #606266;">将文件拖到此处，或<span style="color: #409eff;">点击上传</span></div>
                    <div style="font-size: 12px; color: #909399; margin-top: 8px;">支持: JPG, PNG, GIF, WebP, PDF, Word, PPT, MP4</div>
                </div>
            </el-upload>
            <div style="margin-top: 16px;">
                <el-input v-model="uploadTags" placeholder="标签（逗号分隔）" style="margin-bottom: 12px;"></el-input>
                <el-input v-model="uploadAltText" placeholder="描述文字（可选）"></el-input>
            </div>
            <template #footer>
                <el-button @click="showUploadDialog = false">取消</el-button>
                <el-button type="primary" @click="uploadFiles" :loading="uploading">上传</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="showPreviewDialog" title="素材预览" width="800px">
            <div v-if="previewAssetData" style="text-align: center;">
                <div style="font-size: 64px; margin-bottom: 16px;">
                    <template v-if="previewAssetData.file_type === 'image'">🖼️</template>
                    <template v-else-if="previewAssetData.file_type === 'video'">🎬</template>
                    <template v-else>📄</template>
                </div>
                <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">{{ previewAssetData.filename }}</div>
                <div style="color: #909399; font-size: 14px;">{{ formatSize(previewAssetData.size) }} | {{ formatDate(previewAssetData.created_at) }}</div>
                <div v-if="previewAssetData.alt_text" style="margin-top: 12px; padding: 12px; background: #f5f7fa; border-radius: 8px;">{{ previewAssetData.alt_text }}</div>
                <div class="asset-tags" style="justify-content: center; margin-top: 12px;">
                    <el-tag v-for="tag in (previewAssetData.tags || [])" :key="tag" size="small">{{ tag }}</el-tag>
                </div>
                <div style="margin-top: 16px; font-size: 13px; color: #606266;">使用次数: {{ previewAssetData.usage_count || 0 }}</div>
            </div>
        </el-dialog>
    </div>
    <script src="vue.global.prod.js"></script>
    <script src="element-plus.full.js"></script>
    <script>
const AssetsApp = {
    data() {
        return {
            currentUser: { username: '' },
            isAdmin: false,
            isLoggedIn: false,
            assets: [],
            allTags: [],
            assetStats: { total: 0, by_type: {} },
            loading: false,
            searchKeyword: '',
            filterType: '',
            filterTag: '',
            showUploadDialog: false,
            showPreviewDialog: false,
            previewAssetData: null,
            uploadFiles: [],
            uploadTags: '',
            uploadAltText: '',
            uploading: false
        }
    },
    methods: {
        handleLogout() { localStorage.removeItem('authToken'); localStorage.removeItem('userRole'); localStorage.removeItem('currentUser'); window.location.href = '/login.html'; },
        redirectToPage(page) { window.location.href = page.startsWith('/') ? page : '/' + page; },
        checkAuth() {
            const token = localStorage.getItem('authToken');
            if (!token) { window.location.href = '/login.html'; return; }
            fetch('/api/auth/me', { headers: { 'Authorization': 'Bearer ' + token } })
                .then(r => r.ok ? r.json() : Promise.reject())
                .then(data => {
                    this.currentUser = data.user;
                    this.isAdmin = data.user.role === 'admin';
                    this.isLoggedIn = true;
                    this.loadAssets();
                    this.loadTags();
                    this.loadStats();
                })
                .catch(() => { localStorage.removeItem('authToken'); localStorage.removeItem('userRole'); localStorage.removeItem('currentUser'); window.location.href = '/login.html'; });
        },
        formatSize(bytes) {
            if (!bytes) return '0 B';
            const units = ['B', 'KB', 'MB', 'GB'];
            let i = 0;
            while (bytes >= 1024 && i < units.length - 1) { bytes /= 1024; i++; }
            return bytes.toFixed(1) + ' ' + units[i];
        },
        formatDate(dateStr) {
            if (!dateStr) return '-';
            return new Date(dateStr).toLocaleDateString('zh-CN');
        },
        getTypeName(type) {
            const map = { 'image': '图片', 'video': '视频', 'document': '文档' };
            return map[type] || type;
        },
        async loadAssets() {
            this.loading = true;
            try {
                const token = localStorage.getItem('authToken');
                let url = '/api/assets?limit=100';
                if (this.filterType) url += '&file_type=' + this.filterType;
                if (this.filterTag) url += '&tag=' + this.filterTag;
                if (this.searchKeyword) url += '&search=' + encodeURIComponent(this.searchKeyword);
                const res = await fetch(url, { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.assets = await res.json();
            } catch (e) { console.error(e); }
            finally { this.loading = false; }
        },
        async loadTags() {
            try {
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/assets/tags', { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.allTags = await res.json();
            } catch (e) { console.error(e); }
        },
        async loadStats() {
            try {
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/assets/counts', { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.assetStats = await res.json();
            } catch (e) { console.error(e); }
        },
        handleFileChange(file, fileList) { this.uploadFiles = fileList; },
        async uploadFiles() {
            if (this.uploadFiles.length === 0) { this.$message.warning('请选择文件'); return; }
            this.uploading = true;
            try {
                const token = localStorage.getItem('authToken');
                for (const fileItem of this.uploadFiles) {
                    const formData = new FormData();
                    formData.append('file', fileItem.raw);
                    if (this.uploadTags) formData.append('tags', this.uploadTags);
                    if (this.uploadAltText) formData.append('alt_text', this.uploadAltText);
                    const res = await fetch('/api/assets/upload', { method: 'POST', headers: { 'Authorization': 'Bearer ' + token }, body: formData });
                    if (!res.ok) throw new Error('上传失败');
                }
                this.$message.success('上传成功');
                this.showUploadDialog = false;
                this.uploadFiles = [];
                this.uploadTags = '';
                this.uploadAltText = '';
                this.loadAssets();
                this.loadStats();
            } catch (e) { this.$message.error(e.message); }
            finally { this.uploading = false; }
        },
        previewAsset(asset) { this.previewAssetData = asset; this.showPreviewDialog = true; },
        async copyUrl(asset) {
            const url = '/content/images/' + asset.filename.split('/').pop();
            navigator.clipboard.writeText(window.location.origin + url).then(() => this.$message.success('链接已复制'));
        },
        async deleteAsset(id) {
            try {
                await this.$confirm('确定删除该素材？', '提示', { type: 'warning' });
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/assets/' + id, { method: 'DELETE', headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) { this.$message.success('删除成功'); this.loadAssets(); this.loadStats(); }
            } catch (e) { if (e !== 'cancel') this.$message.error(e.message || '删除失败'); }
        }
    },
    mounted() {
        this.checkAuth();
    }
};
const app = Vue.createApp(AssetsApp);
app.use(ElementPlus);
if (window.installNavbar) { window.installNavbar(app); }
if (window.installNavigation) { window.installNavigation(app); } else if (window.NavigationComponent) { app.component("navigation-component", window.NavigationComponent); }
app.mount('#app');
    </script>
</body>
</html>
