This commit is contained in:
2026-02-11 22:42:37 +08:00
parent e265bcc28d
commit b0ae1bb68c
8 changed files with 1387 additions and 574 deletions
+1 -1
View File
@@ -45,7 +45,7 @@ public function getAll()
return response()->json([ return response()->json([
'code' => 200, 'code' => 200,
'message' => 'success', 'message' => 'success',
'data' => ['list' => $result], 'data' => $result,
]); ]);
} }
+8
View File
@@ -88,6 +88,14 @@ public function hasRole(string $roleCode): bool
return $this->roles()->where('code', $roleCode)->exists(); return $this->roles()->where('code', $roleCode)->exists();
} }
/**
* 判断用户是否为超级管理员
*/
public function isSuperAdmin(): bool
{
return $this->hasRole('super_admin');
}
/** /**
* 获取 JWT 标识符 * 获取 JWT 标识符
* *
+215 -200
View File
@@ -9,237 +9,252 @@
class AuthService class AuthService
{ {
protected $permissionService; protected $permissionService;
public function __construct(PermissionService $permissionService) public function __construct(PermissionService $permissionService)
{ {
$this->permissionService = $permissionService; $this->permissionService = $permissionService;
} }
/** /**
* 管理员登录 * 管理员登录
*/ */
public function login(array $credentials): array public function login(array $credentials): array
{ {
$user = User::where('username', $credentials['username'])->first(); $user = User::where('username', $credentials['username'])->first();
if (!$user || !Hash::check($credentials['password'], $user->password)) { if (!$user || !Hash::check($credentials['password'], $user->password)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'username' => ['用户名或密码错误'], 'username' => ['用户名或密码错误'],
]); ]);
} }
if ($user->status !== 1) { if ($user->status !== 1) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'username' => ['账号已被禁用'], 'username' => ['账号已被禁用'],
]); ]);
} }
// 更新登录信息 // 更新登录信息
$user->update([ $user->update([
'last_login_at' => now(), 'last_login_at' => now(),
'last_login_ip' => request()->ip(), 'last_login_ip' => request()->ip(),
]); ]);
// 生成token // 生成token
$token = auth('admin')->login($user); $token = auth('admin')->login($user);
// 获取用户菜单 // 获取用户菜单
$menu = $this->getUserMenu($user); $menu = $this->getUserMenu($user);
// 获取用户权限列表 // 获取用户权限列表
$permissions = $this->getUserPermissions($user); $permissions = $this->getUserPermissions($user);
return [ return [
'token' => $token, 'token' => $token,
'expires_in' => auth('admin')->factory()->getTTL() * 60, 'expires_in' => auth('admin')->factory()->getTTL() * 60,
'user' => $this->getUserInfo($user), 'user' => $this->getUserInfo($user),
'menu' => $menu, 'menu' => $menu,
'permissions' => $permissions, 'permissions' => $permissions,
]; ];
} }
/** /**
* 管理员登出 * 管理员登出
*/ */
public function logout(): void public function logout(): void
{ {
auth('admin')->logout(); auth('admin')->logout();
} }
/** /**
* 刷新token * 刷新token
*/ */
public function refresh(): array public function refresh(): array
{ {
$newToken = auth('admin')->refresh(); $newToken = auth('admin')->refresh();
$user = auth('admin')->user(); $user = auth('admin')->user();
// 生成新的refresh token // 生成新的refresh token
$newRefreshToken = auth('admin')->refresh(); $newRefreshToken = auth('admin')->refresh();
// 获取用户菜单 // 获取用户菜单
$menu = $this->getUserMenu($user); $menu = $this->getUserMenu($user);
// 获取用户权限列表 // 获取用户权限列表
$permissions = $this->getUserPermissions($user); $permissions = $this->getUserPermissions($user);
return [ return [
'token' => $newToken, 'token' => $newToken,
'refreshToken' => $newRefreshToken, 'refreshToken' => $newRefreshToken,
'user' => $this->getUserInfo($user), 'user' => $this->getUserInfo($user),
'menu' => $menu, 'menu' => $menu,
'permissions' => $permissions, 'permissions' => $permissions,
]; ];
} }
/** /**
* 获取当前用户信息 * 获取当前用户信息
*/ */
public function me(): array public function me(): array
{ {
$user = auth('admin')->user(); $user = auth('admin')->user();
return $this->getUserInfo($user); return $this->getUserInfo($user);
} }
/** /**
* 找回密码 * 找回密码
*/ */
public function resetPassword(array $data): void public function resetPassword(array $data): void
{ {
$user = User::where('username', $data['username']) $user = User::where('username', $data['username'])
->orWhere('email', $data['username']) ->orWhere('email', $data['username'])
->orWhere('phone', $data['username']) ->orWhere('phone', $data['username'])
->first(); ->first();
if (!$user) { if (!$user) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'username' => ['用户不存在'], 'username' => ['用户不存在'],
]); ]);
} }
$user->update([ $user->update([
'password' => Hash::make($data['password']), 'password' => Hash::make($data['password']),
]); ]);
} }
/** /**
* 修改密码 * 修改密码
*/ */
public function changePassword(array $data): void public function changePassword(array $data): void
{ {
$user = auth('admin')->user(); $user = auth('admin')->user();
if (!Hash::check($data['old_password'], $user->password)) { if (!Hash::check($data['old_password'], $user->password)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'old_password' => ['原密码错误'], 'old_password' => ['原密码错误'],
]); ]);
} }
$user->update([ $user->update([
'password' => Hash::make($data['password']), 'password' => Hash::make($data['password']),
]); ]);
} }
/** /**
* 获取用户信息详情 * 获取用户信息详情
*/ */
private function getUserInfo(User $user): array private function getUserInfo(User $user): array
{ {
$user->load(['department', 'roles.permissions']); $user->load(['department', 'roles.permissions']);
return [ return [
'id' => $user->id, 'id' => $user->id,
'username' => $user->username, 'username' => $user->username,
'real_name' => $user->real_name, 'real_name' => $user->real_name,
'email' => $user->email, 'email' => $user->email,
'phone' => $user->phone, 'phone' => $user->phone,
'avatar' => $user->avatar, 'avatar' => $user->avatar,
'department' => $user->department ? [ 'department' => $user->department ? [
'id' => $user->department->id, 'id' => $user->department->id,
'name' => $user->department->name, 'name' => $user->department->name,
] : null, ] : null,
'roles' => $user->roles->pluck('name')->toArray(), 'roles' => $user->roles->pluck('name')->toArray(),
'permissions' => $this->getUserPermissions($user), 'permissions' => $this->getUserPermissions($user),
'status' => $user->status, 'status' => $user->status,
'last_login_at' => $user->last_login_at ? $user->last_login_at->toDateTimeString() : null, 'last_login_at' => $user->last_login_at ? $user->last_login_at->toDateTimeString() : null,
]; ];
} }
/** /**
* 获取用户菜单 * 获取用户菜单
*/ */
private function getUserMenu(User $user): array private function getUserMenu(User $user): array
{ {
// 获取用户的所有权限 // 超级管理员获取所有菜单
$permissionIds = []; if ($user->isSuperAdmin()) {
foreach ($user->roles as $role) { $menuPermissions = \App\Models\Auth\Permission::where('type', 'menu')
foreach ($role->permissions as $permission) { ->where('status', 1)
$permissionIds[] = $permission->id; ->orderBy('sort', 'asc')
} ->get();
} } else {
// 获取用户的所有权限
$permissionIds = [];
foreach ($user->roles as $role) {
foreach ($role->permissions as $permission) {
$permissionIds[] = $permission->id;
}
}
// 查询菜单类型的权限 // 查询菜单类型的权限
$menuPermissions = \App\Models\Auth\Permission::whereIn('id', $permissionIds) $menuPermissions = \App\Models\Auth\Permission::whereIn('id', $permissionIds)
->where('type', 'menu') ->where('type', 'menu')
->where('status', 1) ->where('status', 1)
->orderBy('sort', 'asc') ->orderBy('sort', 'asc')
->get(); ->get();
}
// 构建菜单树 // 构建菜单树
return $this->buildMenuTree($menuPermissions); return $this->buildMenuTree($menuPermissions);
} }
/** /**
* 构建菜单树 * 构建菜单树
*/ */
private function buildMenuTree($permissions, $parentId = 0): array private function buildMenuTree($permissions, $parentId = 0): array
{ {
$tree = []; $tree = [];
foreach ($permissions as $permission) { foreach ($permissions as $permission) {
if ($permission->parent_id == $parentId) { if ($permission->parent_id == $parentId) {
$node = [ $node = [
'path' => $permission->path, 'path' => $permission->path,
'name' => $permission->name, 'name' => $permission->name,
'title' => $permission->title, 'title' => $permission->title,
'meta' => $permission->meta ? json_decode($permission->meta, true) : [], 'meta' => $permission->meta ? json_decode($permission->meta, true) : [],
]; ];
// 添加组件路径 // 添加组件路径
if ($permission->component) { if ($permission->component) {
$node['component'] = $permission->component; $node['component'] = $permission->component;
} }
// 添加重定向 // 添加重定向
if (!empty($node['meta']['redirect'])) { if (!empty($node['meta']['redirect'])) {
$node['redirect'] = $node['meta']['redirect']; $node['redirect'] = $node['meta']['redirect'];
} }
// 递归构建子菜单 // 递归构建子菜单
$children = $this->buildMenuTree($permissions, $permission->id); $children = $this->buildMenuTree($permissions, $permission->id);
if (!empty($children)) { if (!empty($children)) {
$node['children'] = $children; $node['children'] = $children;
} }
$tree[] = $node; $tree[] = $node;
} }
} }
return $tree; return $tree;
} }
/** /**
* 获取用户权限列表 * 获取用户权限列表
*/ */
private function getUserPermissions(User $user): array private function getUserPermissions(User $user): array
{ {
$permissions = []; // 超级管理员获取所有权限
foreach ($user->roles as $role) { if ($user->isSuperAdmin()) {
foreach ($role->permissions as $permission) { return \App\Models\Auth\Permission::where('status', 1)
if (!in_array($permission->name, $permissions)) { ->pluck('name')
$permissions[] = $permission->name; ->toArray();
} }
}
} $permissions = [];
return $permissions; foreach ($user->roles as $role) {
} foreach ($role->permissions as $permission) {
if (!in_array($permission->name, $permissions)) {
$permissions[] = $permission->name;
}
}
}
return $permissions;
}
} }
+32 -30
View File
@@ -659,112 +659,114 @@ private function createSystemConfigs(): void
{ {
$configs = [ $configs = [
[ [
'group' => 'basic', 'group' => 'site',
'key' => 'site_name', 'key' => 'site_name',
'name' => '网站名称', 'name' => '网站名称',
'value' => 'Laravel Swoole 管理系统', 'value' => 'Laravel Swoole 管理系统',
'default_value' => 'Laravel Swoole 管理系统', 'type' => 'string',
'type' => 'input',
'description' => '系统显示的网站名称', 'description' => '系统显示的网站名称',
'sort' => 1, 'sort' => 1,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'basic', 'group' => 'site',
'key' => 'site_logo', 'key' => 'site_logo',
'name' => '网站Logo', 'name' => '网站Logo',
'value' => '', 'value' => '',
'default_value' => '', 'type' => 'file',
'type' => 'image',
'description' => '系统Logo图片地址', 'description' => '系统Logo图片地址',
'sort' => 2, 'sort' => 2,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'basic', 'group' => 'site',
'key' => 'site_copyright', 'key' => 'site_copyright',
'name' => '版权信息', 'name' => '版权信息',
'value' => '© 2024 Laravel Swoole Admin', 'value' => '© 2024 Laravel Swoole Admin',
'default_value' => '© 2024 Laravel Swoole Admin', 'type' => 'string',
'type' => 'input',
'description' => '网站底部版权信息', 'description' => '网站底部版权信息',
'sort' => 3, 'sort' => 3,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'basic', 'group' => 'site',
'key' => 'site_icp', 'key' => 'site_icp',
'name' => '备案号', 'name' => '备案号',
'value' => '', 'value' => '',
'default_value' => '', 'type' => 'string',
'type' => 'input',
'description' => '网站备案号', 'description' => '网站备案号',
'sort' => 4, 'sort' => 4,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'upload', 'group' => 'upload',
'key' => 'upload_max_size', 'key' => 'upload_max_size',
'name' => '上传最大限制', 'name' => '上传最大限制',
'value' => '10', 'value' => '10',
'default_value' => '10',
'type' => 'number', 'type' => 'number',
'description' => '文件上传最大限制(MB', 'description' => '文件上传最大限制(MB',
'sort' => 1, 'sort' => 1,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'upload', 'group' => 'upload',
'key' => 'upload_allowed_types', 'key' => 'upload_allowed_types',
'name' => '允许上传类型', 'name' => '允许上传类型',
'value' => 'jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx', 'value' => 'jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx',
'default_value' => 'jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx', 'type' => 'string',
'type' => 'input',
'description' => '允许上传的文件扩展名', 'description' => '允许上传的文件扩展名',
'sort' => 2, 'sort' => 2,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'system', 'group' => 'system',
'key' => 'user_default_avatar', 'key' => 'user_default_avatar',
'name' => '默认头像', 'name' => '默认头像',
'value' => '', 'value' => '',
'default_value' => '', 'type' => 'file',
'type' => 'image',
'description' => '用户默认头像地址', 'description' => '用户默认头像地址',
'sort' => 1, 'sort' => 1,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'system', 'group' => 'system',
'key' => 'system_timezone', 'key' => 'system_timezone',
'name' => '系统时区', 'name' => '系统时区',
'value' => 'Asia/Shanghai', 'value' => 'Asia/Shanghai',
'default_value' => 'Asia/Shanghai', 'type' => 'string',
'type' => 'input',
'description' => '系统默认时区', 'description' => '系统默认时区',
'sort' => 2, 'sort' => 2,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
], ],
[ [
'group' => 'system', 'group' => 'system',
'key' => 'system_language', 'key' => 'system_language',
'name' => '系统语言', 'name' => '系统语言',
'value' => 'zh-CN', 'value' => 'zh-CN',
'default_value' => 'zh-CN', 'type' => 'string',
'type' => 'input',
'description' => '系统默认语言', 'description' => '系统默认语言',
'sort' => 3, 'sort' => 3,
'is_system' => true, 'is_system' => true,
'status' => true, 'status' => 1,
],
[
'group' => 'system',
'key' => 'enable_register',
'name' => '开启注册',
'value' => '1',
'type' => 'boolean',
'description' => '是否开启用户注册功能',
'sort' => 4,
'is_system' => true,
'status' => 1,
], ],
]; ];
@@ -1,6 +1,6 @@
<template> <template>
<div class="sc-icon-picker"> <div class="sc-icon-picker">
<a-input :value="selectedIcon ? '' : ''" :placeholder="placeholder" readonly @click="handleOpenPicker"> <a-input :value="selectedIcon || ''" :placeholder="placeholder" readonly @click="handleOpenPicker">
<template #prefix v-if="selectedIcon"> <template #prefix v-if="selectedIcon">
<component :is="selectedIcon" /> <component :is="selectedIcon" />
</template> </template>
@@ -10,51 +10,65 @@
</template> </template>
</a-input> </a-input>
<a-modal v-model:open="visible" title="选择图标" :width="800" :footer="null" @cancel="handleCancel"> <a-modal v-model:open="visible" title="选择图标" :width="900" :footer="null" @cancel="handleCancel">
<a-tabs v-model:activeKey="activeTab" @change="handleTabChange"> <div class="icon-picker-content">
<a-tab-pane key="antd" tab="Ant Design"> <!-- 搜索框 -->
<div class="icon-search"> <div class="icon-search">
<a-input v-model:value="searchAntdValue" placeholder="搜索图标..." allow-clear> <a-input
<template #prefix> v-model:value="searchValue"
<SearchOutlined /> placeholder="搜索图标名称..."
</template> allow-clear
</a-input> @change="handleSearchChange"
</div> >
<template #prefix>
<SearchOutlined />
</template>
</a-input>
</div>
<!-- 分类标签 -->
<div class="icon-categories" v-if="!searchValue">
<a-tag
v-for="category in iconCategories"
:key="category.key"
:class="['category-tag', { active: activeCategory === category.key }]"
@click="handleCategoryChange(category.key)"
>
{{ category.label }}
</a-tag>
</div>
<!-- 最近使用 -->
<div v-if="!searchValue && activeCategory === 'recent' && recentIcons.length > 0" class="recent-section">
<div class="section-title">最近使用</div>
<div class="icon-list"> <div class="icon-list">
<div <div
v-for="icon in filteredAntdIcons" v-for="icon in recentIcons"
:key="icon" :key="icon"
:class="['icon-item', { active: tempIcon === icon }]" :class="['icon-item', { active: tempIcon === icon }]"
@click="handleSelectIcon(icon)" @click="handleSelectIcon(icon)"
> >
<component :is="icon" /> <component :is="icon" />
<div class="icon-name">{{ icon }}</div> <div class="icon-name">{{ icon }}</div>
<CloseCircleFilled class="recent-remove" @click.stop="handleRemoveRecent(icon)" />
</div> </div>
<a-empty v-if="filteredAntdIcons.length === 0" description="暂无图标" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
</div> </div>
</a-tab-pane> </div>
<a-tab-pane key="element" tab="Element Plus">
<div class="icon-search"> <!-- 图标列表 -->
<a-input v-model:value="searchElementValue" placeholder="搜索图标..." allow-clear> <div class="icon-list" v-show="activeCategory !== 'recent' || searchValue || (activeCategory === 'recent' && recentIcons.length === 0)">
<template #prefix> <div
<SearchOutlined /> v-for="icon in filteredIcons"
</template> :key="icon"
</a-input> :class="['icon-item', { active: tempIcon === icon }]"
@click="handleSelectIcon(icon)"
>
<component :is="icon" />
<div class="icon-name">{{ icon }}</div>
</div> </div>
<div class="icon-list"> <a-empty v-if="filteredIcons.length === 0" description="暂无图标" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
<div </div>
v-for="icon in filteredElementIcons" </div>
:key="icon"
:class="['icon-item', { active: tempIcon === icon }]"
@click="handleSelectIcon(icon)"
>
<component :is="icon" />
<div class="icon-name">{{ icon.replace('El', '') }}</div>
</div>
<a-empty v-if="filteredElementIcons.length === 0" description="暂无图标" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
</div>
</a-tab-pane>
</a-tabs>
</a-modal> </a-modal>
</div> </div>
</template> </template>
@@ -62,8 +76,9 @@
<script setup> <script setup>
/** /**
* @component scIconPicker * @component scIconPicker
* @description 图标选择器组件,支持 Ant Design Vue 图标库
*/ */
import { ref, computed, watch } from 'vue' import { ref, computed, watch, onMounted } from 'vue'
import { Empty } from 'ant-design-vue' import { Empty } from 'ant-design-vue'
import { SearchOutlined, CloseCircleFilled } from '@ant-design/icons-vue' import { SearchOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
@@ -81,323 +96,214 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue', 'change']) const emit = defineEmits(['update:modelValue', 'change'])
const visible = ref(false) const visible = ref(false)
const activeTab = ref('antd') const activeCategory = ref('all')
const searchAntdValue = ref('') const searchValue = ref('')
const searchElementValue = ref('')
const tempIcon = ref('') const tempIcon = ref('')
const recentIcons = ref([])
const RECENT_ICONS_KEY = 'sc-icon-picker-recent'
const MAX_RECENT_ICONS = 12
// Ant Design 图标列表(常用图标) // 图标分类
const antdIcons = [ const iconCategories = [
'HomeOutlined', { key: 'recent', label: '最近使用' },
'UserOutlined', { key: 'all', label: '全部' },
'SettingOutlined', { key: 'direction', label: '方向' },
'EditOutlined', { key: 'edit', label: '编辑' },
'DeleteOutlined', { key: 'data', label: '数据' },
'PlusOutlined', { key: 'media', label: '媒体' },
'MinusOutlined', { key: 'user', label: '用户' },
'CheckOutlined', { key: 'system', label: '系统' },
'CloseOutlined', { key: 'commerce', label: '商务' },
'SearchOutlined',
'FilterOutlined',
'ReloadOutlined',
'DownloadOutlined',
'UploadOutlined',
'FileTextOutlined',
'FolderOutlined',
'PictureOutlined',
'VideoCameraOutlined',
'AudioOutlined',
'FileOutlined',
'CalendarOutlined',
'ClockCircleOutlined',
'HeartOutlined',
'StarOutlined',
'ThumbUpOutlined',
'MessageOutlined',
'PhoneOutlined',
'MailOutlined',
'EnvironmentOutlined',
'GlobalOutlined',
'LinkOutlined',
'LockOutlined',
'UnlockOutlined',
'EyeOutlined',
'EyeInvisibleOutlined',
'ArrowLeftOutlined',
'ArrowRightOutlined',
'ArrowUpOutlined',
'ArrowDownOutlined',
'CaretLeftOutlined',
'CaretRightOutlined',
'CaretUpOutlined',
'CaretDownOutlined',
'LeftOutlined',
'RightOutlined',
'UpOutlined',
'DownOutlined',
'MenuFoldOutlined',
'MenuUnfoldOutlined',
'BarsOutlined',
'MoreOutlined',
'EllipsisOutlined',
'DashboardOutlined',
'AppstoreOutlined',
'LaptopOutlined',
'DesktopOutlined',
'TabletOutlined',
'MobileOutlined',
'WifiOutlined',
'BluetoothOutlined',
'ThunderboltOutlined',
'BulbOutlined',
'SoundOutlined',
'NotificationOutlined',
'BellOutlined',
'AlertOutlined',
'WarningOutlined',
'InfoCircleOutlined',
'QuestionCircleOutlined',
'CheckCircleOutlined',
'CloseCircleOutlined',
'StopOutlined',
'ExclamationCircleOutlined',
'SafetyOutlined',
'ShieldCheckOutlined',
'SecurityScanOutlined',
'KeyOutlined',
'IdcardOutlined',
'ProfileOutlined',
'SolutionOutlined',
'ContactsOutlined',
'TeamOutlined',
'UsergroupAddOutlined',
'UsergroupDeleteOutlined',
'CrownOutlined',
'GoldOutlined',
'MoneyCollectOutlined',
'BankOutlined',
'PayCircleOutlined',
'CreditCardOutlined',
'WalletOutlined',
'ShoppingCartOutlined',
'ShoppingOutlined',
'GiftOutlined',
'HddOutlined',
'DatabaseOutlined',
'CloudOutlined',
'CloudUploadOutlined',
'CloudDownloadOutlined',
'ServerOutlined',
'AuditOutlined',
'NodeIndexOutlined',
'ReconciliationOutlined',
'PartitionOutlined',
'AccountBookOutlined',
'ProjectOutlined',
'ControlOutlined',
'MonitorOutlined',
'TagsOutlined',
'TagOutlined',
'BookOutlined',
'ReadOutlined',
'ExperimentOutlined',
'FireOutlined',
'RocketOutlined',
'TrophyOutlined',
'MedalOutlined',
'DiamondOutlined',
'ThunderboltTwoTone',
] ]
// Element Plus 图标列表(常用图标) // Ant Design 图标分类列表
const elementIcons = [ const iconCategoriesMap = {
'ElIconEdit', direction: [
'ElIconDelete', 'ArrowLeftOutlined', 'ArrowRightOutlined', 'ArrowUpOutlined', 'ArrowDownOutlined',
'ElIconSearch', 'LeftOutlined', 'RightOutlined', 'UpOutlined', 'DownOutlined',
'ElIconClose', 'CaretLeftOutlined', 'CaretRightOutlined', 'CaretUpOutlined', 'CaretDownOutlined',
'ElIconCheck', 'BackwardOutlined', 'ForwardOutlined', 'FastBackwardOutlined', 'FastForwardOutlined',
'ElIconPlus', 'ShrinkOutlined', 'ArrowsAltOutlined', 'VerticalAlignTopOutlined', 'VerticalAlignBottomOutlined',
'ElIconMinus', 'RollbackOutlined', 'EnterOutlined', 'RetweetOutlined', 'SwapOutlined',
'ElIconUpload', 'SwapLeftOutlined', 'SwapRightOutlined', 'UpCircleOutlined', 'DownCircleOutlined',
'ElIconDownload', 'LeftCircleOutlined', 'RightCircleOutlined', 'ArrowRightOutlined', 'ArrowLeftOutlined',
'ElIconSetting', ],
'ElIconRefresh', edit: [
'ElIconRefreshLeft', 'EditOutlined', 'DeleteOutlined', 'PlusOutlined', 'MinusOutlined',
'ElIconRefreshRight', 'CheckOutlined', 'CloseOutlined', 'FormOutlined', 'CopyOutlined',
'ElIconMenu', 'ScissorOutlined', 'SnippetsOutlined', 'DiffOutlined', 'HighlightOutlined',
'ElIconMore', 'AlignLeftOutlined', 'AlignCenterOutlined', 'AlignRightOutlined', 'AlignCenterOutlined',
'ElIconMoreFilled', 'BoldOutlined', 'ItalicOutlined', 'UnderlineOutlined', 'StrikethroughOutlined',
'ElIconStar', 'RedoOutlined', 'UndoOutlined', 'FileAddOutlined', 'FileSyncOutlined',
'ElIconStarFilled', ],
'ElIconSunny', data: [
'ElIconMoon', 'DatabaseOutlined', 'CloudOutlined', 'CloudServerOutlined', 'CloudUploadOutlined',
'ElIconBell', 'CloudDownloadOutlined', 'DatabaseOutlined', 'HddOutlined', 'ServerOutlined',
'ElIconBellFilled', 'ReconciliationOutlined', 'AccountBookOutlined', 'AuditOutlined', 'BarChartOutlined',
'ElIconMessage', 'AreaChartOutlined', 'DotChartOutlined', 'LineChartOutlined', 'PieChartOutlined',
'ElIconMessageFilled', 'FundOutlined', 'SlidersOutlined', 'ControlOutlined', 'ExperimentOutlined',
'ElIconChatDotRound', 'ProjectOutlined', 'NodeIndexOutlined', 'PartitionOutlined', 'ApartmentOutlined',
'ElIconChatLineSquare', ],
'ElIconChatDotSquare', media: [
'ElIconPhone', 'PictureOutlined', 'VideoCameraOutlined', 'AudioOutlined', 'FileImageOutlined',
'ElIconPhoneFilled', 'FilePdfOutlined', 'FileWordOutlined', 'FileExcelOutlined', 'FileZipOutlined',
'ElIconLocation', 'FolderOutlined', 'FolderOpenOutlined', 'FileTextOutlined', 'FileOutlined',
'ElIconLocationFilled', 'FileMarkdownOutlined', 'FileUnknownOutlined', 'FilePptOutlined', 'FileAddOutlined',
'ElIconLocationInformation', 'CameraOutlined', 'QrcodeOutlined', 'BarcodeOutlined', 'ScanOutlined',
'ElIconView', 'MusicOutlined', 'SoundOutlined', 'CustomerServiceOutlined', 'MessageOutlined',
'ElIconHide', ],
'ElIconLock', user: [
'ElIconUnlock', 'UserOutlined', 'UsergroupAddOutlined', 'UsergroupDeleteOutlined', 'TeamOutlined',
'ElIconKey', 'SolutionOutlined', 'ContactsOutlined', 'IdcardOutlined', 'ProfileOutlined',
'ElIconTickets', 'AliwangwangOutlined', 'SmileOutlined', 'MehOutlined', 'FrownOutlined',
'ElIconDocument', 'HeartOutlined', 'StarOutlined', 'LikeOutlined', 'DislikeOutlined',
'ElIconDocumentAdd', 'ThumbUpOutlined', 'SkypeOutlined', 'GithubOutlined', 'WechatOutlined',
'ElIconDocumentDelete', 'TwitterOutlined', 'WeiboOutlined', 'FacebookOutlined', 'GoogleOutlined',
'ElIconDocumentCopy', ],
'ElIconDocumentChecked', system: [
'ElIconDocumentRemove', 'SettingOutlined', 'HomeOutlined', 'DashboardOutlined', 'AppstoreOutlined',
'ElIconFolder', 'MenuFoldOutlined', 'MenuUnfoldOutlined', 'BarsOutlined', 'MoreOutlined',
'ElIconFolderOpened', 'BellOutlined', 'NotificationOutlined', 'AlertOutlined', 'WarningOutlined',
'ElIconFolderAdd', 'CheckCircleOutlined', 'CloseCircleOutlined', 'ExclamationCircleOutlined', 'InfoCircleOutlined',
'ElIconFolderDelete', 'QuestionCircleOutlined', 'SafetyOutlined', 'SecurityScanOutlined', 'ShieldCheckOutlined',
'ElIconFolderChecked', 'LockOutlined', 'UnlockOutlined', 'KeyOutlined', 'EyeOutlined', 'EyeInvisibleOutlined',
'ElIconFiles', 'LogoutOutlined', 'LoginOutlined', 'MobileOutlined', 'LaptopOutlined', 'DesktopOutlined',
'ElIconPicture', 'ThunderboltOutlined', 'WifiOutlined', 'BluetoothOutlined', 'ApiOutlined',
'ElIconPictureRounded', 'BugOutlined', 'BuildOutlined', 'CodeOutlined', 'CodeSandboxOutlined',
'ElIconPictureFilled', 'FunctionOutlined', 'ConsoleSqlOutlined', 'ApiOutlined',
'ElIconVideoCamera', ],
'ElIconVideoCameraFilled', commerce: [
'ElIconMicrophone', 'ShoppingCartOutlined', 'ShoppingOutlined', 'GiftOutlined', 'GoldOutlined',
'ElIconMicrophoneFilled', 'CrownOutlined', 'MedalOutlined', 'TrophyOutlined', 'DiamondOutlined',
'ElIconHeadset', 'BankOutlined', 'CreditCardOutlined', 'PayCircleOutlined', 'WalletOutlined',
'ElIconHeadsetFilled', 'MoneyCollectOutlined', 'TransactionOutlined', 'DollarOutlined', 'EuroOutlined',
'ElIconMuteNotification', 'PoundOutlined', 'YenOutlined', 'GiftFilledOutlined', 'RocketOutlined',
'ElIconNotification', 'FireOutlined', 'ThunderboltTwoTone', 'BulbOutlined', 'SafetyCertificateOutlined',
'ElIconWarning', ],
'ElIconWarningFilled', all: [
'ElIconInfoFilled', 'HomeOutlined', 'DashboardOutlined', 'AppstoreOutlined', 'BarsOutlined',
'ElIconSuccessFilled', 'MenuFoldOutlined', 'MenuUnfoldOutlined', 'MoreOutlined', 'EllipsisOutlined',
'ElIconCircleCheck', 'UserOutlined', 'TeamOutlined', 'UsergroupAddOutlined', 'UsergroupDeleteOutlined',
'ElIconCircleCheckFilled', 'SettingOutlined', 'ControlOutlined', 'ToolOutlined', 'BuildOutlined',
'ElIconCircleClose', 'SearchOutlined', 'FilterOutlined', 'SortAscendingOutlined', 'SortDescendingOutlined',
'ElIconCircleCloseFilled', 'ReloadOutlined', 'SyncOutlined', 'RedoOutlined', 'UndoOutlined',
'ElIconCirclePlus', 'EditOutlined', 'DeleteOutlined', 'PlusOutlined', 'MinusOutlined',
'ElIconCirclePlusFilled', 'CheckOutlined', 'CloseOutlined', 'CheckCircleOutlined', 'CloseCircleOutlined',
'ElIconCircleMinus', 'ArrowLeftOutlined', 'ArrowRightOutlined', 'ArrowUpOutlined', 'ArrowDownOutlined',
'ElIconCircleMinusFilled', 'LeftOutlined', 'RightOutlined', 'UpOutlined', 'DownOutlined',
'ElIconAim', 'FileTextOutlined', 'FileOutlined', 'FolderOutlined', 'FolderOpenOutlined',
'ElIconPosition', 'PictureOutlined', 'VideoCameraOutlined', 'AudioOutlined', 'CameraOutlined',
'ElIconCompass', 'CalendarOutlined', 'ClockCircleOutlined', 'HistoryOutlined', 'FieldTimeOutlined',
'ElIconMapLocation', 'HeartOutlined', 'StarOutlined', 'LikeOutlined', 'DislikeOutlined',
'ElIconPromotion', 'MessageOutlined', 'MailOutlined', 'PhoneOutlined', 'WechatOutlined',
'ElIconDownload', 'EnvironmentOutlined', 'GlobalOutlined', 'CompassOutlined', 'MapOutlined',
'ElIconUploadFilled', 'LockOutlined', 'UnlockOutlined', 'KeyOutlined', 'SafetyOutlined',
'ElIconShare', 'EyeOutlined', 'EyeInvisibleOutlined', 'VisibilityOutlined', 'EyeFilled',
'ElIconConnection', 'BellOutlined', 'NotificationOutlined', 'AlertOutlined', 'WarningOutlined',
'ElIconLink', 'InfoCircleOutlined', 'QuestionCircleOutlined', 'ExclamationCircleOutlined', 'StopOutlined',
'ElIconUnlink', 'DatabaseOutlined', 'CloudOutlined', 'HddOutlined', 'ServerOutlined',
'ElIconOperation', 'WifiOutlined', 'BluetoothOutlined', 'ApiOutlined', 'CodeOutlined',
'ElIconDataAnalysis', 'LaptopOutlined', 'MobileOutlined', 'TabletOutlined', 'DesktopOutlined',
'ElIconDataLine', 'ThunderboltOutlined', 'BulbOutlined', 'FireOutlined', 'ExperimentOutlined',
'ElIconDataBoard', 'ShoppingCartOutlined', 'ShoppingOutlined', 'GiftOutlined', 'WalletOutlined',
'ElIconHistogram', 'CreditCardOutlined', 'BankOutlined', 'PayCircleOutlined', 'MoneyCollectOutlined',
'ElIconTrendCharts', 'MedalOutlined', 'TrophyOutlined', 'CrownOutlined', 'GoldOutlined',
'ElIconPieChart', 'RocketOutlined', 'FundOutlined', 'PieChartOutlined', 'BarChartOutlined',
'ElIconOdometer', 'AreaChartOutlined', 'LineChartOutlined', 'DotChartOutlined',
'ElIconMonitor', 'FileAddOutlined', 'FileExcelOutlined', 'FilePdfOutlined', 'FileWordOutlined',
'ElIconTimer', 'UploadOutlined', 'DownloadOutlined', 'ImportOutlined', 'ExportOutlined',
'ElIconClock', 'CopyOutlined', 'ScanOutlined', 'QrcodeOutlined', 'BarcodeOutlined',
'ElIconAlarmClock', 'PrinterOutlined', 'RetweetOutlined', 'SwapOutlined', 'ShareAltOutlined',
'ElIconCalendar', 'ApiOutlined', 'CodeSandboxOutlined', 'ConsoleSqlOutlined', 'FunctionOutlined',
'ElIconDate', ],
'ElIconSwitch', }
'ElIconSwitchButton',
'ElIconTools', // 加载最近使用的图标
'ElIconScrewdriver', const loadRecentIcons = () => {
'ElIconHammer', try {
'ElIconBrush', const stored = localStorage.getItem(RECENT_ICONS_KEY)
'ElIconEditPen', if (stored) {
'ElIconBriefcase', recentIcons.value = JSON.parse(stored)
'ElIconWallet', }
'ElIconGoods', } catch (error) {
'ElIconShoppingCart', console.error('加载最近使用图标失败:', error)
'ElIconShoppingCartFull', }
'ElIconShoppingBag', }
'ElIconPresent',
'ElIconSoldOut', // 保存最近使用的图标
'ElIconSell', const saveRecentIcons = (icon) => {
'ElIconDiscount', if (!icon) return
'ElIconTicket',
'ElIconCoin', // 移除已存在的相同图标
'ElIconMoney', const index = recentIcons.value.indexOf(icon)
'ElIconWalletFilled', if (index > -1) {
'ElIconCreditCard', recentIcons.value.splice(index, 1)
'ElIconUser', }
'ElIconUserFilled',
'ElIconAvatar', // 添加到开头
'ElIconSuitcase', recentIcons.value.unshift(icon)
'ElIconGrid',
'ElIconMenuFilled', // 限制数量
'ElIconHomeFilled', if (recentIcons.value.length > MAX_RECENT_ICONS) {
'ElIconHouse', recentIcons.value = recentIcons.value.slice(0, MAX_RECENT_ICONS)
'ElIconOfficeBuilding', }
'ElIconSchool',
'ElIconReading', // 保存到本地存储
'ElIconReadingLamp', try {
'ElIconNotebook', localStorage.setItem(RECENT_ICONS_KEY, JSON.stringify(recentIcons.value))
'ElIconNotebookFilled', } catch (error) {
'ElIconFinished', console.error('保存最近使用图标失败:', error)
'ElIconCollection', }
'ElIconCollectionTag', }
'ElIconFiles',
'ElIconPostcard', // 移除最近使用的图标
'ElIconMemo', const handleRemoveRecent = (icon) => {
'ElIconStamp', const index = recentIcons.value.indexOf(icon)
'ElIconPriceTag', if (index > -1) {
'ElIconMedal', recentIcons.value.splice(index, 1)
'ElIconTrophy', try {
'ElIconTrophyBase', localStorage.setItem(RECENT_ICONS_KEY, JSON.stringify(recentIcons.value))
'ElIconFirstAidKit', } catch (error) {
'ElIconToiletPaper', console.error('保存最近使用图标失败:', error)
'ElIconAim', }
'ElIconSFlag', }
'ElIconSOpportunity', }
'ElIconMagicStick',
'ElIconHelp',
'ElIconQuestionFilled',
'ElIconWarning',
'ElIconWarningFilled',
]
// 当前选中的图标 // 当前选中的图标
const selectedIcon = ref(props.modelValue) const selectedIcon = ref(props.modelValue)
// 过滤后的 Ant Design 图标 // 获取当前分类的图标
const filteredAntdIcons = computed(() => { const currentCategoryIcons = computed(() => {
if (!searchAntdValue.value) { if (activeCategory.value === 'all') {
return antdIcons return iconCategoriesMap.all
} }
return antdIcons.filter((icon) => return iconCategoriesMap[activeCategory.value] || []
icon.toLowerCase().includes(searchAntdValue.value.toLowerCase()),
)
}) })
// 过滤后的 Element 图标 // 过滤后的图标
const filteredElementIcons = computed(() => { const filteredIcons = computed(() => {
if (!searchElementValue.value) { let icons = []
return elementIcons
if (searchValue.value) {
// 搜索时从所有图标中筛选
const allIcons = iconCategoriesMap.all
icons = allIcons.filter((icon) =>
icon.toLowerCase().includes(searchValue.value.toLowerCase())
)
} else if (activeCategory.value === 'recent') {
// 最近使用时不显示其他图标
icons = []
} else {
// 根据分类显示
icons = currentCategoryIcons.value
} }
return elementIcons.filter((icon) =>
icon.toLowerCase().includes(searchElementValue.value.toLowerCase()), return icons
)
}) })
// 打开选择器 // 打开选择器
const handleOpenPicker = () => { const handleOpenPicker = () => {
tempIcon.value = props.modelValue tempIcon.value = props.modelValue
// 根据当前图标设置默认标签页
if (props.modelValue) {
activeTab.value = props.modelValue.startsWith('El') ? 'element' : 'antd'
}
visible.value = true visible.value = true
} }
@@ -407,9 +313,17 @@ const handleClear = () => {
emit('change', '') emit('change', '')
} }
// 切换标签页 // 切换分类
const handleTabChange = (key) => { const handleCategoryChange = (key) => {
activeTab.value = key activeCategory.value = key
}
// 搜索变化
const handleSearchChange = () => {
// 搜索时重置分类
if (searchValue.value) {
activeCategory.value = 'all'
}
} }
// 选择图标(直接确认并关闭) // 选择图标(直接确认并关闭)
@@ -417,6 +331,10 @@ const handleSelectIcon = (icon) => {
emit('update:modelValue', icon) emit('update:modelValue', icon)
emit('change', icon) emit('change', icon)
selectedIcon.value = icon selectedIcon.value = icon
// 添加到最近使用
saveRecentIcons(icon)
visible.value = false visible.value = false
} }
@@ -425,13 +343,18 @@ const handleCancel = () => {
visible.value = false visible.value = false
} }
// 监听props变化,更新本地状态 // 监听 props 变化,更新本地状态
watch( watch(
() => props.modelValue, () => props.modelValue,
(newVal) => { (newVal) => {
selectedIcon.value = newVal selectedIcon.value = newVal
} }
) )
// 组件挂载时加载最近使用的图标
onMounted(() => {
loadRecentIcons()
})
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@@ -439,18 +362,61 @@ watch(
:deep(.ant-input) { :deep(.ant-input) {
cursor: pointer; cursor: pointer;
} }
}
.icon-picker-content {
.icon-search { .icon-search {
margin-bottom: 16px; margin-bottom: 16px;
} }
.icon-categories {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
padding: 12px;
background: #fafafa;
border-radius: 6px;
.category-tag {
cursor: pointer;
transition: all 0.3s;
user-select: none;
margin: 0;
&:hover {
background-color: #e6f7ff;
color: #1890ff;
border-color: #1890ff;
}
&.active {
background-color: #1890ff;
color: #fff;
border-color: #1890ff;
}
}
}
.recent-section {
margin-bottom: 16px;
.section-title {
font-size: 14px;
font-weight: 500;
color: #333;
margin-bottom: 12px;
padding-left: 4px;
}
}
.icon-list { .icon-list {
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 12px; gap: 12px;
max-height: 400px; max-height: 400px;
overflow-y: auto; overflow-y: auto;
padding: 8px; padding: 4px;
&::-webkit-scrollbar { &::-webkit-scrollbar {
width: 6px; width: 6px;
@@ -466,6 +432,7 @@ watch(
} }
.icon-item { .icon-item {
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
@@ -475,10 +442,17 @@ watch(
border-radius: 6px; border-radius: 6px;
cursor: pointer; cursor: pointer;
transition: all 0.3s; transition: all 0.3s;
background: #fff;
&:hover { &:hover {
border-color: #1890ff; border-color: #1890ff;
color: #1890ff; color: #1890ff;
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
.recent-remove {
opacity: 1;
}
} }
&.active { &.active {
@@ -488,7 +462,7 @@ watch(
} }
:deep(svg) { :deep(svg) {
font-size: 24px; font-size: 28px;
margin-bottom: 8px; margin-bottom: 8px;
} }
@@ -501,8 +475,29 @@ watch(
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
width: 100%; width: 100%;
line-height: 1.2;
}
.recent-remove {
position: absolute;
top: 4px;
right: 4px;
font-size: 14px;
color: #ff4d4f;
opacity: 0;
transition: opacity 0.3s;
padding: 2px;
border-radius: 50%;
&:hover {
background-color: rgba(255, 77, 95, 0.1);
}
} }
} }
} }
} }
:deep(.ant-modal-body) {
padding: 16px 24px;
}
</style> </style>
@@ -83,7 +83,7 @@ const rules = {
// 部门数据 // 部门数据
const departments = ref([]) const departments = ref([])
const departmentFieldNames = { const departmentFieldNames = {
title: 'name', label: 'name',
value: 'id', value: 'id',
children: 'children' children: 'children'
} }
@@ -0,0 +1,370 @@
<template>
<a-modal
v-model:open="visible"
:title="isEdit ? '编辑配置' : '新增配置'"
:width="600"
:confirm-loading="loading"
@ok="handleOk"
@cancel="handleCancel"
>
<a-form ref="formRef" :model="formData" :rules="rules" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
<a-form-item label="配置分组" name="group">
<a-select v-model:value="formData.group" placeholder="请选择配置分组" allow-show-search>
<a-select-option value="system">系统设置</a-select-option>
<a-select-option value="site">站点配置</a-select-option>
<a-select-option value="upload">上传配置</a-select-option>
<a-select-option value="email">邮件配置</a-select-option>
<a-select-option value="sms">短信配置</a-select-option>
<a-select-option value="other">其他</a-select-option>
<template #notFoundContent>
<div style="text-align: center">
<a-input v-model:value="customGroup" placeholder="输入新分组" style="margin-bottom: 8px" />
<a-button type="primary" size="small" @click="handleAddCustomGroup">添加</a-button>
</div>
</template>
</a-select>
</a-form-item>
<a-form-item label="配置键" name="key">
<a-input v-model:value="formData.key" placeholder="请输入配置键,如:site_name" :disabled="isEdit && formData.is_system" />
<div style="color: #999; font-size: 12px; margin-top: 4px">唯一标识建议使用英文下划线命名</div>
</a-form-item>
<a-form-item label="配置名称" name="name">
<a-input v-model:value="formData.name" placeholder="请输入配置名称" />
</a-form-item>
<a-form-item label="数据类型" name="type">
<a-select v-model:value="formData.type" placeholder="请选择数据类型">
<a-select-option value="string">字符串</a-select-option>
<a-select-option value="text">文本</a-select-option>
<a-select-option value="number">数字</a-select-option>
<a-select-option value="boolean">布尔值</a-select-option>
<a-select-option value="select">下拉框</a-select-option>
<a-select-option value="radio">单选框</a-select-option>
<a-select-option value="checkbox">多选框</a-select-option>
<a-select-option value="file">文件</a-select-option>
<a-select-option value="json">JSON</a-select-option>
</a-select>
</a-form-item>
<a-form-item
v-if="['select', 'radio', 'checkbox'].includes(formData.type)"
label="可选值"
name="options"
>
<a-textarea
v-model:value="optionsText"
placeholder="每行一个选项,格式:label:value&#10;例如:&#10;正常:1&#10;禁用:0"
:rows="4"
/>
</a-form-item>
<a-form-item label="配置值" name="value">
<!-- 字符串输入 -->
<a-input
v-if="formData.type === 'string'"
v-model:value="formData.value"
placeholder="请输入配置值"
/>
<!-- 文本域 -->
<a-textarea
v-else-if="formData.type === 'text'"
v-model:value="formData.value"
placeholder="请输入配置值"
:rows="4"
/>
<!-- 数字输入 -->
<a-input-number
v-else-if="formData.type === 'number'"
v-model:value="formData.value"
placeholder="请输入数字"
style="width: 100%"
/>
<!-- 布尔值 -->
<a-switch
v-else-if="formData.type === 'boolean'"
v-model:checked="formData.value"
checked-children=""
un-checked-children=""
/>
<!-- 下拉框/单选框/多选框 -->
<a-select
v-else-if="['select', 'radio'].includes(formData.type)"
v-model:value="formData.value"
placeholder="请选择配置值"
allow-clear
>
<a-select-option v-for="opt in parsedOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</a-select-option>
</a-select>
<a-checkbox-group
v-else-if="formData.type === 'checkbox'"
v-model:value="formData.value"
>
<a-checkbox v-for="opt in parsedOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</a-checkbox>
</a-checkbox-group>
<!-- 文件上传 -->
<sc-upload
v-else-if="formData.type === 'file'"
v-model="formData.value"
:limit="1"
accept="*/*"
list-type="picture-card"
/>
<!-- JSON编辑器 -->
<a-textarea
v-else-if="formData.type === 'json'"
v-model:value="formData.value"
placeholder='请输入JSON格式数据,例如:{"key": "value"}'
:rows="4"
/>
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" placeholder="请输入排序" :min="0" style="width: 100%" />
</a-form-item>
<a-form-item label="状态" name="status">
<a-radio-group v-model:value="formData.status">
<a-radio :value="1">启用</a-radio>
<a-radio :value="0">禁用</a-radio>
</a-radio-group>
</a-form-item>
<a-form-item label="描述" name="description">
<a-textarea v-model:value="formData.description" placeholder="请输入配置描述" :rows="2" />
</a-form-item>
</a-form>
</a-modal>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { systemApi } from '@/api/system'
const props = defineProps({
visible: Boolean,
record: {
type: Object,
default: null
}
})
const emit = defineEmits(['update:visible', 'success'])
const formRef = ref(null)
const loading = ref(false)
const customGroup = ref('')
const optionsText = ref('')
// 是否编辑模式
const isEdit = computed(() => !!props.record?.id)
// 表单数据
const formData = reactive({
group: 'system',
key: '',
name: '',
type: 'string',
value: '',
options: null,
sort: 0,
status: 1,
description: '',
is_system: false
})
// 表单验证规则
const rules = {
group: [{ required: true, message: '请选择配置分组', trigger: 'change' }],
key: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
type: [{ required: true, message: '请选择数据类型', trigger: 'change' }],
value: [{ required: true, message: '请输入配置值', trigger: 'change' }]
}
// 解析选项
const parsedOptions = computed(() => {
if (!optionsText.value) return []
try {
return optionsText.value
.split('\n')
.filter((line) => line.trim())
.map((line) => {
const [label, value] = line.split(':').map((s) => s.trim())
return { label, value: value || label }
})
} catch {
return []
}
})
// 监听record变化,初始化表单
watch(
() => props.record,
(newRecord) => {
if (newRecord) {
// 编辑模式
Object.assign(formData, {
group: newRecord.group || 'system',
key: newRecord.key || '',
name: newRecord.name || '',
type: newRecord.type || 'string',
value: parseValueByType(newRecord.value, newRecord.type),
options: newRecord.options,
sort: newRecord.sort || 0,
status: newRecord.status ?? 1,
description: newRecord.description || '',
is_system: newRecord.is_system || false
})
// 解析选项
if (newRecord.options && typeof newRecord.options === 'object') {
optionsText.value = newRecord.options
.map((opt) => {
if (typeof opt === 'object') {
return `${opt.label}:${opt.value}`
}
return opt
})
.join('\n')
}
} else {
// 新增模式,重置表单
resetForm()
}
},
{ immediate: true }
)
// 根据类型解析值
const parseValueByType = (value, type) => {
if (!value) return value
switch (type) {
case 'number':
return Number(value)
case 'boolean':
return value === 'true' || value === true || value === 1
case 'checkbox':
if (typeof value === 'string') {
try {
return JSON.parse(value)
} catch {
return value.split(',')
}
}
return value
default:
return value
}
}
// 重置表单
const resetForm = () => {
Object.assign(formData, {
group: 'system',
key: '',
name: '',
type: 'string',
value: '',
options: null,
sort: 0,
status: 1,
description: '',
is_system: false
})
optionsText.value = ''
formRef.value?.clearValidate()
}
// 添加自定义分组
const handleAddCustomGroup = () => {
if (!customGroup.value) {
message.warning('请输入分组名称')
return
}
formData.group = customGroup.value
customGroup.value = ''
message.success('分组已添加')
}
// 处理确定按钮
const handleOk = async () => {
try {
await formRef.value.validate()
loading.value = true
const submitData = { ...formData }
// 处理选项
if (['select', 'radio', 'checkbox'].includes(formData.type) && optionsText.value) {
submitData.options = parsedOptions.value
}
// 处理值类型转换
if (formData.type === 'number') {
submitData.value = Number(submitData.value)
} else if (formData.type === 'boolean') {
submitData.value = submitData.value ? '1' : '0'
} else if (formData.type === 'checkbox' && Array.isArray(submitData.value)) {
submitData.value = submitData.value.join(',')
} else if (formData.type === 'json') {
// 验证JSON格式
try {
JSON.parse(submitData.value)
} catch (e) {
throw new Error('JSON格式不正确')
}
}
if (isEdit.value) {
await systemApi.configs.edit.put(formData.id, submitData)
message.success('更新成功')
} else {
await systemApi.configs.add.post(submitData)
message.success('创建成功')
}
emit('success')
emit('update:visible', false)
resetForm()
} catch (error) {
if (error.message) {
message.error(error.message || '操作失败')
}
} finally {
loading.value = false
}
}
// 处理取消按钮
const handleCancel = () => {
resetForm()
emit('update:visible', false)
}
</script>
<style scoped lang="scss">
:deep(.ant-modal-body) {
max-height: 60vh;
overflow-y: auto;
}
:deep(.ant-select-dropdown) {
.ant-input {
margin-bottom: 8px;
}
}
</style>
@@ -0,0 +1,423 @@
<template>
<div class="pages system-configs-page">
<div class="tool-bar">
<div class="left-panel">
<a-space>
<a-input
v-model:value="searchForm.keyword"
placeholder="配置名称/键名"
allow-clear
style="width: 180px"
/>
<a-select
v-model:value="searchForm.group"
placeholder="配置分组"
allow-clear
style="width: 140px"
:options="groupOptions"
/>
<a-button type="primary" @click="handleSearch">
<template #icon><search-outlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><redo-outlined /></template>
重置
</a-button>
</a-space>
</div>
<div class="right-panel">
<a-button type="primary" @click="handleAdd">
<template #icon><plus-outlined /></template>
新增
</a-button>
<a-dropdown>
<a-button>
批量操作
<down-outlined />
</a-button>
<template #overlay>
<a-menu>
<a-menu-item @click="handleBatchDelete">
<delete-outlined />
批量删除
</a-menu-item>
<a-menu-item @click="handleBatchStatus(1)">
<check-outlined />
批量启用
</a-menu-item>
<a-menu-item @click="handleBatchStatus(0)">
<stop-outlined />
批量禁用
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</div>
</div>
<div class="table-content">
<scTable
ref="tableRef"
:columns="columns"
:data-source="tableData"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
:row-key="(record) => record.id"
@refresh="refreshTable"
@paginationChange="handlePaginationChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'type'">
<a-tag :color="getTypeColor(record.type)">{{ getTypeText(record.type) }}</a-tag>
</template>
<template v-if="column.key === 'value'">
<span v-if="['string', 'number', 'boolean'].includes(record.type)" class="value-text">
{{ formatValue(record.value, record.type) }}
</span>
<span v-else-if="record.type === 'file'" class="file-value">
<file-outlined />
{{ record.value }}
</span>
<a v-else-if="record.type === 'image'" :href="record.value" target="_blank" class="image-value">
<img :src="record.value" alt="预览" class="config-image" />
</a>
<span v-else class="json-value">{{ record.value }}</span>
</template>
<template v-if="column.key === 'status'">
<a-badge :status="record.status ? 'success' : 'default'" :text="record.status ? '启用' : '禁用'" />
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleEdit(record)">
<edit-outlined />
编辑
</a-button>
<a-button
type="link"
size="small"
danger
:disabled="record.is_system"
@click="handleDelete(record)"
>
<delete-outlined />
删除
</a-button>
</a-space>
</template>
</template>
</scTable>
</div>
<!-- 新增/编辑弹窗 -->
<SaveDialog v-model:visible="showSaveDialog" :record="currentRecord" @success="handleSaveSuccess" />
</div>
</template>
<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
PlusOutlined,
DownOutlined,
DeleteOutlined,
CheckOutlined,
StopOutlined,
EditOutlined,
FileOutlined
} from '@ant-design/icons-vue'
import { useTable } from '@/hooks/useTable'
import { systemApi } from '@/api/system'
import SaveDialog from './components/SaveDialog.vue'
// 表格引用
const tableRef = ref(null)
// 搜索表单
const searchForm = reactive({
keyword: '',
group: undefined
})
// 分组选项
const groupOptions = ref([])
// 当前记录
const currentRecord = ref(null)
// 显示新增/编辑弹窗
const showSaveDialog = ref(false)
// 使用 useTable Hook
const { tableData, loading, pagination, rowSelection, handleSearch, handleReset, handlePaginationChange, refreshTable } =
useTable({
api: systemApi.configs.list.get,
searchForm,
needPagination: true
})
// 表格列配置
const columns = [
{
title: 'ID',
dataIndex: 'id',
key: 'id',
width: 80
},
{
title: '配置分组',
dataIndex: 'group',
key: 'group',
width: 120
},
{
title: '配置键',
dataIndex: 'key',
key: 'key',
width: 200,
ellipsis: true
},
{
title: '配置名称',
dataIndex: 'name',
key: 'name',
width: 180
},
{
title: '配置值',
dataIndex: 'value',
key: 'value',
ellipsis: true,
width: 250
},
{
title: '类型',
dataIndex: 'type',
key: 'type',
width: 100,
align: 'center'
},
{
title: '排序',
dataIndex: 'sort',
key: 'sort',
width: 80,
align: 'center'
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
align: 'center'
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
ellipsis: true
},
{
title: '操作',
key: 'action',
width: 150,
fixed: 'right'
}
]
// 获取类型颜色
const getTypeColor = (type) => {
const colors = {
string: 'blue',
text: 'cyan',
number: 'green',
boolean: 'orange',
select: 'purple',
radio: 'purple',
checkbox: 'purple',
file: 'pink',
json: 'geekblue'
}
return colors[type] || 'default'
}
// 获取类型文本
const getTypeText = (type) => {
const texts = {
string: '字符串',
text: '文本',
number: '数字',
boolean: '布尔值',
select: '下拉框',
radio: '单选框',
checkbox: '多选框',
file: '文件',
json: 'JSON'
}
return texts[type] || type
}
// 格式化值
const formatValue = (value, type) => {
if (type === 'boolean') {
return value === 'true' || value === true ? '是' : '否'
}
if (type === 'number') {
return Number(value)
}
return value
}
// 获取分组列表
const loadGroups = async () => {
try {
const res = await systemApi.configs.groups.get()
groupOptions.value = res.data.map((item) => ({ label: item, value: item }))
} catch (error) {
console.error('获取分组列表失败:', error)
}
}
// 新增
const handleAdd = () => {
currentRecord.value = null
showSaveDialog.value = true
}
// 编辑
const handleEdit = (record) => {
currentRecord.value = { ...record }
showSaveDialog.value = true
}
// 删除
const handleDelete = (record) => {
if (record.is_system) {
message.warning('系统配置不能删除')
return
}
Modal.confirm({
title: '确认删除',
content: `确定要删除配置"${record.name}"吗?`,
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
await systemApi.configs.delete.delete(record.id)
message.success('删除成功')
refreshTable()
} catch (error) {
message.error(error.message || '删除失败')
}
}
})
}
// 批量删除
const handleBatchDelete = () => {
const selectedRowKeys = rowSelection.selectedRowKeys
if (selectedRowKeys.length === 0) {
message.warning('请先选择要删除的配置')
return
}
Modal.confirm({
title: '确认删除',
content: `确定要删除选中的 ${selectedRowKeys.length} 条配置吗?`,
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
await systemApi.configs.batchDelete.post({ ids: selectedRowKeys })
message.success('批量删除成功')
rowSelection.selectedRowKeys = []
refreshTable()
} catch (error) {
message.error(error.message || '批量删除失败')
}
}
})
}
// 批量更新状态
const handleBatchStatus = (status) => {
const selectedRowKeys = rowSelection.selectedRowKeys
if (selectedRowKeys.length === 0) {
message.warning('请先选择要操作的配置')
return
}
Modal.confirm({
title: status === 1 ? '确认启用' : '确认禁用',
content: `确定要${status === 1 ? '启用' : '禁用'}选中的 ${selectedRowKeys.length} 条配置吗?`,
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
await systemApi.configs.batchStatus.post({ ids: selectedRowKeys, status })
message.success(`${status === 1 ? '启用' : '禁用'}成功`)
rowSelection.selectedRowKeys = []
refreshTable()
} catch (error) {
message.error(error.message || '操作失败')
}
}
})
}
// 保存成功
const handleSaveSuccess = () => {
showSaveDialog.value = false
refreshTable()
}
// 初始化
onMounted(() => {
loadGroups()
})
</script>
<style scoped lang="scss">
.system-configs-page {
@extend .pages-base-layout;
.value-text {
color: #666;
font-family: monospace;
}
.file-value {
display: flex;
align-items: center;
gap: 4px;
color: #1890ff;
}
.image-value {
display: inline-block;
width: 40px;
height: 40px;
overflow: hidden;
border-radius: 4px;
cursor: pointer;
.config-image {
width: 100%;
height: 100%;
object-fit: cover;
}
&:hover .config-image {
transform: scale(1.1);
transition: transform 0.3s;
}
}
.json-value {
color: #999;
font-family: monospace;
font-size: 12px;
}
}
</style>