gongxiangp2/app/admin/page.tsx
chenpei 0c4e61ccfc feat: 系统管理页面完全支持浏览器黑夜模式
- 更新背景色、容器、卡片样式支持dark模式
- 更新所有表格(素材、用户)样式支持dark模式
- 更新标签栏、标题、文本颜色支持dark模式
- 更新分类管理(使用店铺、场景类别)支持dark模式
- 更新部门管理UI支持dark模式
- 更新所有按钮、输入框、模态框支持dark模式
- 更新空状态、加载状态文本颜色

现在系统管理和系统设置页面都完全支持黑夜模式,提升用户体验!
2025-10-27 17:33:13 +08:00

1369 lines
54 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client'
import { useEffect, useState, useCallback } from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import Header from '@/components/Header'
import EditMaterialModal from '@/components/EditMaterialModal'
import { format } from 'date-fns'
interface User {
id: string
email: string
username: string
department: string
role: string
isActive: boolean
canDownload: boolean
createdAt: string
_count: {
materials: number
}
}
interface Material {
id: string
previewUrl: string
productModel: string
categoryName: string
sceneName: string
materialType: string
renderer: string
authorName: string
createdAt: string
user: {
username: string
}
}
interface Category {
id: string
name: string
count: number
}
interface Scene {
id: string
name: string
count: number
}
export default function AdminPage() {
const { data: session, status } = useSession()
const router = useRouter()
const [activeTab, setActiveTab] = useState<'materials' | 'users' | 'categories' | 'departments'>('materials')
const [materials, setMaterials] = useState<Material[]>([])
const [users, setUsers] = useState<User[]>([])
const [categories, setCategories] = useState<Category[]>([])
const [scenes, setScenes] = useState<Scene[]>([])
const [loading, setLoading] = useState(true)
const [editingMaterial, setEditingMaterial] = useState<Material | null>(null)
const [editingCategory, setEditingCategory] = useState<Category | null>(null)
const [editingScene, setEditingScene] = useState<Scene | null>(null)
const [showAddCategoryModal, setShowAddCategoryModal] = useState(false)
const [showAddSceneModal, setShowAddSceneModal] = useState(false)
const [newCategoryName, setNewCategoryName] = useState('')
const [newSceneName, setNewSceneName] = useState('')
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null)
// 编辑用户部门
const [editingUser, setEditingUser] = useState<User | null>(null)
const [departments, setDepartments] = useState<Array<{id: string, name: string}>>([])
const [selectedDepartment, setSelectedDepartment] = useState('')
// 部门管理
const [newDepartmentName, setNewDepartmentName] = useState('')
const [addingDepartment, setAddingDepartment] = useState(false)
// Toast自动隐藏
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000)
return () => clearTimeout(timer)
}
}, [toast])
const showToast = (message: string, type: 'success' | 'error' = 'success') => {
setToast({ message, type })
}
useEffect(() => {
if (status === 'unauthenticated') {
router.push('/login')
return
}
if (status === 'authenticated' && (session.user as any)?.role !== 'ADMIN') {
router.push('/')
return
}
}, [status, session, router])
useEffect(() => {
if (status === 'authenticated') {
fetchData()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [status, activeTab])
const fetchData = async () => {
setLoading(true)
try {
if (activeTab === 'materials') {
const response = await fetch('/api/materials?pageSize=1000')
if (response.ok) {
const data = await response.json()
// 处理新的分页API响应格式
setMaterials(data.materials || data)
}
} else if (activeTab === 'users') {
const response = await fetch('/api/admin/users')
if (response.ok) {
const data = await response.json()
setUsers(data)
}
// 加载部门列表
fetchDepartments()
} else if (activeTab === 'categories') {
const [categoriesRes, scenesRes] = await Promise.all([
fetch('/api/categories'),
fetch('/api/scenes')
])
if (categoriesRes.ok) {
const data = await categoriesRes.json()
setCategories(data)
}
if (scenesRes.ok) {
const data = await scenesRes.json()
setScenes(data)
}
} else if (activeTab === 'departments') {
fetchDepartments()
}
} catch (error) {
console.error('Error fetching data:', error)
} finally {
setLoading(false)
}
}
const fetchDepartments = async () => {
try {
const response = await fetch('/api/departments')
if (response.ok) {
const data = await response.json()
setDepartments(data)
}
} catch (error) {
console.error('Error fetching departments:', error)
}
}
const handleEditUserDepartment = (user: User) => {
setEditingUser(user)
setSelectedDepartment(user.department || '')
}
const handleUpdateUserDepartment = async () => {
if (!editingUser) return
try {
const response = await fetch('/api/admin/users/update-department', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: editingUser.id,
department: selectedDepartment,
}),
})
if (response.ok) {
// 更新本地状态
setUsers(prevUsers =>
prevUsers.map(u =>
u.id === editingUser.id
? { ...u, department: selectedDepartment }
: u
)
)
setEditingUser(null)
setSelectedDepartment('')
showToast('部门更新成功')
} else {
const error = await response.json()
showToast(error.error || '更新失败', 'error')
}
} catch (error) {
console.error('Update department error:', error)
showToast('更新失败,请稍后重试', 'error')
}
}
const handleAddDepartment = async () => {
if (!newDepartmentName.trim()) {
showToast('请输入部门名称', 'error')
return
}
setAddingDepartment(true)
try {
const response = await fetch('/api/departments', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: newDepartmentName.trim() }),
})
if (response.ok) {
await fetchDepartments()
setNewDepartmentName('')
showToast('部门添加成功')
} else {
const error = await response.json()
showToast(error.error || '添加失败', 'error')
}
} catch (error) {
console.error('Add department error:', error)
showToast('添加失败,请稍后重试', 'error')
} finally {
setAddingDepartment(false)
}
}
const handleDeleteDepartment = async (id: string, name: string) => {
if (!confirm(`确定要删除部门"${name}"吗?`)) return
try {
const response = await fetch(`/api/departments?id=${id}`, {
method: 'DELETE',
})
if (response.ok) {
setDepartments(prevDepts => prevDepts.filter(d => d.id !== id))
showToast('部门删除成功')
} else {
const error = await response.json()
showToast(error.error || '删除失败', 'error')
}
} catch (error) {
console.error('Delete department error:', error)
showToast('删除失败,请稍后重试', 'error')
}
}
const handleDeleteMaterial = async (id: string) => {
if (!confirm('确定要删除这个素材吗?')) return
try {
const response = await fetch(`/api/materials?id=${id}`, {
method: 'DELETE',
})
if (response.ok) {
// 直接从本地状态移除
setMaterials(prevMaterials => prevMaterials.filter(m => m.id !== id))
showToast('删除成功')
} else {
showToast('删除失败', 'error')
}
} catch (error) {
console.error('Error deleting material:', error)
showToast('删除失败', 'error')
}
}
const handleDeleteUser = async (id: string) => {
if (!confirm('确定要删除这个用户吗?该用户的所有素材也会被删除。')) return
try {
const response = await fetch(`/api/admin/users?id=${id}`, {
method: 'DELETE',
})
if (response.ok) {
// 直接从本地状态移除
setUsers(prevUsers => prevUsers.filter(u => u.id !== id))
showToast('删除成功')
} else {
const data = await response.json()
showToast(data.error || '删除失败', 'error')
}
} catch (error) {
console.error('Error deleting user:', error)
showToast('删除失败', 'error')
}
}
const handleToggleDownload = async (userId: string, currentCanDownload: boolean) => {
const action = currentCanDownload ? '关闭' : '开启'
if (!confirm(`确定要${action}该用户的下载权限吗?`)) return
try {
const response = await fetch('/api/admin/users/toggle-download', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId }),
})
if (response.ok) {
// 直接更新本地状态,避免重新加载整个列表
setUsers(prevUsers =>
prevUsers.map(user =>
user.id === userId
? { ...user, canDownload: !currentCanDownload }
: user
)
)
showToast(`下载权限已${action}`)
} else {
const data = await response.json()
showToast(data.error || '操作失败', 'error')
}
} catch (error) {
console.error('Error toggling download permission:', error)
showToast('操作失败', 'error')
}
}
const handleToggleActive = async (userId: string, currentStatus: boolean) => {
const action = currentStatus ? '禁用' : '激活'
if (!confirm(`确定要${action}这个用户吗?`)) return
try {
const response = await fetch('/api/admin/users/toggle-active', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId,
isActive: !currentStatus,
}),
})
if (response.ok) {
// 直接更新本地状态
setUsers(prevUsers =>
prevUsers.map(user =>
user.id === userId
? { ...user, isActive: !currentStatus }
: user
)
)
showToast(`${action}成功`)
} else {
const data = await response.json()
showToast(data.error || `${action}失败`, 'error')
}
} catch (error) {
console.error('Toggle active error:', error)
showToast(`${action}失败`, 'error')
}
}
const handleUpdateCategory = async (id: string, newName: string) => {
if (!newName.trim()) {
showToast('分类名称不能为空', 'error')
return
}
try {
const response = await fetch('/api/categories', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, name: newName.trim() }),
})
if (response.ok) {
// 直接更新本地状态
setCategories(prevCategories =>
prevCategories.map(cat =>
cat.id === id ? { ...cat, name: newName.trim() } : cat
)
)
setEditingCategory(null)
showToast('修改成功')
} else {
const data = await response.json()
showToast(data.error || '修改失败', 'error')
}
} catch (error) {
console.error('Error updating category:', error)
showToast('修改失败', 'error')
}
}
const handleUpdateScene = async (id: string, newName: string) => {
if (!newName.trim()) {
showToast('场景名称不能为空', 'error')
return
}
try {
const response = await fetch('/api/scenes', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, name: newName.trim() }),
})
if (response.ok) {
// 直接更新本地状态
setScenes(prevScenes =>
prevScenes.map(scene =>
scene.id === id ? { ...scene, name: newName.trim() } : scene
)
)
setEditingScene(null)
showToast('修改成功')
} else {
const data = await response.json()
showToast(data.error || '修改失败', 'error')
}
} catch (error) {
console.error('Error updating scene:', error)
showToast('修改失败', 'error')
}
}
const handleDeleteCategory = async (id: string) => {
if (!confirm('确定要删除这个使用店铺分类吗?')) return
try {
const response = await fetch(`/api/categories?id=${id}`, {
method: 'DELETE',
})
if (response.ok) {
// 直接从本地状态移除
setCategories(prevCategories => prevCategories.filter(cat => cat.id !== id))
showToast('删除成功')
} else {
const data = await response.json()
showToast(data.error || '删除失败', 'error')
}
} catch (error) {
console.error('Error deleting category:', error)
showToast('删除失败', 'error')
}
}
const handleDeleteScene = async (id: string) => {
if (!confirm('确定要删除这个场景类别吗?')) return
try {
const response = await fetch(`/api/scenes?id=${id}`, {
method: 'DELETE',
})
if (response.ok) {
// 直接从本地状态移除
setScenes(prevScenes => prevScenes.filter(scene => scene.id !== id))
showToast('删除成功')
} else {
const data = await response.json()
showToast(data.error || '删除失败', 'error')
}
} catch (error) {
console.error('Error deleting scene:', error)
showToast('删除失败', 'error')
}
}
const handleSetRole = async (userId: string, currentRole: string) => {
const newRole = currentRole === 'ADMIN' ? 'USER' : 'ADMIN'
const action = newRole === 'ADMIN' ? '设置为管理员' : '取消管理员权限'
if (!confirm(`确定要${action}吗?`)) return
try {
const response = await fetch('/api/admin/users/set-role', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId,
role: newRole,
}),
})
if (response.ok) {
// 直接更新本地状态
setUsers(prevUsers =>
prevUsers.map(user =>
user.id === userId
? { ...user, role: newRole }
: user
)
)
showToast(`${action}成功`)
} else {
const data = await response.json()
showToast(data.error || `${action}失败`, 'error')
}
} catch (error) {
console.error('Set role error:', error)
showToast(`${action}失败`, 'error')
}
}
const handleAddCategory = async () => {
if (!newCategoryName.trim()) {
showToast('分类名称不能为空', 'error')
return
}
try {
const response = await fetch('/api/categories', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: newCategoryName.trim() }),
})
if (response.ok) {
const data = await response.json()
// 添加到本地状态
setCategories(prevCategories => [...prevCategories, { id: data.id, name: newCategoryName.trim(), count: 0 }])
setShowAddCategoryModal(false)
setNewCategoryName('')
showToast('添加成功')
} else {
const data = await response.json()
showToast(data.error || '添加失败', 'error')
}
} catch (error) {
console.error('Error adding category:', error)
showToast('添加失败', 'error')
}
}
const handleAddScene = async () => {
if (!newSceneName.trim()) {
showToast('场景名称不能为空', 'error')
return
}
try {
const response = await fetch('/api/scenes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: newSceneName.trim() }),
})
if (response.ok) {
const data = await response.json()
// 添加到本地状态
setScenes(prevScenes => [...prevScenes, { id: data.id, name: newSceneName.trim(), count: 0 }])
setShowAddSceneModal(false)
setNewSceneName('')
showToast('添加成功')
} else {
const data = await response.json()
showToast(data.error || '添加失败', 'error')
}
} catch (error) {
console.error('Error adding scene:', error)
showToast('添加失败', 'error')
}
}
if (status === 'loading' || loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-xl text-gray-600 dark:text-gray-400">加载中...</div>
</div>
)
}
if (!session || (session.user as any)?.role !== 'ADMIN') {
return null
}
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<Header session={session} />
{/* Toast通知 */}
{toast && (
<div className={`fixed top-20 right-4 z-50 px-6 py-3 rounded-lg shadow-lg ${
toast.type === 'success'
? 'bg-green-500 text-white'
: 'bg-red-500 text-white'
} animate-fade-in`}>
{toast.message}
</div>
)}
<main className="container mx-auto px-4 py-8 max-w-7xl">
<div className="flex items-center justify-between mb-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">系统管理</h1>
<button
onClick={() => router.push('/admin/settings')}
className="btn-primary flex items-center gap-2"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
</svg>
外观设置
</button>
</div>
{/* Tabs */}
<div className="flex space-x-4 border-b border-gray-200 dark:border-gray-700 mb-8">
<button
type="button"
onClick={() => setActiveTab('materials')}
className={`pb-4 px-4 font-medium transition-colors ${
activeTab === 'materials'
? 'text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
}`}
>
素材管理
</button>
<button
type="button"
onClick={() => setActiveTab('users')}
className={`pb-4 px-4 font-medium transition-colors ${
activeTab === 'users'
? 'text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
}`}
>
用户管理
</button>
<button
type="button"
onClick={() => setActiveTab('categories')}
className={`pb-4 px-4 font-medium transition-colors ${
activeTab === 'categories'
? 'text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
}`}
>
分类管理
</button>
<button
type="button"
onClick={() => setActiveTab('departments')}
className={`pb-4 px-4 font-medium transition-colors ${
activeTab === 'departments'
? 'text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
}`}
>
部门管理
</button>
</div>
{/* Materials Table */}
{activeTab === 'materials' && (
<div className="card-apple overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
预览图
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
商品型号
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
场景名称
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
作者
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
上传时间
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
操作
</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{materials.map((material) => (
<tr key={material.id}>
<td className="px-6 py-4 whitespace-nowrap">
<img
src={material.previewUrl}
alt={material.sceneName}
className="w-16 h-16 object-cover rounded-lg"
/>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900 dark:text-white">
{material.productModel}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900 dark:text-white">
{material.sceneName}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900 dark:text-white">
{material.authorName}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
@{material.user.username}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{format(new Date(material.createdAt), 'yyyy-MM-dd HH:mm')}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center space-x-3">
<button
onClick={() => setEditingMaterial(material)}
className="text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white font-medium"
>
编辑
</button>
<button
onClick={() => handleDeleteMaterial(material.id)}
className="text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white font-medium"
>
删除
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{materials.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无素材
</div>
)}
</div>
)}
{/* Users Table */}
{activeTab === 'users' && (
<div className="card-apple overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
用户名
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
邮箱
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
部门
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
角色
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
状态
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
下载权限
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
素材数量
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
注册时间
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
操作
</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{users.map((user) => (
<tr key={user.id}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900 dark:text-white">
{user.username}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900 dark:text-white">{user.email}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-500 dark:text-gray-400">
{user.department || '-'}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.role === 'ADMIN'
? 'bg-purple-100 text-purple-800'
: 'bg-green-100 text-green-800'
}`}
>
{user.role === 'ADMIN' ? '管理员' : '用户'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.isActive
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}
>
{user.isActive ? '已激活' : '未激活'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.canDownload
? 'bg-blue-100 text-blue-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{user.canDownload ? '允许下载' : '禁止下载'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{user._count.materials}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{format(new Date(user.createdAt), 'yyyy-MM-dd')}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center space-x-3">
{user.email !== session?.user?.email && (
<>
<button
onClick={() => handleEditUserDepartment(user)}
className="text-blue-600 hover:text-blue-800 dark:text-blue-400 font-medium"
title="编辑部门"
>
编辑部门
</button>
<button
onClick={() => handleSetRole(user.id, user.role)}
className={`font-medium ${
user.role === 'ADMIN'
? 'text-orange-600 hover:text-orange-800 dark:text-orange-400'
: 'text-purple-600 hover:text-purple-800 dark:text-purple-400'
}`}
>
{user.role === 'ADMIN' ? '取消管理员' : '设为管理员'}
</button>
<button
onClick={() => handleToggleActive(user.id, user.isActive)}
className="text-gray-700 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100 font-medium"
>
{user.isActive ? '禁用' : '激活'}
</button>
{user.role !== 'ADMIN' && (
<button
onClick={() => handleToggleDownload(user.id, user.canDownload)}
className={`font-medium ${
user.canDownload
? 'text-yellow-600 hover:text-yellow-800 dark:text-yellow-400'
: 'text-blue-600 hover:text-blue-800 dark:text-blue-400'
}`}
>
{user.canDownload ? '关闭下载' : '开启下载'}
</button>
)}
<button
onClick={() => handleDeleteUser(user.id)}
className="text-red-600 hover:text-red-800 dark:text-red-400 font-medium"
>
删除
</button>
</>
)}
{user.email === session?.user?.email && (
<span className="text-xs text-gray-500 dark:text-gray-400 italic">
当前账号
</span>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{users.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无用户
</div>
)}
</div>
)}
{/* Categories Management */}
{activeTab === 'categories' && (
<div className="space-y-8">
{/* 使用店铺分类 */}
<div className="card-apple">
<div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">使用店铺分类</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">管理所有使用店铺分类名称</p>
</div>
<button
onClick={() => setShowAddCategoryModal(true)}
className="px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white text-sm rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
新增店铺
</button>
</div>
<div className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{categories.map((category) => (
<div
key={category.id}
className="border border-gray-200 dark:border-gray-600 rounded-lg p-4 hover:shadow-md transition-shadow"
>
{editingCategory?.id === category.id ? (
<div className="space-y-3">
<input
type="text"
defaultValue={category.name}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-gray-400 outline-none"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleUpdateCategory(category.id, e.currentTarget.value)
} else if (e.key === 'Escape') {
setEditingCategory(null)
}
}}
autoFocus
/>
<div className="flex gap-2">
<button
onClick={(e) => {
const input = e.currentTarget.parentElement?.previousElementSibling as HTMLInputElement
handleUpdateCategory(category.id, input.value)
}}
className="flex-1 px-3 py-1.5 bg-gray-900 text-white text-sm rounded-lg hover:bg-gray-800 transition-colors"
>
保存
</button>
<button
onClick={() => setEditingCategory(null)}
className="flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 text-sm rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
</div>
</div>
) : (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-medium text-gray-900 dark:text-white">
{category.name}
</h3>
<span className="text-xs text-gray-500 bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded-full">
{category.count} 个素材
</span>
</div>
<div className="flex gap-2">
<button
onClick={() => setEditingCategory(category)}
className="flex-1 px-3 py-1.5 text-gray-700 dark:text-gray-300 text-sm border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
编辑
</button>
<button
onClick={() => handleDeleteCategory(category.id)}
className="flex-1 px-3 py-1.5 text-red-600 dark:text-red-400 text-sm border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
>
删除
</button>
</div>
</div>
)}
</div>
))}
</div>
{categories.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无使用店铺分类
</div>
)}
</div>
</div>
{/* 场景类别 */}
<div className="card-apple">
<div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">场景类别</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">管理所有场景类别名称</p>
</div>
<button
onClick={() => setShowAddSceneModal(true)}
className="px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white text-sm rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
新增场景
</button>
</div>
<div className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{scenes.map((scene) => (
<div
key={scene.id}
className="border border-gray-200 dark:border-gray-600 rounded-lg p-4 hover:shadow-md transition-shadow"
>
{editingScene?.id === scene.id ? (
<div className="space-y-3">
<input
type="text"
defaultValue={scene.name}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-gray-400 outline-none"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleUpdateScene(scene.id, e.currentTarget.value)
} else if (e.key === 'Escape') {
setEditingScene(null)
}
}}
autoFocus
/>
<div className="flex gap-2">
<button
onClick={(e) => {
const input = e.currentTarget.parentElement?.previousElementSibling as HTMLInputElement
handleUpdateScene(scene.id, input.value)
}}
className="flex-1 px-3 py-1.5 bg-gray-900 text-white text-sm rounded-lg hover:bg-gray-800 transition-colors"
>
保存
</button>
<button
onClick={() => setEditingScene(null)}
className="flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 text-sm rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
</div>
</div>
) : (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-medium text-gray-900 dark:text-white">
{scene.name}
</h3>
<span className="text-xs text-gray-500 bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded-full">
{scene.count} 个素材
</span>
</div>
<div className="flex gap-2">
<button
onClick={() => setEditingScene(scene)}
className="flex-1 px-3 py-1.5 text-gray-700 dark:text-gray-300 text-sm border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
编辑
</button>
<button
onClick={() => handleDeleteScene(scene.id)}
className="flex-1 px-3 py-1.5 text-red-600 dark:text-red-400 text-sm border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
>
删除
</button>
</div>
</div>
)}
</div>
))}
</div>
{scenes.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无场景类别
</div>
)}
</div>
</div>
</div>
)}
{/* Departments Tab */}
{activeTab === 'departments' && (
<div className="card-apple">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">部门管理</h2>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
管理系统中的部门列表,用户注册时可以选择所属部门
</p>
</div>
</div>
</div>
<div className="p-6 space-y-4">
{/* 添加部门 */}
<div className="flex gap-2">
<input
type="text"
value={newDepartmentName}
onChange={(e) => setNewDepartmentName(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleAddDepartment()
}
}}
placeholder="输入部门名称(例如:设计部、技术部等)"
className="flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-600 outline-none transition-all"
disabled={addingDepartment}
/>
<button
onClick={handleAddDepartment}
disabled={addingDepartment}
className="btn-primary whitespace-nowrap disabled:opacity-50"
>
{addingDepartment ? '添加中...' : '添加部门'}
</button>
</div>
{/* 部门列表 */}
<div className="mt-4">
{departments.length === 0 ? (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
暂无部门,请添加第一个部门
</div>
) : (
<div className="space-y-2">
{departments.map((dept) => (
<div
key={dept.id}
className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"
>
<span className="text-gray-900 dark:text-white font-medium">
{dept.name}
</span>
<button
onClick={() => handleDeleteDepartment(dept.id, dept.name)}
className="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 transition-colors"
title="删除部门"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
))}
</div>
)}
</div>
</div>
</div>
)}
</main>
{/* Edit Material Modal */}
{editingMaterial && (
<EditMaterialModal
material={editingMaterial}
onClose={() => setEditingMaterial(null)}
onSuccess={async () => {
setEditingMaterial(null)
// 只重新获取素材列表,不刷新其他数据
if (activeTab === 'materials') {
try {
const response = await fetch('/api/materials?pageSize=1000')
if (response.ok) {
const data = await response.json()
setMaterials(data.materials || data)
}
} catch (error) {
console.error('Error fetching materials:', error)
}
}
showToast('修改成功')
}}
/>
)}
{/* Add Category Modal */}
{showAddCategoryModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
新增使用店铺分类
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
分类名称
</label>
<input
type="text"
value={newCategoryName}
onChange={(e) => setNewCategoryName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddCategory()
} else if (e.key === 'Escape') {
setShowAddCategoryModal(false)
setNewCategoryName('')
}
}}
placeholder="请输入店铺名称"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:ring-2 focus:ring-gray-400 outline-none"
autoFocus
/>
</div>
<div className="flex gap-3 justify-end">
<button
onClick={() => {
setShowAddCategoryModal(false)
setNewCategoryName('')
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
<button
onClick={handleAddCategory}
className="px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors"
>
确定添加
</button>
</div>
</div>
</div>
</div>
)}
{/* Add Scene Modal */}
{showAddSceneModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
新增场景类别
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
类别名称
</label>
<input
type="text"
value={newSceneName}
onChange={(e) => setNewSceneName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddScene()
} else if (e.key === 'Escape') {
setShowAddSceneModal(false)
setNewSceneName('')
}
}}
placeholder="请输入场景类别名称"
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:ring-2 focus:ring-gray-400 outline-none"
autoFocus
/>
</div>
<div className="flex gap-3 justify-end">
<button
onClick={() => {
setShowAddSceneModal(false)
setNewSceneName('')
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
<button
onClick={handleAddScene}
className="px-4 py-2 bg-gray-900 dark:bg-gray-700 text-white rounded-lg hover:bg-gray-800 dark:hover:bg-gray-600 transition-colors"
>
确定添加
</button>
</div>
</div>
</div>
</div>
)}
{/* 编辑用户部门模态框 */}
{editingUser && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
编辑用户部门
</h3>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
用户:{editingUser.username} ({editingUser.email})
</p>
</div>
<div className="p-6 space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
选择部门
</label>
<select
value={selectedDepartment}
onChange={(e) => setSelectedDepartment(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
>
<option value="">-- 未分配部门 --</option>
{departments.map((dept) => (
<option key={dept.id} value={dept.name}>
{dept.name}
</option>
))}
</select>
</div>
{departments.length === 0 && (
<div className="text-sm text-yellow-600 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-3">
⚠️ 暂无部门,请先在系统设置中添加部门
</div>
)}
</div>
<div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex gap-3 justify-end">
<button
onClick={() => {
setEditingUser(null)
setSelectedDepartment('')
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
>
取消
</button>
<button
onClick={handleUpdateUserDepartment}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
>
保存
</button>
</div>
</div>
</div>
)}
</div>
)
}