数据结构优化

This commit is contained in:
李琦
2026-01-19 20:21:09 +08:00
parent 68c4c6df1c
commit 7e918cedd4
39 changed files with 3703 additions and 824 deletions

View File

@@ -234,13 +234,22 @@ const menuItems = ref<MenuItem[]>([
{ title: '角色管理', path: '/admin/roles', icon: '🔒' }
]
},
{
title: '附件管理',
icon: '📎',
isOpen: false,
children: [
{ title: '附件库', path: '/admin/attachments', icon: '📦' },
{ title: '附件分类管理', path: '/admin/attachment-categories', icon: '📂' },
{ title: 'OSS配置', path: '/admin/oss-configs', icon: '☁️' }
]
},
{
title: '系统设置',
icon: '⚙️',
isOpen: false,
children: [
{ title: '全局配置', path: '/admin/settings', icon: '🛠️' },
{ title: '附件管理', path: '/admin/attachments', icon: '📎' },
{ title: '操作日志', path: '/admin/logs', icon: '📋' }
]
}

View File

@@ -0,0 +1,204 @@
<template>
<div v-if="show" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="handleClose">
<div class="admin-card max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-serif italic text-white">附件详情</h2>
<button @click="handleClose" class="text-white/40 hover:text-white transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div v-if="attachment" class="space-y-6">
<!-- 图片预览 -->
<div v-if="attachment.fileType === 'image'" class="w-full rounded-lg overflow-hidden bg-white/5">
<img :src="attachment.fileUrl" :alt="attachment.originalName" class="w-full h-auto max-h-96 object-contain" />
</div>
<!-- 文件信息 -->
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件名</label>
<p class="text-white">{{ attachment.originalName }}</p>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件大小</label>
<p class="text-white">{{ formatFileSize(attachment.fileSize) }}</p>
</div>
<div>
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件类型</label>
<p class="text-white">{{ getFileTypeLabel(attachment.fileType) }}</p>
</div>
</div>
<div v-if="attachment.mimeType">
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">MIME类型</label>
<p class="text-white font-mono text-sm">{{ attachment.mimeType }}</p>
</div>
<div>
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">存储类型</label>
<p class="text-white">{{ getStorageTypeLabel(attachment.storageType) }}</p>
</div>
<div>
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">分类</label>
<CustomSelect
v-model="localCategoryId"
:options="categoryOptions"
placeholder="无分类"
/>
</div>
<div>
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件URL</label>
<div class="flex gap-2">
<input
type="text"
:value="attachment.fileUrl"
readonly
class="admin-input flex-1 font-mono text-sm"
/>
<button
@click="handleCopyUrl"
class="admin-btn-secondary px-4 whitespace-nowrap"
>
复制
</button>
</div>
</div>
<div v-if="attachment.createdAt" class="text-xs text-art-muted">
创建时间: {{ formatDate(attachment.createdAt) }}
</div>
</div>
<!-- 操作按钮 -->
<div class="flex gap-3 pt-4 border-t border-white/10">
<button @click="handleClose" class="admin-btn-secondary flex-1">
取消
</button>
<button @click="handleSave" :disabled="saving" class="admin-btn-primary flex-1">
{{ saving ? '保存中...' : '保存' }}
</button>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import CustomSelect from '../CustomSelect.vue'
interface Attachment {
id: number
originalName: string
fileUrl: string
fileSize: number
fileType: string
categoryId?: number
mimeType?: string
storageType?: string
createdAt?: string
}
interface Category {
id: number
name: string
}
interface Props {
show: boolean
attachment: Attachment | null
categories: Category[]
}
const props = defineProps<Props>()
const emit = defineEmits<{
'update:show': [value: boolean]
'save': [data: { categoryId: number | null }]
'copy-url': [url: string]
}>()
const localCategoryId = ref<number>(0)
const saving = ref(false)
// 计算属性:分类选项
const categoryOptions = computed(() => {
return [
{ value: 0, label: '无分类' },
...props.categories.map(cat => ({ value: cat.id, label: cat.name }))
]
})
// 监听attachment变化更新本地分类ID
watch(() => props.attachment, (newAttachment) => {
if (newAttachment) {
localCategoryId.value = newAttachment.categoryId || 0
}
}, { immediate: true })
const handleClose = () => {
emit('update:show', false)
}
const handleSave = () => {
saving.value = true
const categoryId = localCategoryId.value === 0 ? null : localCategoryId.value
emit('save', { categoryId })
// saving状态由父组件控制
}
const handleCopyUrl = () => {
if (props.attachment) {
emit('copy-url', props.attachment.fileUrl)
}
}
const formatFileSize = (bytes: number): string => {
if (bytes < 1024) return bytes + ' B'
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}
const getFileTypeLabel = (fileType: string): string => {
const labels: Record<string, string> = {
image: '图片',
video: '视频',
document: '文档',
other: '其他'
}
return labels[fileType] || fileType
}
const getStorageTypeLabel = (storageType?: string): string => {
const labels: Record<string, string> = {
local: '本地存储',
qcloud: '腾讯云COS',
aliyun: '阿里云OSS',
qiniu: '七牛云'
}
return labels[storageType || 'local'] || storageType || '本地存储'
}
const formatDate = (timestamp: string | number): string => {
const date = new Date(typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000)
return date.toLocaleString('zh-CN')
}
// 暴露saving状态给父组件
defineExpose({
saving
})
</script>
<style scoped>
/* 使用全局admin样式无需额外样式 */
</style>

View File

@@ -0,0 +1,386 @@
<template>
<div class="image-upload">
<!-- 单个上传模式 -->
<template v-if="!multiple">
<div
v-if="!imageUrl"
@click="triggerFileInput"
@dragover.prevent="handleDragOver"
@dragenter.prevent="handleDragEnter"
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
class="upload-area border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors"
:class="[
isDragging ? 'border-art-accent bg-art-accent/5' : 'border-white/20 hover:border-art-accent/50',
disabled ? 'opacity-50 cursor-not-allowed' : ''
]"
>
<input
ref="fileInput"
type="file"
:accept="accept"
:multiple="false"
@change="handleFileSelect"
class="hidden"
:disabled="disabled"
/>
<div class="space-y-3">
<div class="w-12 h-12 mx-auto flex items-center justify-center text-art-muted">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
</div>
<p class="text-sm text-art-muted">点击或拖拽图片到此处上传</p>
<p class="text-xs text-art-muted/50">支持 JPGPNGGIF 格式</p>
</div>
</div>
<div v-else class="image-preview relative group">
<img :src="imageUrl" alt="Preview" class="w-full h-auto rounded-lg max-h-64 object-contain bg-white/5" />
<div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center gap-2">
<button
@click.stop="removeImage"
class="px-4 py-2 bg-red-500/80 text-white rounded hover:bg-red-500 transition-colors text-sm"
:disabled="disabled"
>
删除
</button>
<button
@click.stop="triggerFileInput"
class="px-4 py-2 bg-art-accent text-black rounded hover:opacity-90 transition-colors text-sm"
:disabled="disabled"
>
更换
</button>
</div>
</div>
<div v-if="uploading" class="mt-4 text-center">
<div class="inline-flex items-center gap-2 text-art-accent">
<div class="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-art-accent"></div>
<span class="text-sm">上传中...</span>
</div>
</div>
<div v-if="error" class="mt-4 text-center text-red-400 text-sm">
{{ error }}
</div>
</template>
<!-- 批量上传模式 -->
<template v-else>
<div class="space-y-4">
<!-- 图片列表 -->
<div v-if="imageUrls.length > 0" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
<div
v-for="(url, index) in imageUrls"
:key="index"
class="image-item relative group aspect-square rounded-lg overflow-hidden bg-white/5 border border-white/10"
>
<img :src="url" :alt="`Image ${index + 1}`" class="w-full h-full object-cover" />
<div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
<button
@click="removeImage(index)"
class="px-3 py-1.5 bg-red-500/80 text-white rounded hover:bg-red-500 transition-colors text-xs"
:disabled="disabled"
>
删除
</button>
</div>
<div class="absolute top-2 left-2 bg-black/50 text-white text-xs px-2 py-1 rounded">
{{ index + 1 }}
</div>
</div>
</div>
<!-- 上传区域 -->
<div
v-if="imageUrls.length < (maxCount || Infinity)"
@click="triggerFileInput"
@dragover.prevent="handleDragOver"
@dragenter.prevent="handleDragEnter"
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
class="upload-area border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors"
:class="[
isDragging ? 'border-art-accent bg-art-accent/5' : 'border-white/20 hover:border-art-accent/50',
disabled ? 'opacity-50 cursor-not-allowed' : ''
]"
>
<input
ref="fileInput"
type="file"
:accept="accept"
:multiple="true"
@change="handleFileSelect"
class="hidden"
:disabled="disabled"
/>
<div class="space-y-2">
<div class="w-10 h-10 mx-auto flex items-center justify-center text-art-muted">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
</div>
<p class="text-sm text-art-muted">点击或拖拽图片到此处上传</p>
<p class="text-xs text-art-muted/50">
{{ maxCount ? `最多上传 ${maxCount} 张,已上传 ${imageUrls.length}` : `已上传 ${imageUrls.length}` }}
</p>
</div>
</div>
<!-- 上传进度 -->
<div v-if="uploadingCount > 0" class="mt-4 text-center">
<div class="inline-flex items-center gap-2 text-art-accent">
<div class="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-art-accent"></div>
<span class="text-sm">正在上传 {{ uploadingCount }} 张图片...</span>
</div>
</div>
<!-- 错误提示 -->
<div v-if="error" class="mt-4 text-center text-red-400 text-sm">
{{ error }}
</div>
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useToast } from '../../composables/useToast'
import { API_BASE } from '../../services/api'
const props = withDefaults(defineProps<{
modelValue?: string | string[]
multiple?: boolean
maxCount?: number
categoryId?: number
accept?: string
disabled?: boolean
}>(), {
multiple: false,
accept: 'image/*',
disabled: false
})
const emit = defineEmits<{
'update:modelValue': [value: string | string[]]
}>()
const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
const uploadingCount = ref(0)
const error = ref('')
const isDragging = ref(false)
const toast = useToast()
// 单个模式的值
const imageUrl = computed({
get: () => {
if (props.multiple) return ''
return (props.modelValue as string) || ''
},
set: (val: string) => {
if (!props.multiple) {
emit('update:modelValue', val)
}
}
})
// 批量模式的值
const imageUrls = computed({
get: () => {
if (!props.multiple) return []
const value = props.modelValue
if (Array.isArray(value)) {
return value
}
return value ? [value] : []
},
set: (val: string[]) => {
if (props.multiple) {
emit('update:modelValue', val)
}
}
})
const triggerFileInput = () => {
if (props.disabled) return
fileInput.value?.click()
}
const handleDragOver = (e: DragEvent) => {
if (props.disabled) return
e.preventDefault()
isDragging.value = true
}
const handleDragEnter = (e: DragEvent) => {
if (props.disabled) return
e.preventDefault()
isDragging.value = true
}
const handleDragLeave = (e: DragEvent) => {
if (props.disabled) return
e.preventDefault()
isDragging.value = false
}
const handleDrop = (e: DragEvent) => {
if (props.disabled) return
e.preventDefault()
isDragging.value = false
if (e.dataTransfer?.files) {
const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'))
if (files.length > 0) {
if (props.multiple) {
handleMultipleFiles(files)
} else {
uploadFile(files[0])
}
}
}
}
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement
if (target.files && target.files.length > 0) {
const files = Array.from(target.files).filter(file => file.type.startsWith('image/'))
if (files.length > 0) {
if (props.multiple) {
handleMultipleFiles(files)
} else {
uploadFile(files[0])
}
}
}
// 清空input允许重复选择同一文件
if (target) {
target.value = ''
}
}
const handleMultipleFiles = async (files: File[]) => {
if (props.maxCount && imageUrls.value.length + files.length > props.maxCount) {
error.value = `最多只能上传 ${props.maxCount} 张图片`
toast.showToast(error.value, 'error')
return
}
error.value = ''
uploadingCount.value = files.length
const uploadPromises = files.map(file => uploadSingleFile(file))
try {
const results = await Promise.all(uploadPromises)
const successfulUrls = results.filter(url => url !== null) as string[]
if (successfulUrls.length > 0) {
const newUrls = [...imageUrls.value, ...successfulUrls]
imageUrls.value = newUrls
toast.showToast(`成功上传 ${successfulUrls.length} 张图片`, 'success')
}
} catch (err) {
console.error('Batch upload error:', err)
} finally {
uploadingCount.value = 0
}
}
const uploadFile = async (file: File) => {
if (!file.type.startsWith('image/')) {
error.value = '请选择图片文件'
toast.showToast(error.value, 'error')
return
}
uploading.value = true
error.value = ''
try {
const url = await uploadSingleFile(file)
if (url) {
imageUrl.value = url
toast.showToast('图片上传成功', 'success')
}
} catch (err: any) {
error.value = err.message || '上传失败,请重试'
toast.showToast(error.value, 'error')
} finally {
uploading.value = false
}
}
const uploadSingleFile = async (file: File): Promise<string | null> => {
try {
const formData = new FormData()
formData.append('file', file)
if (props.categoryId) {
formData.append('categoryId', props.categoryId.toString())
}
formData.append('storageType', 'local')
const token = localStorage.getItem('token')
const response = await fetch(`${API_BASE}/admin/attachments/upload`, {
method: 'POST',
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {})
},
body: formData
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.message || '上传失败')
}
const data = await response.json()
return data.result.fileUrl
} catch (err: any) {
console.error('Upload error:', err)
throw err
}
}
const removeImage = (index?: number) => {
if (props.disabled) return
if (props.multiple && typeof index === 'number') {
const newUrls = [...imageUrls.value]
newUrls.splice(index, 1)
imageUrls.value = newUrls
} else {
imageUrl.value = ''
if (fileInput.value) {
fileInput.value.value = ''
}
}
}
</script>
<style scoped>
.upload-area {
min-height: 120px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
}
.image-item {
transition: transform 0.2s;
}
.image-item:hover {
transform: scale(1.02);
}
</style>

View File

@@ -21,10 +21,11 @@
+ 新建分类
</button>
</div>
<select v-model="selectedCategoryId" class="admin-input">
<option :value="0">请选择分类</option>
<option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
</select>
<CustomSelect
v-model="selectedCategoryId"
:options="categoryOptions"
placeholder="请选择分类"
/>
<!-- Quick Create Category -->
<div v-if="showCreateCategory" class="admin-card p-3 space-y-2">
@@ -49,10 +50,11 @@
+ 新建专栏
</button>
</div>
<select v-model="selectedColumnId" class="admin-input">
<option :value="0">不选择专栏</option>
<option v-for="col in columns" :key="col.id" :value="col.id">{{ col.name }}</option>
</select>
<CustomSelect
v-model="selectedColumnId"
:options="columnOptions"
placeholder="不选择专栏"
/>
<!-- Quick Create Column -->
<div v-if="showCreateColumn" class="admin-card p-3 space-y-2">
@@ -132,7 +134,7 @@
</template>
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ref, watch, onMounted, computed } from 'vue'
import {
fetchCategories,
fetchColumns,
@@ -147,6 +149,7 @@ import {
Post
} from '../../services/api'
import { useToast } from '../../composables/useToast'
import CustomSelect from '../CustomSelect.vue'
const props = defineProps<{
isOpen: boolean
@@ -178,6 +181,22 @@ const newTag = ref({ name: '', slug: '' })
const saving = ref(false)
// 计算属性:分类选项
const categoryOptions = computed(() => {
return [
{ value: 0, label: '请选择分类' },
...categories.value.map(cat => ({ value: cat.id, label: cat.name }))
]
})
// 计算属性:专栏选项
const columnOptions = computed(() => {
return [
{ value: 0, label: '不选择专栏' },
...columns.value.map(col => ({ value: col.id, label: col.name }))
]
})
const close = () => {
emit('update:isOpen', false)
showCreateCategory.value = false