更新功能

This commit is contained in:
2026-02-10 22:36:05 +08:00
parent 2248d51887
commit 1969669f0b
32 changed files with 3497 additions and 4701 deletions
@@ -45,7 +45,7 @@ public function tree()
return response()->json([ return response()->json([
'code' => 200, 'code' => 200,
'message' => 'success', 'message' => 'success',
'data' => ['tree' => $result], 'data' => $result,
]); ]);
} }
@@ -41,7 +41,7 @@ public function tree(Request $request)
return response()->json([ return response()->json([
'code' => 200, 'code' => 200,
'message' => 'success', 'message' => 'success',
'data' => ['tree' => $result], 'data' => $result,
]); ]);
} }
@@ -55,7 +55,7 @@ public function menu(Request $request)
return response()->json([ return response()->json([
'code' => 200, 'code' => 200,
'message' => 'success', 'message' => 'success',
'data' => ['tree' => $result], 'data' => $result,
]); ]);
} }
+2 -2
View File
@@ -125,10 +125,10 @@ export function useTable(options = {}) {
// 调用API函数,确保this上下文正确 // 调用API函数,确保this上下文正确
const res = await api(requestParams) const res = await api(requestParams)
if (res.code === 1) { if (res.code === 200) {
// 如果是分页数据 // 如果是分页数据
if (needPagination) { if (needPagination) {
tableData.value = res.data?.data || [] tableData.value = res.data?.list || []
pagination.total = res.data?.total || 0 pagination.total = res.data?.total || 0
} else { } else {
// 非分页数据(如树形数据) // 非分页数据(如树形数据)
@@ -1,530 +1,203 @@
<template> <template>
<div class="department-management"> <div class="pages department-page">
<!-- 搜索表单 --> <div class="tool-bar">
<a-card class="search-card" :bordered="false"> <div class="left-panel">
<a-form :model="searchParams" layout="inline"> <a-form layout="inline" :model="searchForm">
<a-form-item label="关键词"> <a-form-item>
<a-input v-model:value="searchParams.keyword" placeholder="部门名称" allow-clear style="width: 200px" /> <a-input v-model:value="searchForm.keyword" placeholder="请输入部门名称" allow-clear style="width: 200px" />
</a-form-item> </a-form-item>
<a-form-item label="状态"> <a-form-item>
<a-select v-model:value="searchParams.status" allow-clear placeholder="请选择状态" style="width: 120px">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">禁用</a-select-option>
</a-select>
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleSearch">
<template #icon><SearchOutlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<!-- 操作按钮 -->
<a-card class="table-card" :bordered="false">
<template #title>
<a-space>
<a-button type="primary" @click="handleAdd">
<template #icon><PlusOutlined /></template>
新增
</a-button>
<a-button @click="handleExpandAll">
<template #icon><ExpandOutlined /></template>
展开全部
</a-button>
<a-button @click="handleCollapseAll">
<template #icon><CompressOutlined /></template>
折叠全部
</a-button>
<a-button @click="handleExport">
<template #icon><ExportOutlined /></template>
导出
</a-button>
<a-button @click="handleImport">
<template #icon><ImportOutlined /></template>
导入
</a-button>
<a-switch
v-model:checked="viewMode"
checked-children="树形"
un-checked-children="列表"
@change="handleViewModeChange"
/>
</a-space>
</template>
<!-- 树形表格 -->
<a-table
v-if="viewMode"
:columns="treeColumns"
:data-source="treeDataSource"
:loading="loading"
:pagination="false"
:row-selection="treeRowSelection"
:default-expanded-row-keys="expandedKeys"
:expanded-row-keys="expandedKeys"
@expand="handleExpand"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'name'">
<a-space> <a-space>
<a-avatar v-if="record.parent_id === 0" shape="square" :size="24" style="background: #1890ff"> <a-button type="primary" @click="handleSearch">
<template #icon><HomeOutlined /></template> <template #icon><search-outlined /></template>
</a-avatar> </a-button>
<a-avatar v-else shape="square" :size="24" style="background: #52c41a"> <a-button @click="handleReset">
<template #icon><ApartmentOutlined /></template> <template #icon><redo-outlined /></template>
</a-avatar> </a-button>
<span>{{ record.name }}</span>
</a-space> </a-space>
</template> </a-form-item>
<template v-if="column.key === 'status'"> </a-form>
<a-tag :color="record.status === 1 ? 'success' : 'error'"> </div>
{{ record.status === 1 ? '启用' : '禁用' }} <div class="right-panel">
</a-tag> <a-button type="primary" @click="handleAdd">
</template> <template #icon><plus-outlined /></template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleAddChild(record)">添加子部门</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定要删除该部门吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
<!-- 列表表格 -->
<sc-table
v-else
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleAddChild(record)">添加子部门</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定要删除该部门吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</sc-table>
</a-card>
<!-- 新增/编辑弹窗 -->
<a-modal
v-model:open="modalVisible"
:title="modalTitle"
:width="600"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }">
<a-form-item label="上级部门" name="parent_id">
<a-tree-select
v-model:value="formData.parent_id"
:tree-data="departmentTree"
allow-clear
placeholder="请选择上级部门"
:field-names="{ label: 'name', value: 'id', children: 'children' }"
tree-default-expand-all
/>
</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="leader">
<a-input v-model:value="formData.leader" placeholder="请输入负责人" />
</a-form-item>
<a-form-item label="联系电话" name="phone">
<a-input v-model:value="formData.phone" placeholder="请输入联系电话" />
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" :min="0" :max="9999" 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>
</a-modal>
<!-- 导入弹窗 -->
<a-modal v-model:open="importVisible" title="导入部门" :width="500" @ok="handleImportSubmit">
<a-space direction="vertical" style="width: 100%">
<a-alert message="请先下载导入模板,填写完成后上传" type="info" show-icon />
<a-button block @click="handleDownloadTemplate">
<template #icon><DownloadOutlined /></template>
下载导入模板
</a-button> </a-button>
<a-upload <a-button danger :disabled="selectedRows.length === 0" @click="handleBatchDelete">
:file-list="fileList" <template #icon><delete-outlined /></template>
:before-upload="beforeUpload" </a-button>
@remove="handleRemove" </div>
> </div>
<a-button block> <div class="table-content">
<template #icon><UploadOutlined /></template> <scTable ref="tableRef" :columns="columns" :data-source="tableData" :loading="loading" :pagination="false"
选择文件 :row-key="rowKey" :row-selection="rowSelection" @refresh="refreshTable" @select="handleSelectChange"
</a-button> @selectAll="handleSelectAll">
</a-upload> <template #action="{ record }">
</a-space> <a-space>
</a-modal> <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定删除该部门吗?" @confirm="handleDelete(record)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</scTable>
</div>
</div> </div>
<!-- 新增/编辑部门弹窗 -->
<save-dialog v-if="dialog.save" ref="saveDialogRef" @success="handleSaveSuccess" @closed="dialog.save = false" />
</template> </template>
<script setup> <script setup>
import { ref, computed, onMounted } from 'vue' import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue' import { message, Modal } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
PlusOutlined,
DeleteOutlined,
CheckOutlined,
CloseOutlined,
ExpandOutlined,
CompressOutlined,
ExportOutlined,
ImportOutlined,
DownloadOutlined,
UploadOutlined,
HomeOutlined,
ApartmentOutlined,
} from '@ant-design/icons-vue'
import authApi from '@/api/auth'
import scTable from '@/components/scTable/index.vue' import scTable from '@/components/scTable/index.vue'
import saveDialog from './save.vue'
import authApi from '@/api/auth'
import { useTable } from '@/hooks/useTable'
defineOptions({ defineOptions({
name: 'DepartmentManagement', name: 'authDepartment'
}) })
const searchParams = ref({ // 使用useTable hooks
keyword: '', const {
status: undefined, tableRef,
}) searchForm,
tableData,
const loading = ref(false) loading,
const dataSource = ref([]) selectedRows,
const treeDataSource = ref([]) rowSelection,
const pagination = ref({ handleSearch,
current: 1, handleReset,
pageSize: 20, handleSelectChange,
total: 0, handleSelectAll,
}) refreshTable
} = useTable({
const viewMode = ref(true) api: authApi.departments.tree.get,
const expandedKeys = ref([]) searchForm: {
const selectedRowKeys = ref([]) keyword: ''
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys
}, },
})) columns: [],
needPagination: false,
needSelection: true,
immediateLoad: false
})
const treeRowSelection = computed(() => ({ // 对话框状态
selectedRowKeys: selectedRowKeys.value, const dialog = reactive({
onChange: (keys) => { save: false
selectedRowKeys.value = keys })
},
}))
// 弹窗引用
const saveDialogRef = ref(null)
// 行key
const rowKey = 'id'
// 表格列配置
const columns = [ const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 }, { title: '#', dataIndex: '_index', key: '_index', width: 60, align: 'center' },
{ title: '部门名称', dataIndex: 'name', key: 'name', width: 200 }, { title: '部门名称', dataIndex: 'name', key: 'name', width: 300 },
{ title: '上级部门', dataIndex: 'parent_name', key: 'parent_name', width: 200 }, { title: '排序', dataIndex: 'sort', key: 'sort', width: 100, align: 'center' },
{ title: '负责人', dataIndex: 'leader', key: 'leader', width: 120 }, { title: '操作', dataIndex: 'action', key: 'action', width: 220, align: 'center', slot: 'action', fixed: 'right' }
{ title: '联系电话', dataIndex: 'phone', key: 'phone', width: 130 },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'action', width: 220, fixed: 'right' },
] ]
const treeColumns = [
{ title: '部门名称', key: 'name', width: 300 },
{ title: '负责人', dataIndex: 'leader', key: 'leader', width: 120 },
{ title: '联系电话', dataIndex: 'phone', key: 'phone', width: 130 },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '操作', key: 'action', width: 220, fixed: 'right' },
]
const departmentTree = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增部门')
const formData = ref({})
const formRef = ref(null)
const formRules = {
name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
}
const importVisible = ref(false)
const fileList = ref([])
const uploadFile = ref(null)
const fetchData = async () => {
loading.value = true
try {
if (viewMode.value) {
const res = await authApi.departments.tree.get()
treeDataSource.value = res.data
} else {
const res = await authApi.departments.list.get({
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
})
dataSource.value = res.data.list
pagination.value.total = res.data.total
}
} catch (error) {
message.error('获取部门列表失败')
} finally {
loading.value = false
}
}
const fetchDepartmentTree = async () => {
try {
const res = await authApi.departments.tree.get()
departmentTree.value = [{ id: 0, name: '顶级部门', children: res.data }]
} catch (error) {
message.error('获取部门树失败')
}
}
const handleSearch = () => {
pagination.value.current = 1
fetchData()
}
const handleReset = () => {
searchParams.value = {
keyword: '',
status: undefined,
}
pagination.value.current = 1
fetchData()
}
const handleViewModeChange = () => {
selectedRowKeys.value = []
fetchData()
}
const handlePageChange = (page) => {
pagination.value.current = page
fetchData()
}
const handleExpand = (expanded, record) => {
if (expanded) {
expandedKeys.value.push(record.id)
} else {
expandedKeys.value = expandedKeys.value.filter((key) => key !== record.id)
}
}
const handleExpandAll = () => {
const getAllKeys = (data) => {
let keys = []
data.forEach((item) => {
if (item.children && item.children.length > 0) {
keys.push(item.id)
keys = keys.concat(getAllKeys(item.children))
}
})
return keys
}
expandedKeys.value = getAllKeys(treeDataSource.value)
}
const handleCollapseAll = () => {
expandedKeys.value = []
}
// 新增部门
const handleAdd = () => { const handleAdd = () => {
modalTitle.value = '新增部门' dialog.save = true
formData.value = { setTimeout(() => {
parent_id: 0, saveDialogRef.value?.open('add')
status: 1, }, 0)
sort: 0,
}
modalVisible.value = true
} }
const handleAddChild = (record) => { // 查看部门
modalTitle.value = '新增子部门' const handleView = (record) => {
formData.value = { dialog.save = true
parent_id: record.id, setTimeout(() => {
status: 1, saveDialogRef.value?.open('show').setData(record)
sort: 0, }, 0)
}
modalVisible.value = true
} }
// 编辑部门
const handleEdit = (record) => { const handleEdit = (record) => {
modalTitle.value = '编辑部门' dialog.save = true
formData.value = { ...record } setTimeout(() => {
modalVisible.value = true saveDialogRef.value?.open('edit').setData(record)
}, 0)
} }
const handleSubmit = async () => { // 删除部门
const handleDelete = async (record) => {
try { try {
await formRef.value.validate() const res = await authApi.departments.delete.delete(record.id)
if (formData.value.id) { if (res.code === 200) {
await authApi.departments.edit.put(formData.value.id, formData.value) message.success('删除成功')
message.success('更新成功') refreshTable()
} else { } else {
await authApi.departments.add.post(formData.value) message.error(res.message || '删除失败')
message.success('创建成功')
} }
modalVisible.value = false
fetchData()
} catch (error) {
if (error.errorFields) {
return
}
message.error(error.message || '操作失败')
}
}
const handleCancel = () => {
modalVisible.value = false
formData.value = {}
formRef.value?.resetFields()
}
const handleDelete = async (id) => {
try {
await authApi.departments.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) { } catch (error) {
console.error('删除部门失败:', error)
message.error('删除失败') message.error('删除失败')
} }
} }
const handleExport = async () => { // 批量删除
try { const handleBatchDelete = () => {
const res = await authApi.departments.export.post({}) if (selectedRows.value.length === 0) {
const url = window.URL.createObjectURL(new Blob([res])) message.warning('请选择要删除的部门')
const link = document.createElement('a')
link.href = url
link.setAttribute('download', `departments_${Date.now()}.xlsx`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
message.success('导出成功')
} catch (error) {
message.error('导出失败')
}
}
const handleImport = () => {
importVisible.value = true
fileList.value = []
uploadFile.value = null
}
const beforeUpload = (file) => {
const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
if (!isExcel) {
message.error('只能上传 Excel 文件')
return false
}
const isLt10M = file.size / 1024 / 1024 < 10
if (!isLt10M) {
message.error('文件大小不能超过 10MB')
return false
}
uploadFile.value = file
fileList.value = [file]
return false
}
const handleRemove = () => {
uploadFile.value = null
fileList.value = []
}
const handleDownloadTemplate = async () => {
try {
const res = await authApi.departments.downloadTemplate.get()
const url = window.URL.createObjectURL(new Blob([res]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'department_template.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch (error) {
message.error('下载模板失败')
}
}
const handleImportSubmit = async () => {
if (!uploadFile.value) {
message.error('请选择文件')
return return
} }
const formData = new FormData() Modal.confirm({
formData.append('file', uploadFile.value) title: '确认删除',
content: `确定删除选中的 ${selectedRows.value.length} 个部门吗?如果删除项中含有子集将会被一并删除`,
try { okText: '确定',
const res = await authApi.departments.import.post(formData) cancelText: '取消',
message.success(res.message || '导入成功') okType: 'danger',
importVisible.value = false onOk: async () => {
fetchData() try {
} catch (error) { const ids = selectedRows.value.map(item => item.id)
message.error('导入失败') const res = await authApi.departments.batchDelete.post({ ids })
} if (res.code === 200) {
message.success('删除成功')
selectedRows.value = []
refreshTable()
} else {
message.error(res.message || '删除失败')
}
} catch (error) {
console.error('批量删除部门失败:', error)
message.error('删除失败')
}
}
})
} }
// 保存成功回调
const handleSaveSuccess = () => {
refreshTable()
}
// 初始化
onMounted(() => { onMounted(() => {
fetchData() refreshTable()
fetchDepartmentTree()
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.department-management { .department-page {
padding: 16px; display: flex;
flex-direction: column;
height: 100%;
padding: 0;
.search-card { .table-content {
margin-bottom: 16px; flex: 1;
} overflow: hidden;
background: #f5f5f5;
.table-card {
:deep(.ant-card-body) {
padding: 16px;
}
} }
} }
</style> </style>
@@ -0,0 +1,170 @@
<template>
<a-modal :title="titleMap[mode]" :open="visible" :width="500" :destroy-on-close="true" :footer="null"
@cancel="handleCancel">
<a-form :model="form" :rules="rules" :disabled="mode === 'show'" ref="dialogForm" :label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }">
<a-form-item label="上级部门" name="parent_id">
<a-tree-select v-model:value="form.parent_id" :tree-data="departments"
:field-names="departmentFieldNames" :tree-default-expand-all="false" placeholder="请选择上级部门"
allow-clear tree-node-filter-prop="name"
:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" />
</a-form-item>
<a-form-item label="部门名称" name="name">
<a-input v-model:value="form.name" placeholder="请输入部门名称" allow-clear></a-input>
</a-form-item>
<a-form-item label="负责人" name="leader">
<a-input v-model:value="form.leader" placeholder="请输入负责人" allow-clear></a-input>
</a-form-item>
<a-form-item label="联系电话" name="phone">
<a-input v-model:value="form.phone" placeholder="请输入联系电话" allow-clear></a-input>
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="form.sort" :min="0" :max="10000" style="width: 100%" placeholder="请输入排序" />
</a-form-item>
<a-form-item :wrapper-col="{ offset: 5 }">
<div style="display: flex; gap: 10px">
<a-button v-if="mode !== 'show'" type="primary" :loading="isSaveing" @click="submit"> </a-button>
<a-button @click="handleCancel"> </a-button>
</div>
</a-form-item>
</a-form>
</a-modal>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'
defineOptions({
name: 'DepartmentSave'
})
const emit = defineEmits(['success', 'closed'])
const mode = ref('add')
const titleMap = {
add: '新增部门',
edit: '编辑部门',
show: '查看部门'
}
const visible = ref(false)
const isSaveing = ref(false)
// 表单数据
const form = reactive({
id: '',
name: '',
leader: '',
phone: '',
sort: 0,
parent_id: null,
status: 1
})
// 表单引用
const dialogForm = ref()
// 验证规则
const rules = {
name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
sort: [
{ required: true, message: '请输入排序', trigger: 'change' },
{ type: 'number', message: '排序必须为数字', trigger: 'change' }
]
}
// 部门数据
const departments = ref([])
const departmentFieldNames = {
title: 'name',
value: 'id',
children: 'children'
}
// 显示对话框
const open = (openMode = 'add') => {
mode.value = openMode
visible.value = true
return {
setData,
open,
close
}
}
// 关闭对话框
const close = () => {
visible.value = false
}
// 处理取消
const handleCancel = () => {
emit('closed')
visible.value = false
}
// 表单提交方法
const submit = async () => {
try {
await dialogForm.value.validate()
isSaveing.value = true
let res = {}
form.parent_id = form.parent_id || 0
if (mode.value === 'add') {
res = await authApi.departments.add.post(form)
} else {
res = await authApi.departments.edit.put(form.id, form)
}
isSaveing.value = false
if (res.code === 200) {
emit('success', form, mode.value)
visible.value = false
message.success('操作成功')
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('表单验证失败', error)
isSaveing.value = false
}
}
// 加载部门树数据
const loadDepartments = async () => {
try {
const res = await authApi.departments.tree.get()
if (res.code === 200) {
departments.value = res.data || []
}
} catch (error) {
console.error('加载部门树失败:', error)
message.error('加载部门树失败')
}
}
// 表单注入数据
const setData = (data) => {
form.id = data.id
form.name = data.name
form.leader = data.leader || ''
form.phone = data.phone || ''
form.sort = data.sort || 0
form.parent_id = data.parent_id || null
form.status = data.status !== undefined ? data.status : 1
}
// 组件挂载时加载数据
loadDepartments()
// 暴露方法给父组件
defineExpose({
open,
setData,
close
})
</script>
<style></style>
@@ -0,0 +1,408 @@
<template>
<div class="pages online-users-page">
<!-- 统计卡片 -->
<div class="stats-cards">
<a-row :gutter="16">
<a-col :span="6">
<a-card>
<a-statistic title="在线用户总数" :value="onlineCount" :value-style="{ color: '#3f8600' }">
<template #prefix>
<UserOutlined style="font-size: 24px" />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :span="18">
<a-card>
<a-form layout="inline" :model="searchForm">
<a-form-item label="刷新间隔">
<a-select v-model:value="refreshInterval" style="width: 150px" @change="handleRefreshIntervalChange">
<a-select-option :value="0">不自动刷新</a-select-option>
<a-select-option :value="5000">5</a-select-option>
<a-select-option :value="10000">10</a-select-option>
<a-select-option :value="30000">30</a-select-option>
<a-select-option :value="60000">60</a-select-option>
</a-select>
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleRefresh" :loading="loading">
<template #icon><ReloadOutlined /></template>
刷新
</a-button>
<a-button @click="handleRefreshAllOffline">
<template #icon><StopOutlined /></template>
全部下线
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
</a-col>
</a-row>
</div>
<!-- 工具栏 -->
<div class="tool-bar">
<div class="left-panel">
<a-form layout="inline" :model="searchForm">
<a-form-item label="用户名">
<a-input v-model:value="searchForm.keyword" placeholder="请输入用户名" allow-clear style="width: 200px" />
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleSearch">
<template #icon><SearchOutlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</div>
</div>
<!-- 表格内容 -->
<div class="table-content">
<sc-table
ref="tableRef"
:columns="columns"
:data-source="tableData"
:loading="loading"
:pagination="pagination"
:row-key="rowKey"
@refresh="refreshTable"
>
<template #status="{ record }">
<a-tag :color="record.is_online ? 'success' : 'default'">
{{ record.is_online ? '在线' : '离线' }}
</a-tag>
</template>
<template #lastActive="{ record }">
{{ formatDate(record.last_active_at) }}
</template>
<template #action="{ record }">
<a-space>
<a-button type="link" size="small" @click="handleViewSessions(record)">
查看会话
</a-button>
<a-popconfirm
title="确定强制该用户下线吗?"
@confirm="handleOffline(record)"
>
<a-button type="link" size="small" danger>
强制下线
</a-button>
</a-popconfirm>
<a-button
type="link"
size="small"
danger
@click="handleOfflineAll(record)"
>
全部下线
</a-button>
</a-space>
</template>
</sc-table>
</div>
<!-- 会话详情弹窗 -->
<sessions-dialog
v-if="dialog.sessions"
ref="sessionsDialogRef"
@success="handleSessionsSuccess"
@closed="dialog.sessions = false"
/>
</div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { UserOutlined, SearchOutlined, RedoOutlined, ReloadOutlined, StopOutlined } from '@ant-design/icons-vue'
import scTable from '@/components/scTable/index.vue'
import sessionsDialog from './sessions.vue'
import authApi from '@/api/auth'
defineOptions({
name: 'authOnlineUsers'
})
// 表格引用
const tableRef = ref(null)
// 搜索表单
const searchForm = reactive({
keyword: ''
})
// 表格数据
const tableData = ref([])
const loading = ref(false)
const pagination = reactive({
current: 1,
pageSize: 20,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total) => `${total}`
})
// 行key
const rowKey = 'id'
// 在线用户数量
const onlineCount = ref(0)
// 刷新定时器
const refreshInterval = ref(30000) // 默认30秒
let refreshTimer = null
// 对话框状态
const dialog = reactive({
sessions: false
})
// 弹窗引用
const sessionsDialogRef = ref(null)
// 表格列配置
const columns = [
{ title: '#', dataIndex: '_index', key: '_index', width: 60, align: 'center' },
{ title: '用户名', dataIndex: 'username', key: 'username', width: 150 },
{ title: '真实姓名', dataIndex: 'real_name', key: 'real_name', width: 150 },
{ title: '邮箱', dataIndex: 'email', key: 'email', width: 200 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 150 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 100, align: 'center', slot: 'status' },
{ title: '最后活跃时间', dataIndex: 'last_active_at', key: 'last_active_at', width: 180, slot: 'lastActive' },
{ title: '最后登录IP', dataIndex: 'last_login_ip', key: 'last_login_ip', width: 150 },
{ title: '操作', dataIndex: 'action', key: 'action', width: 200, align: 'center', slot: 'action', fixed: 'right' }
]
// 加载在线用户数量
const loadOnlineCount = async () => {
try {
const res = await authApi.onlineUsers.count.get()
if (res.code === 200) {
onlineCount.value = res.data || 0
}
} catch (error) {
console.error('获取在线用户数量失败:', error)
}
}
// 加载在线用户列表
const loadOnlineUsers = async () => {
try {
loading.value = true
const params = {
...searchForm,
limit: pagination.pageSize
}
const res = await authApi.onlineUsers.list.get(params)
loading.value = false
if (res.code === 200) {
// 添加序号
const list = res.data?.list || []
tableData.value = list.map((item, index) => ({
...item,
_index: (pagination.current - 1) * pagination.pageSize + index + 1
}))
pagination.total = res.data?.total || 0
}
} catch (error) {
console.error('加载在线用户列表失败:', error)
loading.value = false
}
}
// 刷新表格
const refreshTable = () => {
loadOnlineCount()
loadOnlineUsers()
}
// 搜索
const handleSearch = () => {
pagination.current = 1
refreshTable()
}
// 重置
const handleReset = () => {
searchForm.keyword = ''
pagination.current = 1
refreshTable()
}
// 刷新按钮
const handleRefresh = () => {
refreshTable()
message.success('刷新成功')
}
// 刷新间隔变化
const handleRefreshIntervalChange = (value) => {
clearRefreshTimer()
if (value > 0) {
startRefreshTimer(value)
}
}
// 启动刷新定时器
const startRefreshTimer = (interval) => {
refreshTimer = setInterval(() => {
refreshTable()
}, interval)
}
// 清除刷新定时器
const clearRefreshTimer = () => {
if (refreshTimer) {
clearInterval(refreshTimer)
refreshTimer = null
}
}
// 查看用户会话
const handleViewSessions = (record) => {
dialog.sessions = true
setTimeout(() => {
sessionsDialogRef.value?.open().setData(record)
}, 0)
}
// 强制用户下线(单个)
const handleOffline = async (record) => {
try {
const res = await authApi.onlineUsers.offline.post(record.id, {})
if (res.code === 200) {
message.success('强制下线成功')
refreshTable()
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('强制下线失败:', error)
message.error('操作失败')
}
}
// 强制用户所有设备下线
const handleOfflineAll = async (record) => {
try {
const res = await authApi.onlineUsers.offlineAll.post(record.id)
if (res.code === 200) {
message.success('全部下线成功')
refreshTable()
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('全部下线失败:', error)
message.error('操作失败')
}
}
// 全部下线
const handleRefreshAllOffline = () => {
Modal.confirm({
title: '确认操作',
content: '确定要强制所有在线用户下线吗?',
okText: '确定',
cancelText: '取消',
okType: 'danger',
onOk: async () => {
try {
// 这里需要遍历所有在线用户并下线
const onlineUsers = tableData.value.filter(user => user.is_online)
for (const user of onlineUsers) {
await authApi.onlineUsers.offlineAll.post(user.id)
}
message.success('全部下线成功')
refreshTable()
} catch (error) {
console.error('全部下线失败:', error)
message.error('操作失败')
}
}
})
}
// 会话操作成功回调
const handleSessionsSuccess = () => {
refreshTable()
}
// 格式化日期
const formatDate = (date) => {
if (!date) return '-'
const d = new Date(date)
return d.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
// 初始化
onMounted(() => {
refreshTable()
// 启动自动刷新
if (refreshInterval.value > 0) {
startRefreshTimer(refreshInterval.value)
}
})
// 组件卸载时清除定时器
onUnmounted(() => {
clearRefreshTimer()
})
</script>
<style scoped lang="scss">
.online-users-page {
display: flex;
flex-direction: column;
height: 100%;
padding: 0;
.stats-cards {
margin-bottom: 16px;
:deep(.ant-card) {
border-radius: 4px;
}
:deep(.ant-statistic-title) {
font-size: 14px;
color: #8c8c8c;
}
:deep(.ant-statistic-content) {
font-size: 24px;
font-weight: 500;
}
}
.tool-bar {
padding: 16px 24px;
background: #fff;
border-bottom: 1px solid #f0f0f0;
}
.table-content {
flex: 1;
overflow: hidden;
background: #f5f5f5;
}
}
</style>
@@ -0,0 +1,285 @@
<template>
<a-modal title="用户会话详情" :open="visible" :width="800" :destroy-on-close="true" :footer="null" @cancel="handleCancel">
<div class="sessions-content">
<!-- 用户信息 -->
<div class="user-info">
<a-descriptions :column="3" bordered size="small">
<a-descriptions-item label="用户名">{{ userInfo.username }}</a-descriptions-item>
<a-descriptions-item label="真实姓名">{{ userInfo.real_name }}</a-descriptions-item>
<a-descriptions-item label="状态">
<a-tag :color="userInfo.is_online ? 'success' : 'default'">
{{ userInfo.is_online ? '在线' : '离线' }}
</a-tag>
</a-descriptions-item>
<a-descriptions-item label="邮箱" :span="2">{{ userInfo.email }}</a-descriptions-item>
<a-descriptions-item label="手机号">{{ userInfo.phone }}</a-descriptions-item>
</a-descriptions>
</div>
<!-- 会话列表 -->
<div class="sessions-list">
<div class="list-header">
<span>会话列表{{ sessions.length }} </span>
<a-button type="link" size="small" danger @click="handleOfflineAll">
全部下线
</a-button>
</div>
<a-list :data-source="sessions" :loading="loading" size="small">
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
<template #avatar>
<a-avatar shape="square" :icon="item.device_type === 'pc' ? 'DesktopOutlined' : 'MobileOutlined'" />
</template>
<template #title>
<div class="session-title">
<span>{{ getDeviceName(item.device_type) }}</span>
<a-tag :color="item.is_online ? 'success' : 'default'" size="small">
{{ item.is_online ? '活跃' : '过期' }}
</a-tag>
</div>
</template>
<template #description>
<div class="session-info">
<div><span class="label">IP地址</span>{{ item.ip_address }}</div>
<div><span class="label">登录时间</span>{{ formatDate(item.created_at) }}</div>
<div><span class="label">最后活跃</span>{{ formatDate(item.last_active_at) }}</div>
<div v-if="item.user_agent"><span class="label">浏览器</span>{{ item.user_agent }}</div>
</div>
</template>
</a-list-item-meta>
<template #actions>
<a-popconfirm
v-if="item.is_online"
title="确定强制该会话下线吗?"
@confirm="handleOffline(item)"
>
<a-button type="link" size="small" danger>
强制下线
</a-button>
</a-popconfirm>
<a-tag v-else color="default" size="small">已过期</a-tag>
</template>
</a-list-item>
</template>
</a-list>
<a-empty v-if="!loading && sessions.length === 0" description="暂无会话数据" :image-size="80" />
</div>
</div>
<template #footer>
<a-button @click="handleCancel"> </a-button>
</template>
</a-modal>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'
defineOptions({
name: 'OnlineUserSessions'
})
const emit = defineEmits(['success', 'closed'])
const visible = ref(false)
const loading = ref(false)
// 用户信息
const userInfo = reactive({
id: '',
username: '',
real_name: '',
email: '',
phone: '',
is_online: false
})
// 会话列表
const sessions = ref([])
// 打开对话框
const open = () => {
visible.value = true
return {
open,
setData,
close
}
}
// 关闭对话框
const close = () => {
visible.value = false
}
// 处理取消
const handleCancel = () => {
emit('closed')
visible.value = false
}
// 加载用户会话
const loadUserSessions = async (userId) => {
try {
loading.value = true
const res = await authApi.onlineUsers.sessions.get(userId)
loading.value = false
if (res.code === 200) {
sessions.value = res.data || []
}
} catch (error) {
console.error('加载用户会话失败:', error)
loading.value = false
message.error('加载会话失败')
}
}
// 设置数据
const setData = (data) => {
userInfo.id = data.id
userInfo.username = data.username
userInfo.real_name = data.real_name
userInfo.email = data.email
userInfo.phone = data.phone
userInfo.is_online = data.is_online
// 加载会话列表
loadUserSessions(data.id)
}
// 强制会话下线
const handleOffline = async (session) => {
try {
const res = await authApi.onlineUsers.offline.post(userInfo.id, { token: session.token })
if (res.code === 200) {
message.success('强制下线成功')
emit('success')
// 重新加载会话列表
loadUserSessions(userInfo.id)
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('强制下线失败:', error)
message.error('操作失败')
}
}
// 全部下线
const handleOfflineAll = async () => {
try {
const res = await authApi.onlineUsers.offlineAll.post(userInfo.id)
if (res.code === 200) {
message.success('全部下线成功')
emit('success')
// 重新加载会话列表
loadUserSessions(userInfo.id)
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('全部下线失败:', error)
message.error('操作失败')
}
}
// 获取设备名称
const getDeviceName = (deviceType) => {
const deviceMap = {
pc: '电脑端',
mobile: '手机端',
tablet: '平板端',
unknown: '未知设备'
}
return deviceMap[deviceType] || deviceMap.unknown
}
// 格式化日期
const formatDate = (date) => {
if (!date) return '-'
const d = new Date(date)
return d.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
// 暴露方法给父组件
defineExpose({
open,
setData,
close
})
</script>
<style scoped lang="scss">
.sessions-content {
.user-info {
margin-bottom: 20px;
:deep(.ant-descriptions-item-label) {
background-color: #fafafa;
font-weight: 500;
}
}
.sessions-list {
.list-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 1px solid #f0f0f0;
span {
font-size: 16px;
font-weight: 500;
color: #262626;
}
}
:deep(.ant-list-item) {
padding: 16px;
border-bottom: 1px solid #f0f0f0;
&:hover {
background-color: #fafafa;
}
}
.session-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 16px;
font-weight: 500;
}
.session-info {
margin-top: 8px;
color: #595959;
div {
margin-bottom: 4px;
&:last-child {
margin-bottom: 0;
}
}
.label {
color: #8c8c8c;
margin-right: 4px;
}
}
}
}
</style>
@@ -1,465 +1,333 @@
<template> <template>
<div class="permission-management"> <div class="pages permission-page">
<!-- 搜索表单 --> <div class="left-box">
<a-card class="search-card" :bordered="false"> <div class="header">
<a-form :model="searchParams" layout="inline"> <a-input v-model:value="menuFilterText" placeholder="搜索菜单..." allow-clear @change="handleMenuSearch">
<a-form-item label="关键词"> <template #prefix>
<a-input v-model:value="searchParams.keyword" placeholder="权限名称/编码" allow-clear style="width: 200px" /> <SearchOutlined style="color: rgba(0, 0, 0, 0.45)" />
</a-form-item> </template>
<a-form-item label="类型"> </a-input>
<a-select v-model:value="searchParams.type" allow-clear placeholder="请选择类型" style="width: 150px"> </div>
<a-select-option value="menu">菜单</a-select-option> <div class="body">
<a-select-option value="api">接口</a-select-option> <a-tree v-model:selectedKeys="selectedMenuKeys" v-model:checkedKeys="checkedMenuKeys"
<a-select-option value="button">按钮</a-select-option> :tree-data="filteredMenuTree" :field-names="{ title: 'title', key: 'id', children: 'children' }"
</a-select> showLine checkable :check-strictly="true" :expand-on-click-node="false" @select="onMenuSelect"
</a-form-item> @check="onMenuCheck">
<a-form-item label="状态"> <template #icon="{ dataRef }">
<a-select v-model:value="searchParams.status" allow-clear placeholder="请选择状态" style="width: 120px"> <FolderOutlined v-if="dataRef.children" />
<a-select-option :value="1">启用</a-select-option> <FileOutlined v-else />
<a-select-option :value="0">禁用</a-select-option> </template>
</a-select> <template #title="{ dataRef }">
</a-form-item> <span class="tree-node-title">{{ dataRef.title }}</span>
<a-form-item> <PlusOutlined class="tree-node-add" @click.stop="handleAdd(dataRef)" />
<a-space> </template>
<a-button type="primary" @click="handleSearch"> </a-tree>
<template #icon><SearchOutlined /></template> </div>
搜索 <div class="footer">
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<!-- 操作按钮 -->
<a-card class="table-card" :bordered="false">
<template #title>
<a-space> <a-space>
<a-button type="primary" @click="handleAdd"> <a-button type="primary" @click="handleAdd(null)">
<template #icon><PlusOutlined /></template> <template #icon><PlusOutlined /></template>
新增 新增
</a-button> </a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchDelete" danger> <a-button danger @click="handleDeleteBatch">
<template #icon><DeleteOutlined /></template> <template #icon><DeleteOutlined /></template>
批量删除 删除
</a-button> </a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus">
<template #icon><CheckOutlined /></template>
批量启用
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus(false)" danger>
<template #icon><CloseOutlined /></template>
批量禁用
</a-button>
<a-switch
v-model:checked="viewMode"
checked-children="树形"
un-checked-children="列表"
@change="handleViewModeChange"
/>
</a-space> </a-space>
</template> </div>
</div>
<!-- 树形表格 --> <div class="right-box">
<a-table <div class="header">
v-if="viewMode" <div class="title">{{ selectedMenu?.title || '请选择权限节点' }}</div>
:columns="treeColumns" </div>
:data-source="treeDataSource" <div class="body">
:loading="loading" <save-form v-if="selectedMenu" :menu="menuTree" :menu-id="selectedMenu.id" :parent-id="parentId"
:pagination="false" @success="handleSaveSuccess" />
:row-selection="treeRowSelection" <a-empty v-else description="请选择左侧权限节点后操作" :image-size="100" />
row-key="id" </div>
> </div>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'name'">
<a-space>
<a-icon v-if="record.icon" :type="record.icon" />
<span>{{ record.name }}</span>
</a-space>
</template>
<template v-if="column.key === 'type'">
<a-tag :color="getTypeColor(record.type)">
{{ getTypeLabel(record.type) }}
</a-tag>
</template>
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleAddChild(record)">添加子权限</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定要删除该权限吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
<!-- 列表表格 -->
<sc-table
v-else
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'name'">
<a-space>
<a-icon v-if="record.icon" :type="record.icon" />
<span>{{ record.name }}</span>
</a-space>
</template>
<template v-if="column.key === 'type'">
<a-tag :color="getTypeColor(record.type)">
{{ getTypeLabel(record.type) }}
</a-tag>
</template>
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleAddChild(record)">添加子权限</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定要删除该权限吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</sc-table>
</a-card>
<!-- 新增/编辑弹窗 -->
<a-modal
v-model:open="modalVisible"
:title="modalTitle"
:width="700"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }">
<a-form-item label="上级权限" name="parent_id">
<a-tree-select
v-model:value="formData.parent_id"
:tree-data="permissionTree"
allow-clear
placeholder="请选择上级权限"
:field-names="{ label: 'name', value: 'id', children: 'children' }"
tree-default-expand-all
/>
</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="code">
<a-input v-model:value="formData.code" placeholder="请输入权限编码,如:system.user.list" />
</a-form-item>
<a-form-item label="权限类型" name="type">
<a-select v-model:value="formData.type" placeholder="请选择权限类型">
<a-select-option value="menu">菜单</a-select-option>
<a-select-option value="api">接口</a-select-option>
<a-select-option value="button">按钮</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="路由" name="route">
<a-input v-model:value="formData.route" placeholder="请输入路由,如:/admin/users" />
</a-form-item>
<a-form-item label="组件" name="component">
<a-input v-model:value="formData.component" placeholder="请输入组件路径" />
</a-form-item>
<a-form-item label="图标" name="icon">
<a-input v-model:value="formData.icon" placeholder="请输入图标名称" />
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" :min="0" :max="9999" 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="meta">
<a-textarea v-model:value="formData.meta" placeholder="JSON格式的元数据" :rows="3" />
</a-form-item>
</a-form>
</a-modal>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, computed, onMounted } from 'vue' import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue' import { message, Modal } from 'ant-design-vue'
import { import { SearchOutlined, FolderOutlined, FileOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
SearchOutlined, import saveForm from './save.vue'
RedoOutlined,
PlusOutlined,
DeleteOutlined,
CheckOutlined,
CloseOutlined,
} from '@ant-design/icons-vue'
import authApi from '@/api/auth' import authApi from '@/api/auth'
import scTable from '@/components/scTable/index.vue'
defineOptions({ defineOptions({
name: 'PermissionManagement', name: 'authPermission'
}) })
const searchParams = ref({ // 菜单树数据
keyword: '', const menuTree = ref([])
type: undefined, const filteredMenuTree = ref([])
status: undefined, const selectedMenuKeys = ref([])
}) const checkedMenuKeys = ref([])
const menuFilterText = ref('')
const loading = ref(false) // 当前选中的菜单
const dataSource = ref([]) const selectedMenu = ref(null)
const treeDataSource = ref([]) const parentId = ref(null)
const pagination = ref({
current: 1,
pageSize: 20,
total: 0,
})
const viewMode = ref(true) // 加载权限树
const selectedRowKeys = ref([]) const loadMenuTree = async () => {
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys
},
}))
const treeRowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys
},
}))
const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '权限名称', key: 'name', width: 200 },
{ title: '权限编码', dataIndex: 'code', key: 'code', width: 200 },
{ title: '类型', key: 'type', width: 100, align: 'center' },
{ title: '路由', dataIndex: 'route', key: 'route', width: 200 },
{ title: '组件', dataIndex: 'component', key: 'component', width: 200 },
{ title: '图标', dataIndex: 'icon', key: 'icon', width: 100 },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'action', width: 220, fixed: 'right' },
]
const treeColumns = [
{ title: '权限名称', key: 'name', width: 300 },
{ title: '权限编码', dataIndex: 'code', key: 'code', width: 200 },
{ title: '类型', key: 'type', width: 100, align: 'center' },
{ title: '路由', dataIndex: 'route', key: 'route', width: 200 },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '操作', key: 'action', width: 220, fixed: 'right' },
]
const permissionTree = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增权限')
const formData = ref({})
const formRef = ref(null)
const formRules = {
name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
code: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
type: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
}
const fetchData = async () => {
loading.value = true
try {
if (viewMode.value) {
const res = await authApi.permissions.tree.get()
treeDataSource.value = res.data
} else {
const res = await authApi.permissions.list.get({
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
})
dataSource.value = res.data.list
pagination.value.total = res.data.total
}
} catch (error) {
message.error('获取权限列表失败')
} finally {
loading.value = false
}
}
const fetchPermissionTree = async () => {
try { try {
const res = await authApi.permissions.tree.get() const res = await authApi.permissions.tree.get()
permissionTree.value = [{ id: 0, name: '顶级权限', children: res.data }] if (res.code === 200) {
menuTree.value = res.data || []
filteredMenuTree.value = res.data || []
}
} catch (error) { } catch (error) {
message.error('获取权限树失败') console.error('加载权限树失败:', error)
} }
} }
const handleSearch = () => { // 权限搜索
pagination.value.current = 1 const handleMenuSearch = (e) => {
fetchData() const keyword = e.target?.value || ''
} menuFilterText.value = keyword
if (!keyword) {
const handleReset = () => { filteredMenuTree.value = menuTree.value
searchParams.value = { return
keyword: '',
type: undefined,
status: undefined,
} }
pagination.value.current = 1
fetchData()
}
const handleViewModeChange = () => { // 递归过滤权限树
selectedRowKeys.value = [] const filterTree = (nodes) => {
fetchData() return nodes.reduce((acc, node) => {
} const isMatch = node.name && node.name.toLowerCase().includes(keyword.toLowerCase())
const filteredChildren = node.children ? filterTree(node.children) : []
const handlePageChange = (page) => { if (isMatch || filteredChildren.length > 0) {
pagination.value.current = page acc.push({
fetchData() ...node,
} children: filteredChildren.length > 0 ? filteredChildren : undefined
})
const handleAdd = () => { }
modalTitle.value = '新增权限' return acc
formData.value = { }, [])
parent_id: 0,
status: 1,
sort: 0,
} }
modalVisible.value = true
filteredMenuTree.value = filterTree(menuTree.value)
} }
const handleAddChild = (record) => { // 查找权限节点
modalTitle.value = '新增子权限' const findMenuNode = (tree, id) => {
formData.value = { for (const node of tree) {
parent_id: record.id, if (node.id === id) {
status: 1, return node
sort: 0, }
if (node.children && node.children.length > 0) {
const found = findMenuNode(node.children, id)
if (found) return found
}
} }
modalVisible.value = true return null
} }
const handleEdit = (record) => { // 查找父节点ID
modalTitle.value = '编辑权限' const findParentId = (tree, id) => {
formData.value = { ...record } for (const node of tree) {
modalVisible.value = true if (node.children && node.children.length > 0) {
const child = node.children.find(child => child.id === id)
if (child) {
return node.id
}
const found = findParentId(node.children, id)
if (found !== null) return found
}
}
return null
} }
const handleSubmit = async () => { // 权限选择事件
const onMenuSelect = (selectedKeys, { selected }) => {
if (selected) {
const menuId = selectedKeys[0]
const menuNode = findMenuNode(menuTree.value, menuId)
selectedMenu.value = menuNode
parentId.value = findParentId(menuTree.value, menuId)
} else {
selectedMenu.value = null
parentId.value = null
}
}
// 权限勾选事件
const onMenuCheck = (checkedKeys, info) => {
console.log('checkedKeys:', checkedKeys, 'info:', info)
}
// 新增权限
const handleAdd = async (parentNode) => {
try { try {
await formRef.value.validate() let newMenuData = {
if (formData.value.id) { parent_id: parentNode ? parentNode.id : 0,
await authApi.permissions.edit.put(formData.value.id, formData.value) name: '新权限',
message.success('更新成功') code: '',
route: '',
component: '',
type: 'menu',
sort: 0,
status: 1
}
const res = await authApi.permissions.add.post(newMenuData)
if (res.code === 200) {
newMenuData.id = res.data.id
message.success('添加成功')
await loadMenuTree()
// 选中新增的权限
selectedMenuKeys.value = [newMenuData.id]
const menuNode = findMenuNode(menuTree.value, newMenuData.id)
selectedMenu.value = menuNode
parentId.value = parentNode ? parentNode.id : null
} else { } else {
await authApi.permissions.add.post(formData.value) message.error(res.message || '添加失败')
message.success('创建成功')
} }
modalVisible.value = false
fetchData()
} catch (error) { } catch (error) {
if (error.errorFields) { console.error('添加权限失败:', error)
return message.error('添加失败')
}
}
// 批量删除权限
const handleDeleteBatch = async () => {
if (checkedMenuKeys.value.length === 0) {
message.warning('请选择需要删除的权限')
return
}
Modal.confirm({
title: '确认删除',
content: `确定删除已选择的 ${checkedMenuKeys.value.length} 个权限吗?`,
okText: '删除',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
try {
const res = await authApi.permissions.batchDelete.post({ ids: checkedMenuKeys.value })
if (res.code === 200) {
message.success('删除成功')
// 如果当前选中的权限被删除了,清空选择
if (selectedMenu.value && checkedMenuKeys.value.includes(selectedMenu.value.id)) {
selectedMenu.value = null
selectedMenuKeys.value = []
}
checkedMenuKeys.value = []
await loadMenuTree()
} else {
message.error(res.message || '删除失败')
}
} catch (error) {
console.error('删除权限失败:', error)
message.error('删除失败')
}
} }
message.error(error.message || '操作失败') })
}
// 保存成功回调
const handleSaveSuccess = async () => {
await loadMenuTree()
// 重新设置当前选中的权限
if (selectedMenu.value) {
const menuNode = findMenuNode(menuTree.value, selectedMenu.value.id)
selectedMenu.value = menuNode
} }
} }
const handleCancel = () => { // 初始化
modalVisible.value = false
formData.value = {}
formRef.value?.resetFields()
}
const handleDelete = async (id) => {
try {
await authApi.permissions.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) {
message.error('删除失败')
}
}
const handleBatchDelete = async () => {
try {
await authApi.permissions.batchDelete.post({ ids: selectedRowKeys.value })
message.success('批量删除成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('批量删除失败')
}
}
const handleBatchStatus = async (status = 1) => {
try {
await authApi.permissions.batchStatus.post({ ids: selectedRowKeys.value, status })
message.success(status ? '批量启用成功' : '批量禁用成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('操作失败')
}
}
const getTypeColor = (type) => {
const colors = {
menu: 'blue',
api: 'green',
button: 'orange',
}
return colors[type] || 'default'
}
const getTypeLabel = (type) => {
const labels = {
menu: '菜单',
api: '接口',
button: '按钮',
}
return labels[type] || type
}
onMounted(() => { onMounted(() => {
fetchData() loadMenuTree()
fetchPermissionTree()
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.permission-management { .permission-page {
padding: 16px; display: flex;
flex-direction: row;
height: 100%;
padding: 0;
.search-card { .left-box {
margin-bottom: 16px; width: 300px;
border-right: 1px solid #f0f0f0;
display: flex;
flex-direction: column;
background: #fff;
.header {
padding: 12px 16px;
border-bottom: 1px solid #f0f0f0;
background: #fafafa;
height: 56px;
}
.body {
flex: 1;
overflow-y: auto;
padding: 12px;
.tree-node-title {
flex: 1;
}
.tree-node-add {
margin-left: 8px;
color: #999;
display: none;
&:hover {
color: #1890ff;
}
}
:deep(.ant-tree-node-content-wrapper) {
width: 100%;
&:hover {
.tree-node-add {
display: inline-block;
}
}
}
}
.footer {
padding: 12px 16px;
border-top: 1px solid #f0f0f0;
background: #fafafa;
}
} }
.table-card { .right-box {
:deep(.ant-card-body) { flex: 1;
padding: 16px; display: flex;
flex-direction: column;
overflow: hidden;
.header {
padding: 16px 24px;
border-bottom: 1px solid #f0f0f0;
background: #fff;
height: 56px;
.title {
font-size: 18px;
font-weight: 500;
color: #333;
}
}
.body {
flex: 1;
overflow-y: auto;
background: #f5f5f5;
} }
} }
} }
@@ -0,0 +1,379 @@
<template>
<div class="save-form">
<a-form :model="form" :rules="rules" ref="dialogForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
<!-- 第一行权限名称和类型 -->
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="权限名称" name="title">
<a-input v-model:value="form.title" placeholder="权限名称" allow-clear />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="类型" name="type" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-radio-group v-model:value="form.type" button-style="solid">
<a-radio-button value="menu">菜单</a-radio-button>
<a-radio-button value="api">接口</a-radio-button>
<a-radio-button value="button">按钮</a-radio-button>
</a-radio-group>
</a-form-item>
</a-col>
</a-row>
<!-- 第二行上级菜单和权限编码 -->
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="上级权限" name="parent_id">
<a-tree-select v-model:value="form.parent_id" :tree-data="menuOptions"
:field-names="menuFieldNames" :tree-default-expand-all="false" show-icon placeholder="顶级权限"
allow-clear tree-node-filter-prop="title" :disabled="!!menuId" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="权限编码" name="name">
<a-input v-model:value="form.name" placeholder="如: system.user.list" allow-clear />
<div class="form-item-msg">格式模块.功能.操作系统唯一标识</div>
</a-form-item>
</a-col>
</a-row>
<!-- 第三行路由地址和组件路径 -->
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="路由地址" name="path">
<a-input v-model:value="form.path" placeholder="/system/users" allow-clear />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="组件路径" name="component">
<a-input v-model:value="form.component" placeholder="system/users/index" allow-clear>
<template #addonBefore>pages/</template>
</a-input>
<div class="form-item-msg">顶级菜单或有子菜单的父节点不需要填写</div>
</a-form-item>
</a-col>
</a-row>
<!-- 第四行菜单图标和排序 -->
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="菜单图标" name="icon">
<sc-icon-picker v-model:value="form.icon" placeholder="请选择图标" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="form.sort" :min="0" :max="10000" style="width: 100%" />
</a-form-item>
</a-col>
</a-row>
<!-- 分隔线 -->
<a-divider />
<!-- 选项设置区域 -->
<div class="options-section">
<h4>选项设置</h4>
<a-row :gutter="16">
<a-col :span="8">
<a-form-item label="是否隐藏" name="hidden" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
<a-checkbox v-model:checked="form.hidden">隐藏菜单</a-checkbox>
<a-checkbox v-model:checked="form.hiddenBreadcrumb">隐藏面包屑</a-checkbox>
</a-form-item>
</a-col>
<a-col :span="8">
<a-form-item label="是否缓存" name="keepAlive" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
<a-switch v-model:checked="form.keepAlive" />
</a-form-item>
</a-col>
<a-col :span="8">
<a-form-item label="是否固定" name="affix" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
<a-switch v-model:checked="form.affix" />
</a-form-item>
</a-col>
</a-row>
</div>
<!-- 状态 -->
<a-divider />
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="状态" name="status" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-switch v-model:checked="statusChecked" checked-children="启用" un-checked-children="禁用" />
</a-form-item>
</a-col>
</a-row>
<!-- 操作按钮 -->
<a-form-item :wrapper-col="{ span: 18, offset: 4 }" style="margin-top: 32px">
<a-space>
<a-button type="primary" @click="handleSave" :loading="loading" size="large">保存</a-button>
<a-button @click="$emit('cancel')" size="large">取消</a-button>
</a-space>
</a-form-item>
</a-form>
</div>
</template>
<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'
import ScIconPicker from '@/components/scIconPicker/index.vue'
defineOptions({
name: 'PermissionSave'
})
const props = defineProps({
menu: { type: [Object, Array], default: () => [] },
menuId: { type: [Number, String], default: null },
parentId: { type: [Number, String], default: null }
})
const emit = defineEmits(['success', 'cancel'])
// 表单数据
const form = reactive({
id: '',
parent_id: 0,
name: '',
title: '',
path: '',
component: '',
icon: '',
sort: 0,
type: 'menu',
status: 1,
// meta 字段内容
hidden: false,
hiddenBreadcrumb: false,
keepAlive: false,
affix: false
})
// 状态开关计算属性
const statusChecked = computed({
get: () => form.status === 1,
set: (val) => {
form.status = val ? 1 : 0
}
})
// 表单引用
const dialogForm = ref()
const loading = ref(false)
// 验证规则
const rules = {
name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
code: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}
// 菜单选项
const menuOptions = ref([])
const menuFieldNames = {
value: 'id',
label: 'title',
children: 'children'
}
// 简单化菜单树,排除自己和子节点
const treeToMap = (tree, excludeId = null) => {
const map = []
tree.forEach(item => {
if (item.id === excludeId) return // 排除自己
const obj = {
id: item.id,
parent_id: item.parent_id,
title: item.title,
children: item.children && item.children.length > 0 ? treeToMap(item.children, excludeId) : null
}
map.push(obj)
})
return map
}
// 查找权限节点
const findMenuNode = (tree, id) => {
for (const node of tree) {
if (node.id === id) {
return node
}
if (node.children && node.children.length > 0) {
const found = findMenuNode(node.children, id)
if (found) return found
}
}
return null
}
// 监听菜单树变化
watch(
() => props.menu,
(newVal) => {
if (newVal) {
// 排除当前编辑的节点,避免选择自己作为父节点
menuOptions.value = treeToMap(newVal, props.menuId)
}
},
{ deep: true, immediate: true }
)
// 监听 menuId 变化,从菜单树中查找并赋值
watch(
() => props.menuId,
(newVal) => {
if (newVal && props.menu && props.menu.length > 0) {
const menuNode = findMenuNode(props.menu, newVal)
if (menuNode) {
setData(menuNode, props.parentId)
}
} else if (!newVal) {
// 清空表单
setData({
id: '',
parent_id: props.parentId || 0,
name: '',
title: '',
route: '',
component: '',
icon: '',
sort: 0,
type: 'menu',
status: 1,
hidden: false,
hiddenBreadcrumb: false,
keepAlive: false,
affix: false
})
}
}
)
// 加载权限详情
const loadMenuDetail = async (id) => {
try {
const res = await authApi.permissions.detail.get(id)
if (res.code === 200 && res.data) {
setData(res.data, props.parentId)
}
} catch (error) {
console.error('加载权限详情失败:', error)
}
}
// 保存
const handleSave = async () => {
try {
await dialogForm.value.validate()
loading.value = true
// 构建提交数据
const submitData = {
id: form.id || undefined,
parent_id: form.parent_id || 0,
name: form.name,
title: form.title,
path: form.path,
component: form.component,
icon: form.icon,
sort: form.sort,
type: form.type,
status: form.status,
meta: {
hidden: form.hidden,
hiddenBreadcrumb: form.hiddenBreadcrumb,
keepAlive: form.keepAlive,
affix: form.affix
}
}
let res = {}
if (form.id) {
res = await authApi.permissions.edit.put(form.id, submitData)
} else {
res = await authApi.permissions.add.post(submitData)
}
loading.value = false
if (res.code === 200) {
message.success('保存成功')
emit('success')
} else {
message.error(res.message || '保存失败')
}
} catch (error) {
console.error('表单验证失败', error)
loading.value = false
}
}
// 表单注入数据
const setData = (data, pid) => {
form.id = data.id || ''
form.parent_id = data.parent_id !== undefined ? data.parent_id : (pid || 0)
form.name = data.name || ''
form.title = data.title || ''
form.path = data.path || ''
form.component = data.component || ''
form.icon = data.icon || ''
form.sort = data.sort || 0
form.type = data.type || 'menu'
form.status = data.status !== undefined ? data.status : 1
// 解析 meta 字段
const meta = data.meta && typeof data.meta === 'string' ? JSON.parse(data.meta) : (data.meta || {})
form.hidden = meta.hidden || false
form.hiddenBreadcrumb = meta.hiddenBreadcrumb || false
form.keepAlive = meta.keepAlive || false
form.affix = meta.affix || false
}
// 初始化
onMounted(() => {
if (props.menuId) {
loadMenuDetail(props.menuId)
} else if (props.parentId) {
form.parent_id = props.parentId
}
})
// 暴露方法给父组件
defineExpose({
setData
})
</script>
<style scoped lang="scss">
.save-form {
padding: 24px;
background: #fff;
.form-item-msg {
font-size: 12px;
color: #8c8c8c;
margin-top: 4px;
line-height: 1.5;
}
.options-section {
margin-top: 16px;
h4 {
font-size: 16px;
font-weight: 500;
color: #262626;
margin-bottom: 24px;
}
}
:deep(.ant-divider) {
margin: 32px 0;
}
:deep(.ant-form-item) {
margin-bottom: 24px;
}
}
</style>
+260 -387
View File
@@ -1,436 +1,309 @@
<template> <template>
<div class="role-management"> <div class="pages role-page">
<!-- 搜索表单 --> <div class="tool-bar">
<a-card class="search-card" :bordered="false"> <div class="left-panel">
<a-form :model="searchParams" layout="inline"> <a-form layout="inline" :model="searchForm">
<a-form-item label="关键词"> <a-form-item label="角色名称">
<a-input v-model:value="searchParams.keyword" placeholder="角色名称/编码" allow-clear style="width: 200px" /> <a-input v-model:value="searchForm.keyword" placeholder="请输入角色名称" allow-clear
</a-form-item> style="width: 180px" />
<a-form-item label="状态"> </a-form-item>
<a-select v-model:value="searchParams.status" allow-clear placeholder="请选择状态" style="width: 120px"> <a-form-item label="状态">
<a-select-option :value="1">启用</a-select-option> <a-select v-model:value="searchForm.status" placeholder="请选择状态" allow-clear style="width: 100px">
<a-select-option :value="0">禁用</a-select-option> <a-select-option :value="1">正常</a-select-option>
</a-select> <a-select-option :value="0">禁用</a-select-option>
</a-form-item> </a-select>
<a-form-item> </a-form-item>
<a-space> <a-form-item>
<a-button type="primary" @click="handleSearch">
<template #icon><SearchOutlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<!-- 操作按钮 -->
<a-card class="table-card" :bordered="false">
<template #title>
<a-space>
<a-button type="primary" @click="handleAdd">
<template #icon><PlusOutlined /></template>
新增
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchCopy">
<template #icon><CopyOutlined /></template>
批量复制
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchDelete" danger>
<template #icon><DeleteOutlined /></template>
批量删除
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus">
<template #icon><CheckOutlined /></template>
批量启用
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus(false)" danger>
<template #icon><CloseOutlined /></template>
批量禁用
</a-button>
</a-space>
</template>
<!-- 数据表格 -->
<sc-table
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space> <a-space>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button> <a-button type="primary" @click="handleSearch">
<a-button type="link" size="small" @click="handlePermissions(record)">权限</a-button> <template #icon><search-outlined /></template>
<a-button type="link" size="small" @click="handleCopy(record)">复制</a-button> 搜索
<a-popconfirm title="确定要删除该角色吗?" @confirm="handleDelete(record.id)"> </a-button>
<a-button type="link" size="small" danger>删除</a-button> <a-button @click="handleReset">
</a-popconfirm> <template #icon><redo-outlined /></template>
重置
</a-button>
</a-space> </a-space>
</a-form-item>
</a-form>
</div>
<div class="right-panel">
<a-dropdown :disabled="selectedRows.length === 0">
<a-button :disabled="selectedRows.length === 0">
批量操作
<down-outlined />
</a-button>
<template #overlay>
<a-menu>
<a-menu-item @click="handleBatchStatus">
<check-circle-outlined />批量启用/禁用
</a-menu-item>
<a-menu-item @click="handleBatchCopy">
<copy-outlined />批量复制
</a-menu-item>
<a-menu-divider />
<a-menu-item @click="handleBatchDelete" danger>
<delete-outlined />批量删除
</a-menu-item>
</a-menu>
</template> </template>
</a-dropdown>
<a-button type="primary" @click="handleAdd">
<template #icon><plus-outlined /></template>
新增
</a-button>
</div>
</div>
<div class="table-content">
<scTable ref="tableRef" :columns="columns" :data-source="tableData" :loading="loading"
:pagination="pagination" :row-key="rowKey" :row-selection="rowSelection" @refresh="refreshTable"
@paginationChange="handlePaginationChange" @select="handleSelectChange" @selectAll="handleSelectAll">
<template #status="{ record }">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '正常' : '禁用' }}
</a-tag>
</template> </template>
</sc-table> <template #action="{ record }">
</a-card> <a-space>
<a-button type="link" size="small" @click="handleView(record)">查看</a-button>
<!-- 新增/编辑弹窗 --> <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-modal <a-button type="link" size="small" @click="handlePermission(record)">权限</a-button>
v-model:open="modalVisible" <a-button type="link" size="small" @click="handleCopy(record)">复制</a-button>
:title="modalTitle" <a-popconfirm title="确定删除该角色吗?" @confirm="handleDelete(record)">
:width="600" <a-button type="link" size="small" danger>删除</a-button>
@ok="handleSubmit" </a-popconfirm>
@cancel="handleCancel" </a-space>
> </template>
<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }"> </scTable>
<a-form-item label="角色名称" name="name"> </div>
<a-input v-model:value="formData.name" placeholder="请输入角色名称" />
</a-form-item>
<a-form-item label="角色编码" name="code">
<a-input v-model:value="formData.code" placeholder="请输入角色编码" :disabled="!!formData.id" />
</a-form-item>
<a-form-item label="描述" name="description">
<a-textarea v-model:value="formData.description" placeholder="请输入描述" :rows="3" />
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" :min="0" :max="9999" 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>
</a-modal>
<!-- 权限分配弹窗 -->
<a-modal
v-model:open="permissionVisible"
title="分配权限"
:width="600"
@ok="handlePermissionSubmit"
@cancel="permissionVisible = false"
>
<a-tree
v-model:checkedKeys="checkedPermissions"
checkable
:tree-data="permissionTree"
:field-names="{ title: 'name', key: 'id', children: 'children' }"
default-expand-all
/>
</a-modal>
<!-- 复制弹窗 -->
<a-modal
v-model:open="copyVisible"
title="复制角色"
:width="500"
@ok="handleCopySubmit"
@cancel="copyVisible = false"
>
<a-form ref="copyFormRef" :model="copyFormData" :rules="copyFormRules" :label-col="{ span: 6 }">
<a-form-item label="角色名称" name="name">
<a-input v-model:value="copyFormData.name" placeholder="请输入角色名称" />
</a-form-item>
<a-form-item label="角色编码" name="code">
<a-input v-model:value="copyFormData.code" placeholder="请输入角色编码" />
</a-form-item>
<a-form-item label="描述" name="description">
<a-textarea v-model:value="copyFormData.description" placeholder="请输入描述" :rows="3" />
</a-form-item>
<a-form-item label="状态" name="status">
<a-radio-group v-model:value="copyFormData.status">
<a-radio :value="1">启用</a-radio>
<a-radio :value="0">禁用</a-radio>
</a-radio-group>
</a-form-item>
</a-form>
</a-modal>
</div> </div>
<!-- 新增/编辑角色弹窗 -->
<save-dialog v-if="dialog.save" ref="saveDialogRef" @success="handleSaveSuccess" @closed="dialog.save = false" />
<!-- 权限设置弹窗 -->
<permission-dialog v-if="dialog.permission" ref="permissionDialogRef" @success="permissionSuccess"
@closed="dialog.permission = false" />
</template> </template>
<script setup> <script setup>
import { ref, computed, onMounted } from 'vue' import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue' import { message, Modal } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
PlusOutlined,
DeleteOutlined,
CheckOutlined,
CloseOutlined,
CopyOutlined,
} from '@ant-design/icons-vue'
import authApi from '@/api/auth'
import scTable from '@/components/scTable/index.vue' import scTable from '@/components/scTable/index.vue'
import saveDialog from './save.vue'
import permissionDialog from './permission.vue'
import authApi from '@/api/auth'
import { useTable } from '@/hooks/useTable'
defineOptions({ defineOptions({
name: 'RoleManagement', name: 'authRole'
}) })
const searchParams = ref({ // 使用useTable hooks
keyword: '', const {
status: undefined, tableRef,
}) searchForm,
tableData,
const loading = ref(false) loading,
const dataSource = ref([]) pagination,
const pagination = ref({ selectedRows,
current: 1, rowSelection,
pageSize: 20, handleSearch,
total: 0, handleReset,
}) handlePaginationChange,
handleSelectChange,
const selectedRowKeys = ref([]) handleSelectAll,
const rowSelection = computed(() => ({ refreshTable
selectedRowKeys: selectedRowKeys.value, } = useTable({
onChange: (keys) => { api: authApi.roles.list.get,
selectedRowKeys.value = keys searchForm: {
keyword: '',
status: null
}, },
})) columns: [],
needPagination: true,
needSelection: true
})
// 对话框状态
const dialog = reactive({
save: false,
permission: false
})
// 弹窗引用
const saveDialogRef = ref(null)
const permissionDialogRef = ref(null)
// 行key
const rowKey = 'id'
// 表格列配置
const columns = [ const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 }, { title: 'ID', dataIndex: 'id', key: 'id', width: 80, align: 'center' },
{ title: '角色名称', dataIndex: 'name', key: 'name', width: 150 }, { title: '角色名称', dataIndex: 'name', key: 'name', width: 200 },
{ title: '角色编码', dataIndex: 'code', key: 'code', width: 150 }, { title: '角色编码', dataIndex: 'code', key: 'code', width: 200 },
{ title: '描述', dataIndex: 'description', key: 'description', width: 200 }, { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' }, { title: '排序', dataIndex: 'sort', key: 'sort', width: 100, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' }, { title: '状态', dataIndex: 'status', key: 'status', width: 100, align: 'center', slot: 'status' },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 }, { title: '操作', dataIndex: 'action', key: 'action', width: 260, align: 'center', slot: 'action', fixed: 'right' }
{ title: '操作', key: 'action', width: 250, fixed: 'right' },
] ]
const modalVisible = ref(false)
const modalTitle = ref('新增角色')
const formData = ref({})
const formRef = ref(null)
const formRules = {
name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
}
const permissionVisible = ref(false)
const currentRole = ref(null)
const permissionTree = ref([])
const checkedPermissions = ref([])
const copyVisible = ref(false)
const copyFormData = ref({})
const copyFormRef = ref(null)
const copyFormRules = {
name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
}
const fetchData = async () => {
loading.value = true
try {
const res = await authApi.roles.list.get({
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
})
dataSource.value = res.data.list
pagination.value.total = res.data.total
} catch (error) {
message.error('获取角色列表失败')
} finally {
loading.value = false
}
}
const fetchPermissionTree = async () => {
try {
const res = await authApi.permissions.tree.get()
permissionTree.value = res.data
} catch (error) {
message.error('获取权限树失败')
}
}
const handleSearch = () => {
pagination.value.current = 1
fetchData()
}
const handleReset = () => {
searchParams.value = {
keyword: '',
status: undefined,
}
pagination.value.current = 1
fetchData()
}
const handlePageChange = (page) => {
pagination.value.current = page
fetchData()
}
// 新增角色
const handleAdd = () => { const handleAdd = () => {
modalTitle.value = '新增角色' dialog.save = true
formData.value = { setTimeout(() => {
status: 1, saveDialogRef.value?.open('add')
sort: 0, }, 0)
}
modalVisible.value = true
} }
// 查看角色
const handleView = (record) => {
dialog.save = true
setTimeout(() => {
saveDialogRef.value?.open('show').setData(record)
}, 0)
}
// 编辑角色
const handleEdit = (record) => { const handleEdit = (record) => {
modalTitle.value = '编辑角色' dialog.save = true
formData.value = { ...record } setTimeout(() => {
modalVisible.value = true saveDialogRef.value?.open('edit').setData(record)
}, 0)
} }
const handleSubmit = async () => { // 删除角色
const handleDelete = async (record) => {
try { try {
await formRef.value.validate() const res = await authApi.roles.delete.delete(record.id)
if (formData.value.id) { if (res.code === 200) {
await authApi.roles.edit.put(formData.value.id, formData.value) message.success('删除成功')
message.success('更新成功') refreshTable()
} else { } else {
await authApi.roles.add.post(formData.value) message.error(res.message || '删除失败')
message.success('创建成功')
} }
modalVisible.value = false
fetchData()
} catch (error) {
if (error.errorFields) {
return
}
message.error(error.message || '操作失败')
}
}
const handleCancel = () => {
modalVisible.value = false
formData.value = {}
formRef.value?.resetFields()
}
const handleDelete = async (id) => {
try {
await authApi.roles.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) { } catch (error) {
console.error('删除角色失败:', error)
message.error('删除失败') message.error('删除失败')
} }
} }
const handleBatchDelete = async () => { // 批量删除
try { const handleBatchDelete = () => {
await authApi.roles.batchDelete.post({ ids: selectedRowKeys.value }) if (selectedRows.value.length === 0) {
message.success('批量删除成功') message.warning('请选择要删除的角色')
selectedRowKeys.value = [] return
fetchData()
} catch (error) {
message.error('批量删除失败')
} }
}
const handleBatchStatus = async (status = 1) => { Modal.confirm({
try { title: '确认删除',
await authApi.roles.batchStatus.post({ ids: selectedRowKeys.value, status }) content: `确定删除选中的 ${selectedRows.value.length} 个角色吗?`,
message.success(status ? '批量启用成功' : '批量禁用成功') okText: '确定',
selectedRowKeys.value = [] cancelText: '取消',
fetchData() okType: 'danger',
} catch (error) { onOk: async () => {
message.error('操作失败') try {
} const ids = selectedRows.value.map(item => item.id)
} const res = await authApi.roles.batchDelete.post({ ids })
if (res.code === 200) {
const handlePermissions = async (record) => { message.success('删除成功')
currentRole.value = record selectedRows.value = []
permissionVisible.value = true refreshTable()
try { } else {
const res = await authApi.roles.permissions.get(record.id) message.error(res.message || '删除失败')
checkedPermissions.value = res.data.map((p) => p.id) }
} catch (error) { } catch (error) {
message.error('获取角色权限失败') console.error('批量删除角色失败:', error)
} message.error('删除失败')
} }
const handlePermissionSubmit = async () => {
try {
await authApi.roles.permissions.post(currentRole.value.id, {
permission_ids: checkedPermissions.value,
})
message.success('分配权限成功')
permissionVisible.value = false
} catch (error) {
message.error('分配权限失败')
}
}
const handleCopy = (record) => {
copyFormData.value = {
name: `${record.name}_copy`,
code: `${record.code}_copy`,
description: record.description,
status: record.status,
}
copyVisible.value = true
}
const handleCopySubmit = async () => {
try {
await copyFormRef.value.validate()
await authApi.roles.copy.post(selectedRowKeys.value[0] || currentRole.value.id, copyFormData.value)
message.success('复制成功')
copyVisible.value = false
fetchData()
} catch (error) {
if (error.errorFields) {
return
} }
message.error(error.message || '复制失败') })
}
} }
const handleBatchCopy = async () => { // 批量更新状态
try { const handleBatchStatus = () => {
await authApi.roles.batchCopy.post({ if (selectedRows.value.length === 0) {
ids: selectedRowKeys.value, message.warning('请选择要操作的角色')
name: copyFormData.value.name, return
code: copyFormData.value.code,
})
message.success('批量复制成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('批量复制失败')
} }
Modal.confirm({
title: '确认操作',
content: '确定要批量启用/禁用选中的角色吗?',
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
const ids = selectedRows.value.map(item => item.id)
const status = selectedRows.value[0].status === 1 ? 0 : 1
const res = await authApi.roles.batchStatus.post({ ids, status })
if (res.code === 200) {
message.success('操作成功')
selectedRows.value = []
refreshTable()
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('批量更新状态失败:', error)
message.error('操作失败')
}
}
})
} }
onMounted(() => { // 复制角色
fetchData() const handleCopy = (record) => {
fetchPermissionTree() // TODO: 实现复制角色弹窗
}) message.info('复制角色功能开发中...')
}
// 批量复制角色
const handleBatchCopy = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要复制的角色')
return
}
// TODO: 实现批量复制角色弹窗
message.info('批量复制角色功能开发中...')
}
// 权限设置
const handlePermission = (record) => {
if (!record && selectedRows.value.length !== 1) {
message.error('请选择一个角色进行权限设置')
return
}
const roleData = record || selectedRows.value[0]
dialog.permission = true
setTimeout(() => {
permissionDialogRef.value?.open().setData(roleData)
}, 0)
}
// 保存成功回调
const handleSaveSuccess = () => {
refreshTable()
}
// 权限设置成功回调
const permissionSuccess = () => {
refreshTable()
}
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.role-management { .role-page {
padding: 16px; display: flex;
flex-direction: column;
height: 100%;
padding: 0;
.search-card { .table-content {
margin-bottom: 16px; flex: 1;
} overflow: hidden;
.table-card {
:deep(.ant-card-body) {
padding: 16px;
}
} }
} }
</style> </style>
@@ -0,0 +1,150 @@
<template>
<a-modal title="角色权限设置" :open="visible" :width="600" :destroy-on-close="true" :footer="null" @cancel="handleCancel">
<div class="permission-content">
<div class="permission-tree">
<a-tree ref="menuTreeRef" v-model:checkedKeys="checkedPermissionIds" :tree-data="permissionTree"
:field-names="fieldNames" :checkable="true" :default-expand-all="true"
:check-strictly="false" :selectable="false">
<template #title="{ name }">
{{ name }}
</template>
</a-tree>
</div>
</div>
<template #footer>
<a-button @click="handleCancel"> </a-button>
<a-button type="primary" :loading="isSaveing" @click="submit"> </a-button>
</template>
</a-modal>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'
const emit = defineEmits(['success', 'closed'])
const visible = ref(false)
const isSaveing = ref(false)
const menuTreeRef = ref()
// 权限树数据
const permissionTree = ref([])
const checkedPermissionIds = ref([])
// 树字段映射
const fieldNames = {
title: 'name',
key: 'id',
children: 'children'
}
// 表单数据
const form = reactive({
role_id: '',
permission_ids: []
})
// 打开对话框
const open = () => {
visible.value = true
return {
open,
setData,
close
}
}
// 关闭对话框
const close = () => {
visible.value = false
}
// 处理取消
const handleCancel = () => {
emit('closed')
visible.value = false
}
// 提交保存
const submit = async () => {
try {
isSaveing.value = true
// 获取选中的权限 ID
form.permission_ids = checkedPermissionIds.value || []
const res = await authApi.roles.permissions.post(form.role_id, { permission_ids: form.permission_ids })
isSaveing.value = false
if (res.code === 200) {
emit('success', form)
visible.value = false
message.success('操作成功')
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('保存权限失败:', error)
isSaveing.value = false
message.error('操作失败')
}
}
// 获取权限树
const loadPermissionTree = async () => {
try {
const res = await authApi.permissions.tree.get()
permissionTree.value = res.data || []
} catch (error) {
console.error('获取权限树失败:', error)
message.error('获取权限树失败')
}
}
// 获取角色已有权限
const loadRolePermissions = async (roleId) => {
try {
const res = await authApi.roles.permissions.get(roleId)
if (res.code === 200 && res.data) {
checkedPermissionIds.value = res.data.map(item => item.id)
}
} catch (error) {
console.error('获取角色权限失败:', error)
}
}
// 设置数据
const setData = async (data) => {
form.role_id = data.id
checkedPermissionIds.value = []
// 加载角色已有的权限
await loadRolePermissions(data.id)
}
// 组件挂载时加载数据
loadPermissionTree()
// 暴露方法给父组件
defineExpose({
open,
setData,
close
})
</script>
<style scoped>
.permission-content {
padding: 20px 0;
}
.permission-tree {
max-height: 500px;
overflow-y: auto;
border: 1px solid #e8e8e8;
padding: 16px;
border-radius: 4px;
}
</style>
@@ -0,0 +1,145 @@
<template>
<a-modal :title="titleMap[mode]" :open="visible" :width="500" :destroy-on-close="true" :footer="null"
@cancel="handleCancel">
<a-form :model="form" :rules="rules" :disabled="mode === 'show'" ref="dialogForm" :label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }">
<a-form-item label="角色名称" name="name">
<a-input v-model:value="form.name" placeholder="请输入角色名称" allow-clear></a-input>
</a-form-item>
<a-form-item label="角色编码" name="code">
<a-input v-model:value="form.code" placeholder="请输入角色编码" allow-clear :disabled="mode === 'edit'"></a-input>
</a-form-item>
<a-form-item label="角色描述" name="description">
<a-textarea v-model:value="form.description" placeholder="请输入角色描述" :rows="4" allow-clear></a-textarea>
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="form.sort" :min="0" :step="1" style="width: 100%" placeholder="请输入排序" />
</a-form-item>
<a-form-item label="状态" name="status">
<a-switch v-model:checked="statusChecked" checked-children="启用" un-checked-children="禁用" />
</a-form-item>
</a-form>
<template #footer>
<a-button @click="handleCancel"> </a-button>
<a-button v-if="mode !== 'show'" type="primary" :loading="isSaveing" @click="submit"> </a-button>
</template>
</a-modal>
</template>
<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'
const emit = defineEmits(['success', 'closed'])
const mode = ref('add')
const titleMap = {
add: '新增角色',
edit: '编辑角色',
show: '查看角色'
}
const visible = ref(false)
const isSaveing = ref(false)
// 表单数据
const form = reactive({
id: '',
name: '',
code: '',
description: '',
sort: 1,
status: 1
})
// 状态开关计算属性
const statusChecked = computed({
get: () => form.status === 1,
set: (val) => {
form.status = val ? 1 : 0
}
})
// 表单引用
const dialogForm = ref()
// 验证规则
const rules = {
name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
code: [
{ required: true, message: '请输入角色编码', trigger: 'blur' },
{ pattern: /^[a-zA-Z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线', trigger: 'blur' }
],
sort: [
{ required: true, message: '请输入排序', trigger: 'change' },
{ type: 'number', message: '排序必须为数字', trigger: 'change' }
]
}
// 显示对话框
const open = (openMode = 'add') => {
mode.value = openMode
visible.value = true
return {
setData,
open,
close
}
}
// 关闭对话框
const close = () => {
visible.value = false
}
// 处理取消
const handleCancel = () => {
emit('closed')
visible.value = false
}
// 表单提交方法
const submit = async () => {
try {
await dialogForm.value.validate()
isSaveing.value = true
let res = {}
if (mode.value === 'add') {
res = await authApi.roles.add.post(form)
} else {
res = await authApi.roles.edit.put(form.id, form)
}
isSaveing.value = false
if (res.code === 200) {
emit('success', form, mode.value)
visible.value = false
message.success('操作成功')
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('表单验证失败', error)
isSaveing.value = false
}
}
// 表单注入数据
const setData = (data) => {
form.id = data.id
form.name = data.name
form.code = data.code
form.description = data.description || ''
form.sort = data.sort
form.status = data.status !== undefined ? data.status : 1
}
// 暴露方法给父组件
defineExpose({
open,
setData,
close
})
</script>
<style></style>
+459 -433
View File
@@ -1,524 +1,550 @@
<template> <template>
<div class="user-management"> <div class="pages user-page">
<!-- 搜索表单 --> <div class="left-box">
<a-card class="search-card" :bordered="false"> <div class="header">
<a-form :model="searchParams" layout="inline"> <a-input v-model:value="departmentKeyword" placeholder="搜索部门..." allow-clear @change="handleDeptSearch">
<a-form-item label="关键词"> <template #prefix>
<a-input v-model:value="searchParams.keyword" placeholder="用户名/真实姓名/邮箱" allow-clear style="width: 200px" /> <search-outlined style="color: rgba(0, 0, 0, 0.45)" />
</a-form-item> </template>
<a-form-item label="部门"> </a-input>
<a-tree-select </div>
v-model:value="searchParams.department_id" <div class="body">
:tree-data="departmentTree" <a-tree v-model:selectedKeys="selectedDeptKeys" :tree-data="filteredDepartmentTree"
allow-clear :field-names="{ title: 'name', key: 'id', children: 'children' }" show-line @select="onDeptSelect">
show-search <template #icon="{ dataRef }">
placeholder="请选择部门" <apartment-outlined v-if="dataRef.children && dataRef.children.length > 0" />
style="width: 200px" <user-outlined v-else />
:field-names="{ label: 'name', value: 'id', children: 'children' }" </template>
tree-default-expand-all </a-tree>
/> </div>
</a-form-item> </div>
<a-form-item label="角色"> <div class="right-box">
<a-select v-model:value="searchParams.role_id" allow-clear placeholder="请选择角色" style="width: 150px"> <div class="tool-bar">
<a-select-option v-for="role in roles" :key="role.id" :value="role.id"> <div class="left-panel">
{{ role.name }} <a-form layout="inline" :model="searchForm">
</a-select-option> <a-form-item label="用户名">
</a-select> <a-input v-model:value="searchForm.username" placeholder="请输入用户名" allow-clear
</a-form-item> style="width: 140px" />
<a-form-item label="状态"> </a-form-item>
<a-select v-model:value="searchParams.status" allow-clear placeholder="请选择状态" style="width: 120px"> <a-form-item label="姓名">
<a-select-option :value="1">启用</a-select-option> <a-input v-model:value="searchForm.real_name" placeholder="请输入姓名" allow-clear
<a-select-option :value="0">禁用</a-select-option> style="width: 140px" />
</a-select> </a-form-item>
</a-form-item> <a-form-item label="邮箱">
<a-form-item> <a-input v-model:value="searchForm.email" placeholder="请输入邮箱" allow-clear
<a-space> style="width: 160px" />
<a-button type="primary" @click="handleSearch"> </a-form-item>
<template #icon><SearchOutlined /></template> <a-form-item label="状态">
搜索 <a-select v-model:value="searchForm.status" placeholder="请选择状态" allow-clear style="width: 100px">
<a-select-option :value="1">正常</a-select-option>
<a-select-option :value="0">禁用</a-select-option>
</a-select>
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleSearch">
<template #icon><search-outlined /></template>
搜索
</a-button>
<a-button @click="handleUserReset">
<template #icon><redo-outlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</div>
<div class="right-panel">
<a-dropdown :disabled="selectedRows.length === 0">
<a-button :disabled="selectedRows.length === 0">
批量操作
<down-outlined />
</a-button> </a-button>
<a-button @click="handleReset"> <template #overlay>
<template #icon><RedoOutlined /></template> <a-menu>
重置 <a-menu-item @click="handleBatchStatus">
<check-circle-outlined />批量启用/禁用
</a-menu-item>
<a-menu-item @click="handleBatchDepartment">
<apartment-outlined />批量分配部门
</a-menu-item>
<a-menu-item @click="handleBatchRoles">
<team-outlined />批量分配角色
</a-menu-item>
<a-menu-divider />
<a-menu-item @click="handleBatchDelete" danger>
<delete-outlined />批量删除
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
<a-dropdown>
<a-button>
更多
<down-outlined />
</a-button> </a-button>
</a-space> <template #overlay>
</a-form-item> <a-menu>
</a-form> <a-menu-item @click="handleImport">
</a-card> <import-outlined />导入用户
</a-menu-item>
<!-- 操作按钮 --> <a-menu-item @click="handleExport">
<a-card class="table-card" :bordered="false"> <export-outlined />导出用户
<template #title> </a-menu-item>
<a-space> <a-menu-item @click="handleDownloadTemplate">
<download-outlined />下载模板
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
<a-button type="primary" @click="handleAdd"> <a-button type="primary" @click="handleAdd">
<template #icon><PlusOutlined /></template> <template #icon><plus-outlined /></template>
新增 新增
</a-button> </a-button>
<a-button @click="handleExport"> </div>
<template #icon><ExportOutlined /></template> </div>
导出 <div class="table-content">
</a-button> <scTable ref="tableRef" :columns="columns" :data-source="tableData" :loading="loading"
<a-button @click="handleImport"> :pagination="pagination" :row-key="rowKey" :row-selection="rowSelection" @refresh="refreshTable"
<template #icon><ImportOutlined /></template> @paginationChange="handlePaginationChange" @select="handleSelectChange" @selectAll="handleSelectAll">
导入 <template #avatar="{ record }">
</a-button> <a-avatar :src="record.avatar" :size="32">
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchDelete" danger> <template #icon><user-outlined /></template>
<template #icon><DeleteOutlined /></template>
批量删除
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus">
<template #icon><CheckOutlined /></template>
批量启用
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus(false)" danger>
<template #icon><CloseOutlined /></template>
批量禁用
</a-button>
</a-space>
</template>
<!-- 数据表格 -->
<sc-table
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'avatar'">
<a-avatar :src="record.avatar" :size="40">
<template #icon><UserOutlined /></template>
</a-avatar> </a-avatar>
</template> </template>
<template v-if="column.key === 'status'"> <template #status="{ record }">
<a-tag :color="record.status === 1 ? 'success' : 'error'"> <a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }} {{ record.status === 1 ? '正常' : '禁用' }}
</a-tag> </a-tag>
</template> </template>
<template v-if="column.key === 'roles'"> <template #department="{ record }">
<a-tag v-for="role in record.roles" :key="role.id" color="blue">{{ role.name }}</a-tag> {{ record.department?.name || '-' }}
</template> </template>
<template v-if="column.key === 'action'"> <template #roles="{ record }">
<a-tag v-for="role in record.roles" :key="role.id" color="blue">
{{ role.name }}
</a-tag>
</template>
<template #action="{ record }">
<a-space> <a-space>
<a-button type="link" size="small" @click="handleView(record)">查看</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button> <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-button type="link" size="small" @click="handleRole(record)">角色</a-button>
<a-button type="link" size="small" @click="handleResetPassword(record)">重置密码</a-button> <a-button type="link" size="small" @click="handleResetPassword(record)">重置密码</a-button>
<a-popconfirm title="确定删除该用户吗?" @confirm="handleDelete(record.id)"> <a-popconfirm title="确定删除该用户吗?" @confirm="handleDelete(record)">
<a-button type="link" size="small" danger>删除</a-button> <a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm> </a-popconfirm>
</a-space> </a-space>
</template> </template>
</template> </scTable>
</sc-table> </div>
</a-card> </div>
<!-- 新增/编辑弹窗 -->
<a-modal
v-model:open="modalVisible"
:title="modalTitle"
:width="600"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }">
<a-form-item label="用户名" name="username">
<a-input v-model:value="formData.username" placeholder="请输入用户名" :disabled="!!formData.id" />
</a-form-item>
<a-form-item v-if="!formData.id" label="密码" name="password">
<a-input-password v-model:value="formData.password" placeholder="请输入密码" />
</a-form-item>
<a-form-item label="真实姓名" name="real_name">
<a-input v-model:value="formData.real_name" placeholder="请输入真实姓名" />
</a-form-item>
<a-form-item label="邮箱" name="email">
<a-input v-model:value="formData.email" placeholder="请输入邮箱" />
</a-form-item>
<a-form-item label="手机号" name="phone">
<a-input v-model:value="formData.phone" placeholder="请输入手机号" />
</a-form-item>
<a-form-item label="部门" name="department_id">
<a-tree-select
v-model:value="formData.department_id"
:tree-data="departmentTree"
placeholder="请选择部门"
:field-names="{ label: 'name', value: 'id', children: 'children' }"
tree-default-expand-all
/>
</a-form-item>
<a-form-item label="角色" name="role_ids">
<a-select v-model:value="formData.role_ids" mode="multiple" placeholder="请选择角色" :options="roleOptions" />
</a-form-item>
<a-form-item label="头像" name="avatar">
<sc-upload v-model="formData.avatar" :limit="1" accept="image/*" list-type="picture-card" />
</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>
</a-modal>
<!-- 导入弹窗 -->
<a-modal v-model:open="importVisible" title="导入用户" :width="500" @ok="handleImportSubmit">
<a-space direction="vertical" style="width: 100%">
<a-alert message="请先下载导入模板,填写完成后上传" type="info" show-icon />
<a-button block @click="handleDownloadTemplate">
<template #icon><DownloadOutlined /></template>
下载导入模板
</a-button>
<a-upload
:file-list="fileList"
:before-upload="beforeUpload"
@remove="handleRemove"
>
<a-button block>
<template #icon><UploadOutlined /></template>
选择文件
</a-button>
</a-upload>
</a-space>
</a-modal>
</div> </div>
<!-- 新增/编辑用户弹窗 -->
<save-dialog v-if="dialog.save" ref="saveDialogRef" @success="handleSaveSuccess" @closed="dialog.save = false" />
<!-- 角色设置弹窗 -->
<role-dialog v-if="dialog.role" ref="roleDialogRef" @success="handleRoleSuccess" @closed="dialog.role = false" />
</template> </template>
<script setup> <script setup>
import { ref, computed, onMounted, h } from 'vue' import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue' import { message, Modal } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
PlusOutlined,
DeleteOutlined,
CheckOutlined,
CloseOutlined,
ExportOutlined,
ImportOutlined,
DownloadOutlined,
UploadOutlined,
UserOutlined,
} from '@ant-design/icons-vue'
import authApi from '@/api/auth'
import scTable from '@/components/scTable/index.vue' import scTable from '@/components/scTable/index.vue'
import scUpload from '@/components/scUpload/index.vue' import saveDialog from './save.vue'
import roleDialog from './role.vue'
import authApi from '@/api/auth'
import { useTable } from '@/hooks/useTable'
defineOptions({ defineOptions({
name: 'UserManagement', name: 'authUser'
}) })
const searchParams = ref({ // 使用useTable hooks
keyword: '', const {
department_id: undefined, tableRef,
role_id: undefined, searchForm,
status: undefined, tableData,
}) loading,
pagination,
const loading = ref(false) selectedRows,
const dataSource = ref([]) rowSelection,
const pagination = ref({ handleSearch,
current: 1, handleReset,
pageSize: 20, handlePaginationChange,
total: 0, handleSelectChange,
}) handleSelectAll,
refreshTable
const selectedRowKeys = ref([]) } = useTable({
const rowSelection = computed(() => ({ api: authApi.users.list.get,
selectedRowKeys: selectedRowKeys.value, searchForm: {
onChange: (keys) => { username: '',
selectedRowKeys.value = keys real_name: '',
email: '',
phone: '',
department_id: null,
status: null
}, },
})) columns: [],
needPagination: true,
needSelection: true
})
// 对话框状态
const dialog = reactive({
save: false,
role: false,
department: false
})
// 弹窗引用
const saveDialogRef = ref(null)
const roleDialogRef = ref(null)
const departmentDialogRef = ref(null)
// 部门树数据
const departmentTree = ref([])
const filteredDepartmentTree = ref([])
const selectedDeptKeys = ref([])
const departmentKeyword = ref('')
// 行key
const rowKey = 'id'
// 表格列配置
const columns = [ const columns = [
{ title: '头像', key: 'avatar', width: 80, align: 'center' }, { title: '头像', dataIndex: 'avatar', key: 'avatar', width: 80, align: 'center', slot: 'avatar' },
{ title: '用户名', dataIndex: 'username', key: 'username', width: 120 }, { title: '用户名', dataIndex: 'username', key: 'username', width: 150 },
{ title: '真实姓名', dataIndex: 'real_name', key: 'real_name', width: 120 }, { title: '姓名', dataIndex: 'real_name', key: 'real_name', width: 150 },
{ title: '邮箱', dataIndex: 'email', key: 'email', width: 180 }, { title: '邮箱', dataIndex: 'email', key: 'email', width: 180 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 130 }, { title: '手机号', dataIndex: 'phone', key: 'phone', width: 130 },
{ title: '部门', dataIndex: 'department_name', key: 'department_name', width: 150 }, { title: '部门', dataIndex: 'department', key: 'department', slot: 'department', width: 150 },
{ title: '角色', key: 'roles', width: 200 }, { title: '角色', dataIndex: 'roles', key: 'roles', width: 200, slot: 'roles' },
{ title: '状态', key: 'status', width: 80, align: 'center' }, { title: '状态', dataIndex: 'status', key: 'status', width: 100, align: 'center', slot: 'status' },
{ title: '最后登录', dataIndex: 'last_login_at', key: 'last_login_at', width: 180 }, { title: '最后登录', dataIndex: 'last_login_at', key: 'last_login_at', width: 180 },
{ title: '操作', key: 'action', width: 200, fixed: 'right' }, { title: '操作', dataIndex: 'action', key: 'action', width: 280, align: 'center', slot: 'action', fixed: 'right' }
] ]
const departmentTree = ref([]) // 加载部门树
const roles = ref([]) const loadDepartmentTree = async () => {
const roleOptions = computed(() => roles.value.map((r) => ({ label: r.name, value: r.id })))
const modalVisible = ref(false)
const modalTitle = ref('新增用户')
const formData = ref({})
const formRef = ref(null)
const formRules = {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
real_name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
email: [{ type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }],
phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
}
const importVisible = ref(false)
const fileList = ref([])
const uploadFile = ref(null)
const fetchData = async () => {
loading.value = true
try {
const res = await authApi.users.list.get({
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
})
dataSource.value = res.data.list
pagination.value.total = res.data.total
} catch (error) {
message.error('获取用户列表失败')
} finally {
loading.value = false
}
}
const fetchDepartments = async () => {
try { try {
const res = await authApi.departments.tree.get() const res = await authApi.departments.tree.get()
departmentTree.value = [{ id: 0, name: '顶级部门', children: res.data }] if (res.code === 200) {
} catch (error) { departmentTree.value = res.data || []
message.error('获取部门树失败') filteredDepartmentTree.value = res.data || []
}
}
const fetchRoles = async () => {
try {
const res = await authApi.roles.all.get()
roles.value = res.data
} catch (error) {
message.error('获取角色列表失败')
}
}
const handleSearch = () => {
pagination.value.current = 1
fetchData()
}
const handleReset = () => {
searchParams.value = {
keyword: '',
department_id: undefined,
role_id: undefined,
status: undefined,
}
pagination.value.current = 1
fetchData()
}
const handlePageChange = (page) => {
pagination.value.current = page
fetchData()
}
const handleAdd = () => {
modalTitle.value = '新增用户'
formData.value = {
status: 1,
role_ids: [],
}
modalVisible.value = true
}
const handleEdit = (record) => {
modalTitle.value = '编辑用户'
formData.value = {
...record,
role_ids: record.roles?.map((r) => r.id) || [],
}
modalVisible.value = true
}
const handleSubmit = async () => {
try {
await formRef.value.validate()
if (formData.value.id) {
await authApi.users.edit.put(formData.value.id, formData.value)
message.success('更新成功')
} else {
await authApi.users.add.post(formData.value)
message.success('创建成功')
} }
modalVisible.value = false
fetchData()
} catch (error) { } catch (error) {
if (error.errorFields) { console.error('加载部门树失败:', error)
return
}
message.error(error.message || '操作失败')
} }
} }
const handleCancel = () => { // 部门搜索
modalVisible.value = false const handleDeptSearch = (e) => {
formData.value = {} const keyword = e.target?.value || ''
formRef.value?.resetFields() departmentKeyword.value = keyword
} if (!keyword) {
filteredDepartmentTree.value = departmentTree.value
const handleDelete = async (id) => { return
try {
await authApi.users.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) {
message.error('删除失败')
} }
}
const handleBatchDelete = async () => { // 递归过滤部门树
try { const filterTree = (nodes) => {
await authApi.users.batchDelete.post({ ids: selectedRowKeys.value }) return nodes.reduce((acc, node) => {
message.success('批量删除成功') const isMatch = node.name && node.name.toLowerCase().includes(keyword.toLowerCase())
selectedRowKeys.value = [] const filteredChildren = node.children ? filterTree(node.children) : []
fetchData()
} catch (error) { if (isMatch || filteredChildren.length > 0) {
message.error('批量删除失败') acc.push({
...node,
children: filteredChildren.length > 0 ? filteredChildren : undefined
})
}
return acc
}, [])
} }
filteredDepartmentTree.value = filterTree(departmentTree.value)
} }
const handleBatchStatus = async (status = 1) => { // 重置 - 覆盖useTable的handleReset以添加额外逻辑
try { const handleUserReset = () => {
await authApi.users.batchStatus.post({ ids: selectedRowKeys.value, status }) searchForm.username = ''
message.success(status ? '批量启用成功' : '批量禁用成功') searchForm.real_name = ''
selectedRowKeys.value = [] searchForm.email = ''
fetchData() searchForm.phone = ''
} catch (error) { searchForm.status = null
message.error('操作失败') searchForm.department_id = null
selectedDeptKeys.value = []
departmentKeyword.value = ''
filteredDepartmentTree.value = departmentTree.value
handleReset()
}
// 部门选择事件
const onDeptSelect = (selectedKeys) => {
if (selectedKeys && selectedKeys.length > 0) {
searchForm.department_id = selectedKeys[0]
} else {
searchForm.department_id = null
} }
handleSearch()
} }
const handleResetPassword = (record) => { // 批量删除
const input = h('input', { const handleBatchDelete = () => {
type: 'password', if (selectedRows.value.length === 0) {
placeholder: '请输入新密码', message.warning('请选择要删除的用户')
onInput: (e) => { return
record.newPassword = e.target.value }
},
})
modal.confirm({ Modal.confirm({
title: '重置密码', title: '确认删除',
content: h('div', { style: { marginTop: '16px' } }, [input]), content: `确定删除选中的 ${selectedRows.value.length} 个用户吗?`,
okText: '删除',
okType: 'danger',
cancelText: '取消',
onOk: async () => { onOk: async () => {
if (!record.newPassword) {
message.error('请输入新密码')
return Promise.reject()
}
try { try {
await authApi.users.edit.put(record.id, { password: record.newPassword }) const ids = selectedRows.value.map(item => item.id)
message.success('重置密码成功') const res = await authApi.users.batchDelete.post({ ids })
if (res.code === 200) {
message.success('删除成功')
selectedRows.value = []
refreshTable()
} else {
message.error(res.message || '删除失败')
}
} catch (error) { } catch (error) {
message.error('重置密码失败') console.error('批量删除用户失败:', error)
return Promise.reject() message.error('删除失败')
} }
}, }
}) })
} }
// 批量更新状态
const handleBatchStatus = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要操作的用户')
return
}
Modal.confirm({
title: '确认操作',
content: '确定要批量启用/禁用选中的用户吗?',
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
const ids = selectedRows.value.map(item => item.id)
const status = selectedRows.value[0].status === 1 ? 0 : 1
const res = await authApi.users.batchStatus.post({ ids, status })
if (res.code === 200) {
message.success('操作成功')
selectedRows.value = []
refreshTable()
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('批量更新状态失败:', error)
message.error('操作失败')
}
}
})
}
// 批量分配部门
const handleBatchDepartment = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要分配部门的用户')
return
}
// TODO: 实现批量分配部门弹窗
message.info('批量分配部门功能开发中...')
}
// 批量分配角色
const handleBatchRoles = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要分配角色的用户')
return
}
// TODO: 实现批量分配角色弹窗
message.info('批量分配角色功能开发中...')
}
// 导出数据
const handleExport = async () => { const handleExport = async () => {
try { try {
const res = await authApi.users.export.post({}) const ids = selectedRows.value.map(item => item.id)
const url = window.URL.createObjectURL(new Blob([res])) const res = await authApi.users.export.post({ ids: ids.length > 0 ? ids : undefined })
const link = document.createElement('a') if (res) {
link.href = url // 创建下载链接
link.setAttribute('download', `users_${Date.now()}.xlsx`) const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
document.body.appendChild(link) const url = window.URL.createObjectURL(blob)
link.click() const link = document.createElement('a')
document.body.removeChild(link) link.href = url
message.success('导出成功') link.download = `users_${Date.now()}.xlsx`
link.click()
window.URL.revokeObjectURL(url)
message.success('导出成功')
}
} catch (error) { } catch (error) {
console.error('导出失败:', error)
message.error('导出失败') message.error('导出失败')
} }
} }
const handleImport = () => { // 下载模板
importVisible.value = true
fileList.value = []
uploadFile.value = null
}
const beforeUpload = (file) => {
const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
if (!isExcel) {
message.error('只能上传 Excel 文件')
return false
}
const isLt10M = file.size / 1024 / 1024 < 10
if (!isLt10M) {
message.error('文件大小不能超过 10MB')
return false
}
uploadFile.value = file
fileList.value = [file]
return false
}
const handleRemove = () => {
uploadFile.value = null
fileList.value = []
}
const handleDownloadTemplate = async () => { const handleDownloadTemplate = async () => {
try { try {
const res = await authApi.users.downloadTemplate.get() const res = await authApi.users.downloadTemplate.get()
const url = window.URL.createObjectURL(new Blob([res])) if (res) {
const link = document.createElement('a') const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
link.href = url const url = window.URL.createObjectURL(blob)
link.setAttribute('download', 'user_template.xlsx') const link = document.createElement('a')
document.body.appendChild(link) link.href = url
link.click() link.download = 'user_template.xlsx'
document.body.removeChild(link) link.click()
window.URL.revokeObjectURL(url)
message.success('下载成功')
}
} catch (error) { } catch (error) {
message.error('下载模板失败') console.error('下载模板失败:', error)
message.error('下载失败')
} }
} }
const handleImportSubmit = async () => { // 导入用户
if (!uploadFile.value) { const handleImport = () => {
message.error('请选择文件') // TODO: 实现导入弹窗
return message.info('导入功能开发中...')
} }
const formData = new FormData() // 重置密码
formData.append('file', uploadFile.value) const handleResetPassword = (record) => {
Modal.confirm({
title: '重置密码',
content: '确定要重置该用户的密码吗?重置后密码为: 123456',
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
// TODO: 实现重置密码接口
message.success('密码重置成功')
} catch (error) {
console.error('重置密码失败:', error)
message.error('重置密码失败')
}
}
})
}
// 新增用户
const handleAdd = () => {
dialog.save = true
setTimeout(() => {
saveDialogRef.value?.open('add')
}, 0)
}
// 查看用户
const handleView = (record) => {
dialog.save = true
setTimeout(() => {
saveDialogRef.value?.open('show').setData(record)
}, 0)
}
// 编辑用户
const handleEdit = (record) => {
dialog.save = true
setTimeout(() => {
saveDialogRef.value?.open('edit').setData(record)
}, 0)
}
// 设置角色
const handleRole = (record) => {
dialog.role = true
setTimeout(() => {
roleDialogRef.value?.open().setData(record)
}, 0)
}
// 删除用户
const handleDelete = async (record) => {
try { try {
const res = await authApi.users.import.post(formData) const res = await authApi.users.delete.delete(record.id)
message.success(res.message || '导入成功') if (res.code === 200) {
importVisible.value = false message.success('删除成功')
fetchData() refreshTable()
} else {
message.error(res.message || '删除失败')
}
} catch (error) { } catch (error) {
message.error('导入失败') console.error('删除用户失败:', error)
message.error('删除失败')
} }
} }
// 保存成功回调
const handleSaveSuccess = () => {
refreshTable()
}
// 角色设置成功回调
const handleRoleSuccess = () => {
refreshTable()
}
// 初始化
onMounted(() => { onMounted(() => {
fetchData() loadDepartmentTree()
fetchDepartments()
fetchRoles()
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.user-management { .user-page {
padding: 16px; display: flex;
flex-direction: row;
height: 100%;
padding: 0;
.search-card { .left-box {
margin-bottom: 16px; width: 260px;
border-right: 1px solid #f0f0f0;
display: flex;
flex-direction: column;
background: #fff;
.header {
padding: 12px 16px;
font-weight: 500;
border-bottom: 1px solid #f0f0f0;
font-size: 14px;
background: #fafafa;
}
.body {
flex: 1;
overflow-y: auto;
padding: 16px;
}
} }
.table-card { .right-box {
:deep(.ant-card-body) { flex: 1;
padding: 16px; display: flex;
flex-direction: column;
overflow: hidden;
.table-content {
flex: 1;
overflow: hidden;
background: #f5f5f5;
} }
} }
} }
@@ -0,0 +1,124 @@
<template>
<a-modal title="角色设置" :open="visible" :width="500" :destroy-on-close="true" :footer="null" @cancel="handleCancel">
<div class="role-content">
<a-checkbox-group v-model:value="checkedRoles" style="width: 100%">
<a-space direction="vertical" style="width: 100%">
<a-checkbox v-for="role in roleList" :key="role.id" :value="role.id" style="width: 100%">
{{ role.name }}
</a-checkbox>
</a-space>
</a-checkbox-group>
</div>
<template #footer>
<a-button @click="handleCancel"> </a-button>
<a-button type="primary" :loading="isSaveing" @click="submit"> </a-button>
</template>
</a-modal>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'
const emit = defineEmits(['success', 'closed'])
const visible = ref(false)
const isSaveing = ref(false)
// 表单数据
const form = reactive({
id: '',
role_ids: []
})
// 选中的角色
const checkedRoles = ref([])
// 角色列表
const roleList = ref([])
// 打开对话框
const open = () => {
visible.value = true
return {
open,
setData,
close
}
}
// 关闭对话框
const close = () => {
visible.value = false
}
// 处理取消
const handleCancel = () => {
emit('closed')
visible.value = false
}
// 提交保存
const submit = async () => {
try {
isSaveing.value = true
// 获取选中的角色 ID
form.role_ids = checkedRoles.value || []
const res = await authApi.users.batchRoles.post({
ids: [form.id],
role_ids: form.role_ids
})
isSaveing.value = false
if (res.code === 200) {
emit('success', form)
visible.value = false
message.success('操作成功')
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('保存角色失败:', error)
isSaveing.value = false
message.error('操作失败')
}
}
// 获取角色列表
const getRoles = async () => {
try {
const res = await authApi.roles.all.get()
roleList.value = res.data || []
} catch (error) {
console.error('获取角色列表失败:', error)
message.error('获取角色列表失败')
}
}
// 设置数据
const setData = (data) => {
form.id = data.id
checkedRoles.value = data.roles ? data.roles.map(item => item.id) : []
}
// 组件挂载时加载数据
getRoles()
// 暴露方法给父组件
defineExpose({
open,
setData,
close
})
</script>
<style scoped>
.role-content {
padding: 20px 0;
max-height: 400px;
overflow-y: auto;
}
</style>
@@ -0,0 +1,260 @@
<template>
<a-modal :title="titleMap[mode]" :open="visible" :width="500" :destroy-on-close="true" :mask-closable="false"
:footer="null" @cancel="handleCancel">
<a-form :model="form" :rules="rules" :disabled="mode === 'show'" ref="dialogForm" :label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }">
<a-form-item label="头像" name="avatar">
<sc-upload v-model="form.avatar" :cropper="true" :aspectRatio="1" title="上传头像"></sc-upload>
</a-form-item>
<a-form-item label="用户名" name="username">
<a-input v-model:value="form.username" placeholder="请输入用户名" allow-clear :disabled="mode === 'edit'" />
</a-form-item>
<a-form-item label="真实姓名" name="real_name">
<a-input v-model:value="form.real_name" placeholder="请输入真实姓名" allow-clear />
</a-form-item>
<a-form-item label="邮箱" name="email">
<a-input v-model:value="form.email" placeholder="请输入邮箱" allow-clear />
</a-form-item>
<a-form-item label="手机号" name="phone">
<a-input v-model:value="form.phone" placeholder="请输入手机号" allow-clear />
</a-form-item>
<template v-if="mode === 'add'">
<a-form-item label="登录密码" name="password">
<a-input-password v-model:value="form.password" placeholder="请输入登录密码" allow-clear />
</a-form-item>
<a-form-item label="确认密码" name="password2">
<a-input-password v-model:value="form.password2" placeholder="请再次输入密码" allow-clear />
</a-form-item>
</template>
<a-form-item label="所属部门" name="department_id">
<a-tree-select v-model:value="form.department_id" :tree-data="department"
:field-names="departmentFieldNames" :tree-default-expand-all="false" show-icon placeholder="请选择部门" allow-clear
tree-node-filter-prop="name" />
</a-form-item>
<a-form-item label="所属角色" name="role_ids">
<a-select v-model:value="form.role_ids" mode="multiple" placeholder="请选择角色" allow-clear style="width: 100%">
<a-select-option v-for="role in rolesList" :key="role.id" :value="role.id">
{{ role.name }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="状态" name="status">
<a-switch v-model:checked="statusChecked" checked-children="启用" un-checked-children="禁用" />
</a-form-item>
</a-form>
<template #footer>
<a-button @click="handleCancel"> </a-button>
<a-button v-if="mode !== 'show'" type="primary" :loading="isSaveing" @click="submit"> </a-button>
</template>
</a-modal>
</template>
<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import scUpload from '@/components/scUpload/index.vue'
import authApi from '@/api/auth'
const emit = defineEmits(['success', 'closed'])
const mode = ref('add')
const titleMap = {
add: '新增用户',
edit: '编辑用户',
show: '查看用户'
}
const visible = ref(false)
const isSaveing = ref(false)
// 表单数据
const form = reactive({
id: '',
username: '',
avatar: '',
real_name: '',
email: '',
phone: '',
department_id: null,
role_ids: [],
status: 1
})
// 状态开关计算属性
const statusChecked = computed({
get: () => form.status === 1,
set: (val) => {
form.status = val ? 1 : 0
}
})
// 表单引用
const dialogForm = ref()
// 验证规则
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
],
real_name: [
{ required: true, message: '请输入真实姓名', trigger: 'blur' },
{ min: 2, max: 50, message: '真实姓名长度在 2 到 50 个字符', trigger: 'blur' }
],
email: [
{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
],
phone: [
{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入登录密码', trigger: 'blur' },
{ min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
{
validator: (rule, value) => {
if (form.password2 !== '') {
dialogForm.value?.validateFields('password2')
}
return Promise.resolve()
},
trigger: 'change'
}
],
password2: [
{ required: true, message: '请再次输入密码', trigger: 'blur' },
{
validator: (rule, value) => {
if (value !== form.password) {
return Promise.reject(new Error('两次输入密码不一致!'))
}
return Promise.resolve()
},
trigger: 'blur'
}
]
}
// 部门数据
const department = ref([])
const departmentFieldNames = {
value: 'id',
label: 'name',
children: 'children'
}
// 角色列表
const rolesList = ref([])
// 显示对话框
const open = (openMode = 'add') => {
mode.value = openMode
visible.value = true
return {
setData,
open,
close
}
}
// 关闭对话框
const close = () => {
visible.value = false
}
// 处理取消
const handleCancel = () => {
emit('closed')
visible.value = false
}
// 加载部门树数据
const loadDepartment = async () => {
try {
const res = await authApi.departments.tree.get()
if (res.code === 200) {
department.value = res.data || []
}
} catch (error) {
console.error('加载部门树失败:', error)
}
}
// 加载角色列表
const loadRoles = async () => {
try {
const res = await authApi.roles.all.get()
if (res.code === 200) {
rolesList.value = res.data || []
}
} catch (error) {
console.error('加载角色列表失败:', error)
}
}
// 表单提交方法
const submit = async () => {
try {
await dialogForm.value.validate()
isSaveing.value = true
const submitData = {
username: form.username,
avatar: form.avatar,
real_name: form.real_name,
email: form.email,
phone: form.phone,
department_id: form.department_id,
role_ids: form.role_ids,
status: form.status
}
if (mode.value === 'add') {
submitData.password = form.password
}
let res = {}
if (mode.value === 'add') {
res = await authApi.users.add.post(submitData)
} else {
res = await authApi.users.edit.put(form.id, submitData)
}
isSaveing.value = false
if (res.code === 200) {
emit('success', form, mode.value)
visible.value = false
message.success('操作成功')
} else {
message.error(res.message || '操作失败')
}
} catch (error) {
console.error('表单验证失败', error)
isSaveing.value = false
}
}
// 表单注入数据
const setData = (data) => {
form.id = data.id
form.username = data.username
form.avatar = data.avatar
form.real_name = data.real_name
form.email = data.email
form.phone = data.phone
form.department_id = data.department_id
form.role_ids = data.roles ? data.roles.map(item => item.id) : []
form.status = data.status !== undefined ? data.status : 1
}
// 组件挂载时加载数据
loadDepartment()
loadRoles()
// 暴露方法给父组件
defineExpose({
open,
setData,
close
})
</script>
<style></style>
@@ -1,50 +0,0 @@
<template>
<div class="icon-picker-demo">
<a-card title="图标选择器演示" style="max-width: 600px; margin: 20px auto;">
<a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
<a-form-item label="选择图标">
<sc-icon-picker v-model="selectedIcon" @change="handleIconChange" />
</a-form-item>
<a-form-item label="选中值">
<a-input v-model:value="selectedIcon" readonly />
</a-form-item>
<a-form-item label="图标预览">
<div v-if="selectedIcon" class="icon-preview">
<component :is="selectedIcon" style="font-size: 48px;" />
</div>
<a-empty v-else description="未选择图标" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
</a-form-item>
</a-form>
</a-card>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { Empty } from 'ant-design-vue'
import ScIconPicker from '@/components/scIconPicker/index.vue'
const selectedIcon = ref('')
const handleIconChange = (value) => {
console.log('图标已选择:', value)
}
</script>
<style scoped lang="scss">
.icon-picker-demo {
padding: 20px;
.icon-preview {
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
min-height: 88px;
}
}
</style>
+421 -24
View File
@@ -1,47 +1,444 @@
<template> <template>
<div class="home-page"> <div class="dashboard-container">
<a-skeleton v-if="loading" active /> <!-- 统计卡片 -->
<component v-else :is="dashboardComponent" @on-mounted="handleMounted" /> <a-row :gutter="16" class="stats-cards">
<a-col :xs="24" :sm="12" :lg="6">
<a-card :loading="loading" hoverable>
<a-statistic
title="用户总数"
:value="stats.userCount"
:prefix="UserOutlined"
:value-style="{ color: '#1890ff' }"
>
<template #suffix>
<a-tag color="blue">活跃</a-tag>
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :xs="24" :sm="12" :lg="6">
<a-card :loading="loading" hoverable>
<a-statistic
title="角色数量"
:value="stats.roleCount"
:prefix="TeamOutlined"
:value-style="{ color: '#52c41a' }"
>
<template #suffix>
<a-tag color="green">配置</a-tag>
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :xs="24" :sm="12" :lg="6">
<a-card :loading="loading" hoverable>
<a-statistic
title="权限节点"
:value="stats.permissionCount"
:prefix="KeyOutlined"
:value-style="{ color: '#722ed1' }"
>
<template #suffix>
<a-tag color="purple">权限</a-tag>
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :xs="24" :sm="12" :lg="6">
<a-card :loading="loading" hoverable>
<a-statistic
title="在线用户"
:value="stats.onlineUserCount"
:prefix="ClockCircleOutlined"
:value-style="{ color: '#fa8c16' }"
>
<template #suffix>
<a-tag color="orange">在线</a-tag>
</template>
</a-statistic>
</a-card>
</a-col>
</a-row>
<!-- 图表区域 -->
<a-row :gutter="16" class="chart-row">
<a-col :xs="24" :lg="12">
<a-card title="用户分布" :loading="loading">
<div class="chart-container">
<div class="pie-chart">
<div class="chart-item" v-for="(item, index) in userDistribution" :key="index">
<div class="chart-bar" :style="{ width: item.percent + '%' }"></div>
<div class="chart-label">{{ item.label }}: {{ item.value }}</div>
</div>
</div>
</div>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card title="系统状态" :loading="loading">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="系统版本">{{ systemInfo.version }}</a-descriptions-item>
<a-descriptions-item label="PHP 版本">{{ systemInfo.phpVersion }}</a-descriptions-item>
<a-descriptions-item label="Laravel 版本">{{ systemInfo.laravelVersion }}</a-descriptions-item>
<a-descriptions-item label="服务器时间">{{ systemInfo.serverTime }}</a-descriptions-item>
<a-descriptions-item label="运行环境">{{ systemInfo.environment }}</a-descriptions-item>
</a-descriptions>
</a-card>
</a-col>
</a-row>
<!-- 快速操作和最近操作 -->
<a-row :gutter="16" class="action-row">
<a-col :xs="24" :lg="12">
<a-card title="快速操作">
<a-row :gutter="[8, 8]">
<a-col :xs="12" :sm="8">
<a-button type="primary" block @click="goToUser">
<UserOutlined />
用户管理
</a-button>
</a-col>
<a-col :xs="12" :sm="8">
<a-button type="primary" block @click="goToRole">
<TeamOutlined />
角色管理
</a-button>
</a-col>
<a-col :xs="12" :sm="8">
<a-button type="primary" block @click="goToPermission">
<KeyOutlined />
权限管理
</a-button>
</a-col>
<a-col :xs="12" :sm="8">
<a-button type="primary" block @click="goToDepartment">
<ApartmentOutlined />
部门管理
</a-button>
</a-col>
<a-col :xs="12" :sm="8">
<a-button type="primary" block @click="goToOnlineUsers">
<WifiOutlined />
在线用户
</a-button>
</a-col>
<a-col :xs="12" :sm="8">
<a-button type="primary" block @click="goToConfig">
<SettingOutlined />
系统配置
</a-button>
</a-col>
</a-row>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card title="最近日志" :loading="loading">
<a-list :data-source="recentLogs" size="small">
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
<template #title>
<a-tag :color="getLogColor(item.level)">{{ item.level }}</a-tag>
{{ item.message }}
</template>
<template #description>
{{ item.created_at }}
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</a-col>
</a-row>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, onMounted, computed, defineAsyncComponent } from 'vue' import { ref, onMounted } from 'vue'
import config from '@/config' import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import authApi from '@/api/auth'
import { message } from 'ant-design-vue'
// 定义组件名称 // 定义组件名称
defineOptions({ defineOptions({
name: 'HomePage', name: 'HomePage',
}) })
const loading = ref(true) const router = useRouter()
const dashboard = ref(config.DASHBOARD_LAYOUT || 'work') const userStore = useUserStore()
// 动态导入组件 const loading = ref(false)
const components = { const stats = ref({
work: defineAsyncComponent(() => import('./work/index.vue')), userCount: 0,
widgets: defineAsyncComponent(() => import('./widgets/index.vue')), roleCount: 0,
} permissionCount: 0,
onlineUserCount: 0
const dashboardComponent = computed(() => {
return components[dashboard.value] || components.work
}) })
const handleMounted = () => { const userDistribution = ref([
loading.value = false { label: '已激活', value: 0, percent: 0 },
{ label: '未激活', value: 0, percent: 0 },
{ label: '已禁用', value: 0, percent: 0 }
])
const systemInfo = ref({
version: '1.0.0',
phpVersion: '8.1.0',
laravelVersion: '10.0.0',
serverTime: '',
environment: 'production'
})
const recentLogs = ref([])
// 获取统计数据
const fetchStats = async () => {
try {
loading.value = true
// 获取用户列表统计
const userRes = await authApi.users.list.get({ page_size: 1 })
if (userRes.code === 200) {
stats.value.userCount = userRes.data.total || 0
}
// 获取角色列表统计
const roleRes = await authApi.roles.list.get({ page_size: 1 })
if (roleRes.code === 200) {
stats.value.roleCount = roleRes.data.total || 0
}
// 获取权限列表统计
const permRes = await authApi.permissions.list.get({ page_size: 1 })
if (permRes.code === 200) {
stats.value.permissionCount = permRes.data.total || 0
}
// 获取在线用户统计
const onlineRes = await authApi.onlineUsers.count.get()
if (onlineRes.code === 200) {
stats.value.onlineUserCount = onlineRes.data.count || 0
}
// 获取用户分布数据(这里使用模拟数据,实际项目中应从后端获取)
const activeCount = Math.floor(stats.value.userCount * 0.7)
const inactiveCount = Math.floor(stats.value.userCount * 0.2)
const disabledCount = stats.value.userCount - activeCount - inactiveCount
userDistribution.value = [
{ label: '已激活', value: activeCount, percent: stats.value.userCount > 0 ? Math.round((activeCount / stats.value.userCount) * 100) : 0 },
{ label: '未激活', value: inactiveCount, percent: stats.value.userCount > 0 ? Math.round((inactiveCount / stats.value.userCount) * 100) : 0 },
{ label: '已禁用', value: disabledCount, percent: stats.value.userCount > 0 ? Math.round((disabledCount / stats.value.userCount) * 100) : 0 }
]
// 更新系统信息
systemInfo.value.serverTime = new Date().toLocaleString('zh-CN')
systemInfo.value.environment = import.meta.env.VITE_APP_ENV || 'production'
// 模拟最近日志数据(实际项目中应从后端获取)
recentLogs.value = [
{ level: 'info', message: '用户登录成功', created_at: formatTime(new Date()) },
{ level: 'info', message: '系统配置更新', created_at: formatTime(new Date(Date.now() - 300000)) },
{ level: 'warning', message: '检测到异常访问', created_at: formatTime(new Date(Date.now() - 600000)) },
{ level: 'error', message: '数据库连接失败', created_at: formatTime(new Date(Date.now() - 900000)) },
{ level: 'info', message: '定时任务执行完成', created_at: formatTime(new Date(Date.now() - 1200000)) }
]
} catch (error) {
message.error('获取统计数据失败')
console.error(error)
} finally {
loading.value = false
}
} }
// 格式化时间
const formatTime = (date) => {
const now = new Date()
const diff = now - date
const minutes = Math.floor(diff / 60000)
if (minutes < 1) {
return '刚刚'
} else if (minutes < 60) {
return `${minutes}分钟前`
} else if (minutes < 1440) {
return `${Math.floor(minutes / 60)}小时前`
} else {
return `${Math.floor(minutes / 1440)}天前`
}
}
// 获取日志颜色
const getLogColor = (level) => {
const colors = {
info: 'blue',
warning: 'orange',
error: 'red',
success: 'green'
}
return colors[level] || 'default'
}
// 路由跳转方法
const goToUser = () => {
router.push('/system/users')
}
const goToRole = () => {
router.push('/system/roles')
}
const goToPermission = () => {
router.push('/system/permissions')
}
const goToDepartment = () => {
router.push('/system/departments')
}
const goToOnlineUsers = () => {
router.push('/system/online-users')
}
const goToConfig = () => {
router.push('/system/config')
}
// 生命周期
onMounted(() => { onMounted(() => {
// 模拟加载延迟 fetchStats()
setTimeout(() => {
loading.value = false // 每分钟更新一次服务器时间
}, 300) setInterval(() => {
systemInfo.value.serverTime = new Date().toLocaleString('zh-CN')
}, 60000)
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.home-page { .dashboard-container {
width: 100%; padding: 20px;
height: 100%; background: #f0f2f5;
min-height: calc(100vh - 64px);
.stats-cards {
margin-bottom: 16px;
:deep(.ant-card) {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
.ant-statistic-title {
font-size: 14px;
color: rgba(0, 0, 0, 0.65);
margin-bottom: 8px;
}
.ant-statistic-content {
font-size: 24px;
font-weight: 600;
}
.ant-statistic-content-prefix {
margin-right: 8px;
font-size: 20px;
}
}
}
.chart-row,
.action-row {
margin-bottom: 16px;
:deep(.ant-card) {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
height: 100%;
.ant-card-head {
border-bottom: 1px solid #f0f0f0;
}
}
}
.chart-container {
padding: 20px 0;
.pie-chart {
.chart-item {
margin-bottom: 16px;
position: relative;
&:last-child {
margin-bottom: 0;
}
.chart-bar {
height: 8px;
background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
border-radius: 4px;
margin-bottom: 8px;
transition: width 0.3s ease;
}
.chart-label {
display: flex;
justify-content: space-between;
font-size: 14px;
color: rgba(0, 0, 0, 0.65);
}
}
}
}
:deep(.ant-btn) {
height: 80px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
.anticon {
font-size: 24px;
}
}
:deep(.ant-list-item) {
padding: 12px 0;
}
:deep(.ant-descriptions-item-label) {
width: 100px;
font-weight: 500;
}
// 响应式调整
@media (max-width: 768px) {
padding: 10px;
.stats-cards {
margin-bottom: 10px;
}
.chart-row,
.action-row {
margin-bottom: 10px;
.ant-col {
margin-bottom: 10px;
}
}
:deep(.ant-btn) {
height: 60px;
.anticon {
font-size: 20px;
}
}
}
} }
</style> </style>
@@ -1,27 +0,0 @@
<template>
<a-card :bordered="true" title="关于项目" class="about-card">
<p>高性能 / 精致 / 优雅基于Vue3 + Ant Design Vue 的中后台前端解决方案如果喜欢就点个星星支持一下</p>
<p>
<a href="https://gitee.com/lolicode/scui" target="_blank">
<img src="https://gitee.com/lolicode/scui/badge/star.svg?theme=dark" alt="star" style="vertical-align: middle;">
</a>
</p>
</a-card>
</template>
<script setup>
// 定义组件名称
defineOptions({
name: 'AboutWidget',
})
</script>
<style scoped lang="scss">
.about-card {
p {
color: #999;
margin-top: 10px;
line-height: 1.8;
}
}
</style>
@@ -1,132 +0,0 @@
<template>
<a-card :bordered="true" title="实时收入">
<a-spin :spinning="loading">
<div ref="chartRef" style="width: 100%; height: 300px;"></div>
</a-spin>
</a-card>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
// 定义组件名称
defineOptions({
name: 'EchartsWidget',
})
const chartRef = ref(null)
const loading = ref(true)
let chart = null
let timer = null
// 初始化图表
const initChart = () => {
if (!chartRef.value) return
chart = echarts.init(chartRef.value)
// 生成初始数据
const now = new Date()
const xData = []
const yData = []
for (let i = 29; i >= 0; i--) {
const time = new Date(now.getTime() - i * 2000)
xData.unshift(time.toLocaleTimeString().replace(/^\D*/, ''))
yData.push(Math.round(Math.random() * 0))
}
const option = {
tooltip: {
trigger: 'axis',
},
xAxis: {
boundaryGap: false,
type: 'category',
data: xData,
},
yAxis: [
{
type: 'value',
name: '价格',
splitLine: {
show: false,
},
},
],
series: [
{
name: '收入',
type: 'line',
symbol: 'none',
lineStyle: {
width: 1,
color: '#409EFF',
},
areaStyle: {
opacity: 0.1,
color: '#79bbff',
},
data: yData,
},
],
}
chart.setOption(option)
// 模拟实时更新
timer = setInterval(() => {
const newTime = new Date().toLocaleTimeString().replace(/^\D*/, '')
const newValue = Math.round(Math.random() * 100)
xData.shift()
xData.push(newTime)
yData.shift()
yData.push(newValue)
chart.setOption({
xAxis: {
data: xData,
},
series: [
{
data: yData,
},
],
})
}, 2100)
}
onMounted(() => {
// 模拟加载延迟
setTimeout(() => {
loading.value = false
initChart()
}, 500)
// 监听窗口大小变化
window.addEventListener('resize', handleResize)
})
const handleResize = () => {
if (chart) {
chart.resize()
}
}
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
if (chart) {
chart.dispose()
}
window.removeEventListener('resize', handleResize)
})
</script>
<style scoped lang="scss">
// 样式根据需要添加
</style>
@@ -1,8 +0,0 @@
import { markRaw } from 'vue'
const resultComps = {}
const files = import.meta.glob('./*.vue', { eager: true })
Object.keys(files).forEach((fileName) => {
let comp = files[fileName]
resultComps[fileName.replace(/^\.\/(.*)\.\w+$/, '$1')] = comp.default
})
export default markRaw(resultComps)
@@ -1,63 +0,0 @@
<template>
<div class="info-card">
<div class="header">
<span class="title">系统信息</span>
</div>
<a-spin :spinning="loading">
<a-descriptions bordered :column="1">
<a-descriptions-item v-for="(item, index) in sysInfo" :key="index" :label="item.label">
{{ item.values }}
</a-descriptions-item>
</a-descriptions>
</a-spin>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import systemApi from '@/api/system'
// 定义组件名称
defineOptions({
name: 'InfoWidget',
})
const loading = ref(true)
const sysInfo = ref([])
const getSystemList = async () => {
try {
const res = await systemApi.info.get()
if (res.code === 1) {
sysInfo.value = res.data
}
} catch (error) {
console.error('获取系统信息失败:', error)
} finally {
loading.value = false
}
}
onMounted(() => {
getSystemList()
})
</script>
<style scoped lang="scss">
.info-card {
background-color: #ffffff;
padding: 16px;
border-radius: 10px;
margin: 16px 0;
.header{
padding-bottom: 10px;
.title{
font-size: 18px;
}
}
:deep(.ant-descriptions-item-label) {
width: 140px;
font-weight: 500;
}
}
</style>
@@ -1,36 +0,0 @@
<template>
<a-card :bordered="true" title="进度环">
<div class="progress">
<a-progress type="dashboard" :percent="85.5" :width="160">
<template #format="percent">
<div class="percentage-value">{{ percent }}%</div>
<div class="percentage-label">当前进度</div>
</template>
</a-progress>
</div>
</a-card>
</template>
<script setup>
// 定义组件名称
defineOptions({
name: 'ProgressWidget',
})
</script>
<style scoped lang="scss">
.progress {
text-align: center;
.percentage-value {
font-size: 28px;
font-weight: 500;
}
.percentage-label {
font-size: 12px;
margin-top: 10px;
color: #999;
}
}
</style>
@@ -1,93 +0,0 @@
<template>
<a-row :gutter="10">
<a-col :span="4">
<a-card :bordered="true" title="今日数量">
<a-statistic :value="count.today" :formatter="formatNumber" />
</a-card>
</a-col>
<a-col :span="4">
<a-card :bordered="true" title="昨日数量">
<a-statistic :value="count.yesterday" :formatter="formatNumber" />
</a-card>
</a-col>
<a-col :span="4">
<a-card :bordered="true" title="本周数量">
<a-statistic :value="count.week" :formatter="formatNumber" />
</a-card>
</a-col>
<a-col :span="4">
<a-card :bordered="true" title="上周数量">
<a-statistic :value="count.last_week" :formatter="formatNumber" />
</a-card>
</a-col>
<a-col :span="4">
<a-card :bordered="true" title="今年数量">
<a-statistic :value="count.year" :formatter="formatNumber" />
</a-card>
</a-col>
<a-col :span="4">
<a-card :bordered="true" title="总数量">
<a-statistic :value="count.all" :formatter="formatNumber" />
</a-card>
</a-col>
</a-row>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import systemApi from '@/api/system'
// 定义组件名称
defineOptions({
name: 'SmsWidget',
})
const count = ref({})
const getSmsCount = async () => {
try {
// 注意:API中可能没有短信统计接口,这里使用模拟数据
// 如果有接口,请取消注释以下代码
// const res = await systemApi.sms.count.get()
// if (res.code === 1) {
// count.value = res.data
// }
// 模拟数据
count.value = {
today: 1234,
yesterday: 5678,
week: 45678,
last_week: 43210,
year: 567890,
all: 1234567
}
} catch (error) {
console.error('获取短信统计失败:', error)
}
}
const formatNumber = (value) => {
return value.toLocaleString()
}
onMounted(() => {
getSmsCount()
})
</script>
<style scoped lang="scss">
:deep(.ant-card-head-title) {
padding: 12px 0;
font-size: 14px;
}
:deep(.ant-card-body) {
padding: 20px;
}
:deep(.ant-statistic-content) {
font-size: 24px;
font-weight: 500;
}
</style>
@@ -1,72 +0,0 @@
<template>
<a-card :bordered="true" title="时钟" class="time-card">
<div class="time">
<h2>{{ time }}</h2>
<p>{{ day }}</p>
</div>
</a-card>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import tool from '@/utils/tool'
// 定义组件名称
defineOptions({
name: 'TimeWidget',
})
const time = ref('')
const day = ref('')
let timer = null
const showTime = () => {
time.value = tool.dateFormat(new Date(), 'hh:mm:ss')
day.value = tool.dateFormat(new Date(), 'yyyy年MM月dd日')
}
onMounted(() => {
showTime()
timer = setInterval(() => {
showTime()
}, 1000)
})
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
</script>
<style scoped lang="scss">
.time-card {
background: linear-gradient(to right, #8e54e9, #4776e6);
color: #fff;
:deep(.ant-card-head-title) {
color: #fff;
}
:deep(.ant-card-head) {
border-color: rgba(255, 255, 255, 0.2);
}
:deep(.ant-card-body) {
background: transparent;
}
}
.time {
h2 {
font-size: 40px;
margin: 0;
}
p {
font-size: 14px;
margin-top: 13px;
opacity: 0.7;
}
}
</style>
@@ -1,69 +0,0 @@
<template>
<div class="ver-card">
<div class="header">
<span class="title">版本信息</span>
</div>
<a-spin :spinning="loading">
<a-descriptions bordered :column="1">
<a-descriptions-item v-for="(item, index) in sysInfo" :key="index" :label="item.label">
{{ item.values }}
</a-descriptions-item>
</a-descriptions>
</a-spin>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import systemApi from '@/api/system'
// 定义组件名称
defineOptions({
name: 'VerWidget',
})
const loading = ref(true)
const sysInfo = ref([])
const getSystemList = async () => {
try {
const res = await systemApi.version.get()
if (res.code === 1) {
sysInfo.value = res.data
}
} catch (error) {
console.error('获取版本信息失败:', error)
// 使用模拟数据作为fallback
sysInfo.value = [
{ label: '系统版本', values: '1.0.0' },
{ label: '框架版本', values: 'Vue 3.x' },
{ label: '构建时间', values: '2024-01-01' },
]
} finally {
loading.value = false
}
}
onMounted(() => {
getSystemList()
})
</script>
<style scoped lang="scss">
.ver-card {
background-color: #ffffff;
padding: 16px;
border-radius: 10px;
margin: 16px 0;
.header{
padding-bottom: 10px;
.title{
font-size: 18px;
}
}
:deep(.ant-descriptions-item-label) {
width: 160px;
font-weight: 500;
}
}
</style>
@@ -1,97 +0,0 @@
<template>
<a-card :bordered="true" title="欢迎">
<div class="welcome">
<div class="logo">
<img :src="logoImage" alt="logo">
<h2>VueAdmin</h2>
</div>
<div class="tips">
<div class="tips-item">
<div class="tips-item-icon"><MenuOutlined /></div>
<div class="tips-item-message">这里是项目控制台你可以点击右上方的"自定义"按钮来添加移除或者移动部件</div>
</div>
<div class="tips-item">
<div class="tips-item-icon"><RocketOutlined /></div>
<div class="tips-item-message">在提高前端算力减少带宽请求和代码执行力上多次优化并且持续着</div>
</div>
<div class="tips-item">
<div class="tips-item-icon"><CoffeeOutlined /></div>
<div class="tips-item-message">项目目的让前端工作更快乐</div>
</div>
</div>
</div>
</a-card>
</template>
<script setup>
import { MenuOutlined, RocketOutlined, CoffeeOutlined } from '@ant-design/icons-vue'
import logoImage from '@/assets/images/logo.png'
// 定义组件名称
defineOptions({
name: 'WelcomeWidget',
})
</script>
<style scoped lang="scss">
.welcome {
display: flex;
flex-direction: row;
align-items: center;
}
.welcome .logo {
text-align: center;
padding: 0 40px;
display: flex;
flex-direction: column;
align-items: center;
img {
width: 100px;
height: 100px;
margin-bottom: 20px;
}
h2 {
font-size: 30px;
font-weight: normal;
display: flex;
align-items: center;
justify-content: center;
margin: 0;
}
}
.tips {
padding: 0 40px;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.tips-item {
display: flex;
align-items: center;
justify-content: center;
padding: 7.5px 0;
}
.tips-item-icon {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
font-size: 18px;
margin-right: 20px;
color: #1890ff;
background: rgba(24, 144, 255, 0.1);
}
.tips-item-message {
flex: 1;
font-size: 14px;
}
</style>
@@ -1,505 +0,0 @@
<template>
<div :class="['widgets-home', customizing ? 'customizing' : '']" ref="main">
<div class="widgets-content">
<div class="widgets-top">
<div class="widgets-top-title">控制台</div>
<div class="widgets-top-actions">
<a-button v-if="customizing" type="primary" shape="round" @click="handleSave">
<template #icon>
<CheckOutlined />
</template>
完成
</a-button>
<a-button v-else type="primary" shape="round" @click="handleCustom">
<template #icon>
<EditOutlined />
</template>
自定义
</a-button>
</div>
</div>
<div class="widgets" ref="widgetsRef">
<div class="widgets-wrapper">
<div v-if="nowCompsList.length <= 0" class="no-widgets">
<a-empty description="没有部件啦" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
</div>
<a-row :gutter="15">
<a-col v-for="(item, index) in grid.layout" :key="index" :md="item" :xs="24">
<div class="draggable-wrapper">
<draggable v-model="grid.compsList[index]" item-key="key" :animation="200"
handle=".customize-overlay" group="widgets" class="draggable-box">
<template #item="{ element }">
<div class="widgets-item">
<component :is="allComps[element]" />
<div v-if="customizing" class="customize-overlay">
<a-button class="close" type="primary" ghost shape="circle"
@click="removeComp(element)">
<template #icon>
<CloseOutlined />
</template>
</a-button>
<label>
<component :is="allComps[element].icon" />
{{ allComps[element].title }}
</label>
</div>
</div>
</template>
</draggable>
</div>
</a-col>
</a-row>
</div>
</div>
</div>
<!-- 自定义侧边栏 -->
<a-drawer v-if="customizing" :open="customizing" :width="360" placement="right" :closable="false" :mask="false"
class="widgets-drawer">
<template #title>
<div class="widgets-aside-title">
<PlusCircleOutlined /> 添加部件
</div>
</template>
<template #extra>
<a-button type="text" @click="handleClose">
<template #icon>
<CloseOutlined />
</template>
</a-button>
</template>
<!-- 布局选择 -->
<div class="select-layout">
<h3>选择布局</h3>
<div class="select-layout-options">
<div class="select-layout-item item01" :class="{ active: grid.layout.join(',') === '12,6,6' }"
@click="setLayout([12, 6, 6])">
<a-row :gutter="2">
<a-col :span="12"><span></span></a-col>
<a-col :span="6"><span></span></a-col>
<a-col :span="6"><span></span></a-col>
</a-row>
</div>
<div class="select-layout-item item02" :class="{ active: grid.layout.join(',') === '24,16,8' }"
@click="setLayout([24, 16, 8])">
<a-row :gutter="2">
<a-col :span="24"><span></span></a-col>
<a-col :span="16"><span></span></a-col>
<a-col :span="8"><span></span></a-col>
</a-row>
</div>
<div class="select-layout-item item03" :class="{ active: grid.layout.join(',') === '24' }"
@click="setLayout([24])">
<a-row :gutter="2">
<a-col :span="24"><span></span></a-col>
<a-col :span="24"><span></span></a-col>
<a-col :span="24"><span></span></a-col>
</a-row>
</div>
</div>
</div>
<!-- 部件列表 -->
<div class="widgets-list">
<h3>可用部件</h3>
<div v-if="myCompsList.length <= 0" class="widgets-list-nodata">
<a-empty description="没有部件啦" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
</div>
<div v-for="item in myCompsList" :key="item.key" class="widgets-list-item">
<div class="item-logo">
<component :is="item.icon" />
</div>
<div class="item-info">
<h2>{{ item.title }}</h2>
<p>{{ item.description }}</p>
</div>
<div class="item-actions">
<a-button type="primary" @click="addComp(item)">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</div>
</div>
</div>
<template #footer>
<a-button @click="handleResetDefault">恢复默认</a-button>
</template>
</a-drawer>
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { Empty } from 'ant-design-vue'
import draggable from 'vuedraggable'
import allComps from './components'
import config from '@/config'
// 定义组件名称
defineOptions({
name: 'WidgetsPage',
})
const customizing = ref(false)
const widgetsRef = ref(null)
const defaultGrid = config.DEFAULT_GRID
const grid = reactive({ layout: [], compsList: [] })
// 初始化
const initGrid = () => {
const savedGrid = localStorage.getItem('widgetsGrid')
if (savedGrid) {
try {
const parsed = JSON.parse(savedGrid)
grid.layout = parsed.layout
grid.compsList = parsed.compsList
} catch {
resetToDefault()
}
} else {
resetToDefault()
}
}
const resetToDefault = () => {
grid.layout = [...defaultGrid.layout]
grid.compsList = defaultGrid.compsList.map((arr) => [...arr])
}
// 计算属性
const allCompsList = computed(() => {
const list = []
for (const key in allComps) {
list.push({
key,
title: allComps[key].title,
icon: allComps[key].icon,
description: allComps[key].description,
})
}
const myCompKeys = grid.compsList.flat()
list.forEach((comp) => {
comp.disabled = myCompKeys.includes(comp.key)
})
return list
})
const myCompsList = computed(() => {
return allCompsList.value.filter((item) => !item.disabled)
})
const nowCompsList = computed(() => {
return grid.compsList.flat()
})
// 方法
const handleCustom = () => {
customizing.value = true
const oldWidth = widgetsRef.value?.offsetWidth || 0
nextTick(() => {
if (widgetsRef.value) {
const scale = widgetsRef.value.offsetWidth / oldWidth
widgetsRef.value.style.setProperty('transform', `scale(${scale})`)
}
})
}
const setLayout = (layout) => {
grid.layout = layout
if (layout.join(',') === '24') {
grid.compsList[0] = [...grid.compsList[0], ...grid.compsList[1], ...grid.compsList[2]]
grid.compsList[1] = []
grid.compsList[2] = []
}
}
const addComp = (item) => {
grid.compsList[0].push(item.key)
}
const removeComp = (key) => grid.compsList.forEach((list, index) => {
grid.compsList[index] = list.filter((k) => k !== key)
})
const handleSave = () => {
customizing.value = false
if (widgetsRef.value) {
widgetsRef.value.style.removeProperty('transform')
}
localStorage.setItem('widgetsGrid', JSON.stringify(grid))
emit('on-mounted')
}
const handleResetDefault = () => {
customizing.value = false
if (widgetsRef.value) {
widgetsRef.value.style.removeProperty('transform')
}
resetToDefault()
localStorage.removeItem('widgetsGrid')
}
const handleClose = () => {
customizing.value = false
if (widgetsRef.value) {
widgetsRef.value.style.removeProperty('transform')
}
}
// 生命周期
onMounted(() => {
initGrid()
emit('on-mounted')
})
const emit = defineEmits(['on-mounted'])
</script>
<style scoped lang="scss">
.widgets-home {
display: flex;
flex-direction: row;
flex: 1;
height: 100%;
}
.widgets-content {
flex: 1;
overflow: auto;
overflow-x: hidden;
padding: 15px;
}
.widgets-top {
margin-bottom: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
.widgets-top-title {
font-size: 18px;
font-weight: bold;
}
.widgets {
transform-origin: top left;
transition: transform 0.15s;
}
.customizing .widgets-wrapper {
margin-right: -360px;
}
.customizing .widgets-wrapper .ant-col {
padding-bottom: 15px;
}
.customizing .widgets-wrapper .draggable-wrapper {
border: 1px dashed #1890ff;
padding: 15px;
}
.customizing .widgets-wrapper .no-widgets {
display: none;
}
.customizing .widgets-item {
position: relative;
margin-bottom: 15px;
}
.customize-overlay {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.9);
cursor: grab;
}
.customize-overlay:active {
cursor: grabbing;
}
.customize-overlay label {
background: #1890ff;
color: #fff;
height: 40px;
padding: 0 30px;
border-radius: 40px;
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
cursor: grab;
margin-top: 8px;
.anticon {
margin-right: 15px;
font-size: 24px;
}
}
.customize-overlay .close {
position: absolute;
top: 15px;
right: 15px;
}
.widgets-list {
margin-top: 24px;
h3 {
font-size: 14px;
margin-bottom: 12px;
}
}
.widgets-list-item {
display: flex;
flex-direction: row;
padding: 15px;
align-items: center;
background: #fafafa;
border-radius: 8px;
margin-bottom: 8px;
transition: background 0.3s;
&:hover {
background: #f0f0f0;
}
}
.widgets-list-item .item-logo {
width: 40px;
height: 40px;
border-radius: 50%;
background: rgba(180, 180, 180, 0.1);
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
margin-right: 15px;
color: #6a8bad;
}
.widgets-list-item .item-info {
flex: 1;
}
.widgets-list-item .item-info h2 {
font-size: 16px;
font-weight: normal;
cursor: default;
margin: 0 0 4px 0;
}
.widgets-list-item .item-info p {
font-size: 12px;
color: #999;
cursor: default;
margin: 0;
}
.widgets-wrapper .sortable-ghost {
opacity: 0.5;
}
.select-layout {
margin-bottom: 24px;
h3 {
font-size: 14px;
margin-bottom: 12px;
}
}
.select-layout-options {
display: flex;
gap: 12px;
}
.select-layout-item {
width: 60px;
height: 60px;
border: 2px solid #d9d9d9;
padding: 5px;
cursor: pointer;
border-radius: 4px;
transition: all 0.3s;
span {
display: block;
background: #d9d9d9;
height: 46px;
border-radius: 2px;
}
&.item02 span {
height: 30px;
}
&.item02 .ant-col:nth-child(1) span {
height: 14px;
margin-bottom: 2px;
}
&.item03 span {
height: 14px;
margin-bottom: 2px;
}
&:hover {
border-color: #1890ff;
}
&.active {
border-color: #1890ff;
span {
background: #1890ff;
}
}
}
.widgets-drawer {
:deep(.ant-drawer-body) {
padding: 0;
}
.widgets-aside-title {
display: flex;
align-items: center;
gap: 8px;
.anticon {
font-size: 18px;
}
}
}
@media (max-width: 992px) {
.customizing .widgets {
transform: scale(1) !important;
}
.customizing .widgets-drawer {
width: 100% !important;
}
.customizing .widgets-wrapper {
margin-right: 0;
}
}
</style>
@@ -1,469 +0,0 @@
<template>
<div class="my-app">
<a-card :bordered="false">
<template #title>
<div class="card-title">
<SettingOutlined />
<span>我的常用应用</span>
</div>
</template>
<template #extra>
<a-button type="primary" @click="showDrawer">
<template #icon>
<PlusOutlined />
</template>
添加应用
</a-button>
</template>
<div v-if="myApps.length === 0" class="empty-state">
<a-empty description="暂无常用应用,请点击上方按钮添加" />
</div>
<div v-else class="apps-grid">
<draggable v-model="myApps" item-key="path" :animation="200" ghost-class="ghost" drag-class="dragging"
class="draggable-grid">
<template #item="{ element }">
<div class="app-item" @click="handleAppClick(element)">
<div class="app-icon">
<component :is="getIconComponent(element.meta?.icon)" />
</div>
<div class="app-name">{{ element.meta?.title }}</div>
<div class="app-description">{{ element.meta?.description || '点击打开' }}</div>
</div>
</template>
</draggable>
</div>
</a-card>
<!-- 添加应用抽屉 -->
<a-drawer v-model:open="drawerVisible" title="管理应用" :width="650" placement="right">
<div class="drawer-content">
<div class="app-section">
<div class="section-header">
<h3>
<StarFilled />
我的常用
</h3>
<span class="count">{{ myApps.length }} 个应用</span>
</div>
<p class="tips">拖拽卡片调整顺序点击移除按钮移除应用</p>
<draggable v-model="myApps" item-key="path" :animation="200" ghost-class="drawer-ghost"
drag-class="drawer-dragging" class="drawer-grid" group="apps">
<template #item="{ element }">
<div class="drawer-app-card">
<div class="remove-btn" @click.stop="removeApp(element.path)">
<CloseOutlined />
</div>
<div class="app-icon">
<component :is="getIconComponent(element.meta?.icon)" />
</div>
<div class="app-name">{{ element.meta?.title }}</div>
</div>
</template>
<template #footer>
<div v-if="myApps.length === 0" class="empty-zone">
<a-empty description="暂无常用应用,从下方拖入应用" :image="false" />
</div>
</template>
</draggable>
</div>
<a-divider style="margin: 24px 0" />
<div class="app-section">
<div class="section-header">
<h3>
<AppstoreOutlined />
全部应用
</h3>
<span class="count">{{ allApps.length }} 个可用</span>
</div>
<p class="tips">拖拽卡片到上方添加为常用应用</p>
<draggable v-model="allApps" item-key="path" :animation="200" ghost-class="drawer-ghost"
drag-class="drawer-dragging" class="drawer-grid" group="apps">
<template #item="{ element }">
<div class="drawer-app-card">
<div class="app-icon">
<component :is="getIconComponent(element.meta?.icon)" />
</div>
<div class="app-name">{{ element.meta?.title }}</div>
</div>
</template>
<template #footer>
<div v-if="allApps.length === 0" class="empty-zone">
<a-empty description="所有应用已添加" :image="false" />
</div>
</template>
</draggable>
</div>
</div>
<template #footer>
<a-button @click="drawerVisible = false">取消</a-button>
<a-button type="primary" @click="handleSave">保存设置</a-button>
</template>
</a-drawer>
</div>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import draggable from 'vuedraggable'
import { useUserStore } from '@/stores/modules/user'
import * as icons from '@ant-design/icons-vue'
// 定义组件名称
defineOptions({
name: 'MyApp',
})
const router = useRouter()
const userStore = useUserStore()
// 从菜单中提取所有应用项(扁平化菜单树)
const extractMenuItems = (menus) => {
const items = []
const traverse = (menuList) => {
for (const menu of menuList) {
// 只添加有路径的菜单项(排除父级菜单项)
if (menu.path && (!menu.children || menu.children.length === 0)) {
items.push(menu)
}
// 递归处理子菜单
if (menu.children && menu.children.length > 0) {
traverse(menu.children)
}
}
}
traverse(menus)
return items
}
// 获取所有可用应用
const allAvailableApps = computed(() => {
return extractMenuItems(userStore.menu || [])
})
const drawerVisible = ref(false)
const myApps = ref([])
const allApps = ref([])
// 获取图标组件
const getIconComponent = (iconName) => {
return icons[iconName] || icons.FileTextOutlined
}
// 从本地存储加载数据
const loadApps = () => {
const savedApps = localStorage.getItem('myApps')
if (savedApps) {
const savedPaths = JSON.parse(savedApps)
myApps.value = allAvailableApps.value.filter(app => savedPaths.includes(app.path))
} else {
// 默认显示前4个应用
myApps.value = allAvailableApps.value.slice(0, 4)
}
updateAllApps()
}
// 更新全部应用列表(排除已添加的)
const updateAllApps = () => {
const myAppPaths = myApps.value.map(app => app.path)
allApps.value = allAvailableApps.value.filter(app => !myAppPaths.includes(app.path))
}
// 显示抽屉
const showDrawer = () => {
drawerVisible.value = true
updateAllApps()
}
// 移除应用
const removeApp = (path) => {
const index = myApps.value.findIndex(app => app.path === path)
if (index > -1) {
myApps.value.splice(index, 1)
updateAllApps()
}
}
// 应用点击处理
const handleAppClick = (app) => {
if (app.path) {
router.push(app.path)
} else {
message.warning('该应用没有配置路由')
}
}
// 保存设置
const handleSave = () => {
const appPaths = myApps.value.map(app => app.path)
localStorage.setItem('myApps', JSON.stringify(appPaths))
message.success('保存成功')
drawerVisible.value = false
}
// 初始化
loadApps()
// 监听菜单变化,重新加载应用
watch(
() => userStore.menu,
() => {
loadApps()
},
{ deep: true }
)
</script>
<style scoped lang="scss">
.my-app {
padding: 20px;
.card-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 16px;
font-weight: 500;
}
.empty-state {
padding: 40px 0;
}
.apps-grid {
.draggable-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.app-item {
padding: 24px;
text-align: center;
background: #fafafa;
border-radius: 8px;
cursor: grab;
transition: all 0.3s;
border: 1px solid #f0f0f0;
&:active {
cursor: grabbing;
}
&:hover {
background: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transform: translateY(-2px);
border-color: #1890ff;
}
&.dragging {
opacity: 0.5;
}
&.ghost {
opacity: 0.3;
background: #e6f7ff;
border-color: #1890ff;
border-style: dashed;
}
.app-icon {
font-size: 40px;
color: #1890ff;
margin-bottom: 12px;
display: flex;
align-items: center;
justify-content: center;
}
.app-name {
font-size: 16px;
font-weight: 500;
margin-bottom: 4px;
}
.app-description {
font-size: 12px;
color: #999;
}
}
}
}
// 抽屉样式 - 使用全局样式避免深度问题
:deep(.my-app .ant-drawer-body) {
padding: 16px;
}
:deep(.my-app .ant-drawer-footer) {
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}
.drawer-content {
.app-section {
margin-bottom: 0;
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
h3 {
display: flex;
align-items: center;
gap: 6px;
font-size: 16px;
font-weight: 600;
margin: 0;
color: #262626;
.anticon {
font-size: 18px;
}
}
.count {
font-size: 12px;
color: #999;
background: #f5f5f5;
padding: 2px 8px;
border-radius: 4px;
}
}
.tips {
font-size: 13px;
color: #8c8c8c;
margin-bottom: 12px;
line-height: 1.5;
}
.empty-zone {
text-align: center;
padding: 30px 20px;
background: #fafafa;
border: 2px dashed #d9d9d9;
border-radius: 8px;
.ant-empty-description {
color: #bfbfbf;
margin: 0;
}
}
// 抽屉内卡片式网格布局
.drawer-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 12px;
min-height: 80px;
}
.drawer-app-card {
position: relative;
padding: 20px 16px;
text-align: center;
background: #fff;
border: 1px solid #f0f0f0;
border-radius: 8px;
cursor: grab;
transition: all 0.25s ease;
&:active {
cursor: grabbing;
}
&:hover {
border-color: #1890ff;
box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
transform: translateY(-2px);
}
.remove-btn {
position: absolute;
top: 8px;
right: 8px;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
background: #ff4d4f;
color: #fff;
border-radius: 50%;
font-size: 12px;
cursor: pointer;
opacity: 0;
transition: opacity 0.25s;
&:hover {
background: #ff7875;
}
}
&:hover .remove-btn {
opacity: 1;
}
.app-icon {
width: 48px;
height: 48px;
margin: 0 auto 12px;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
border-radius: 12px;
font-size: 24px;
color: #1890ff;
:deep(.anticon) {
font-size: 24px;
}
}
.app-name {
font-size: 14px;
font-weight: 500;
color: #262626;
margin-bottom: 4px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.app-description {
font-size: 12px;
color: #8c8c8c;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
// 拖拽时的样式
.drawer-ghost {
opacity: 0.4;
background: #e6f7ff;
border-color: #1890ff;
border-style: dashed;
}
.drawer-dragging {
opacity: 0.6;
transform: scale(0.95);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
}
}
</style>
@@ -1,21 +0,0 @@
<template>
<div class="work-page">
<MyApp />
</div>
</template>
<script setup>
import MyApp from './components/myapp.vue'
// 定义组件名称
defineOptions({
name: 'WorkPage',
})
</script>
<style scoped lang="scss">
.work-page {
width: 100%;
height: 100%;
}
</style>
@@ -1,489 +0,0 @@
<template>
<div class="config-management">
<!-- 搜索表单 -->
<a-card class="search-card" :bordered="false">
<a-form :model="searchParams" layout="inline">
<a-form-item label="关键词">
<a-input v-model:value="searchParams.keyword" placeholder="配置名称/键" allow-clear style="width: 200px" />
</a-form-item>
<a-form-item label="分组">
<a-select v-model:value="searchParams.group" allow-clear placeholder="请选择分组" style="width: 150px">
<a-select-option v-for="group in groups" :key="group" :value="group">
{{ group }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="状态">
<a-select v-model:value="searchParams.status" allow-clear placeholder="请选择状态" style="width: 120px">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">禁用</a-select-option>
</a-select>
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleSearch">
<template #icon><SearchOutlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<!-- 操作按钮 -->
<a-card class="table-card" :bordered="false">
<template #title>
<a-space>
<a-button type="primary" @click="handleAdd">
<template #icon><PlusOutlined /></template>
新增
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchDelete" danger>
<template #icon><DeleteOutlined /></template>
批量删除
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus">
<template #icon><CheckOutlined /></template>
批量启用
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus(false)" danger>
<template #icon><CloseOutlined /></template>
批量禁用
</a-button>
</a-space>
</template>
<!-- 数据表格 -->
<sc-table
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'type'">
<a-tag :color="getTypeColor(record.type)">
{{ getTypeLabel(record.type) }}
</a-tag>
</template>
<template v-if="column.key === 'value'">
<span v-if="record.type === 'image' || record.type === 'file'" class="value-preview">
<a-image
v-if="record.type === 'image'"
:src="record.value"
:width="40"
:height="40"
style="object-fit: cover"
/>
<a-tag v-else color="blue">文件</a-tag>
</span>
<span v-else class="value-text">{{ formatValue(record.value, record.type) }}</span>
</template>
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定要删除该配置吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</sc-table>
</a-card>
<!-- 新增/编辑弹窗 -->
<a-modal
v-model:open="modalVisible"
:title="modalTitle"
:width="700"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }">
<a-form-item label="配置分组" name="group">
<a-select v-model:value="formData.group" placeholder="请选择配置分组">
<a-select-option v-for="group in groups" :key="group" :value="group">
{{ group }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="配置键" name="key">
<a-input v-model:value="formData.key" placeholder="请输入配置键,如:site_name" :disabled="!!formData.id" />
</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="description">
<a-textarea v-model:value="formData.description" placeholder="请输入配置描述" :rows="2" />
</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="number">数字</a-select-option>
<a-select-option value="boolean">布尔值</a-select-option>
<a-select-option value="array">数组</a-select-option>
<a-select-option value="image">图片</a-select-option>
<a-select-option value="file">文件</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="配置值" name="value">
<template v-if="formData.type === 'boolean'">
<a-radio-group v-model:value="formData.value">
<a-radio :value="true"></a-radio>
<a-radio :value="false"></a-radio>
</a-radio-group>
</template>
<template v-else-if="formData.type === 'number'">
<a-input-number v-model:value="formData.value" style="width: 100%" />
</template>
<template v-else-if="formData.type === 'array'">
<a-textarea
v-model:value="arrayValue"
placeholder="JSON数组格式,如:[1,2,3]"
:rows="3"
@blur="handleArrayBlur"
/>
</template>
<template v-else-if="formData.type === 'image'">
<sc-upload v-model="formData.value" :limit="1" accept="image/*" list-type="picture-card" />
</template>
<template v-else-if="formData.type === 'file'">
<sc-upload v-model="formData.value" :limit="1" list-type="text" />
</template>
<template v-else>
<a-textarea v-model:value="formData.value" placeholder="请输入配置值" :rows="3" />
</template>
</a-form-item>
<a-form-item v-if="formData.type === 'string'" label="可选值" name="options">
<a-textarea
v-model:value="optionsValue"
placeholder="每行一个选项,如:option1&#10;option2&#10;option3"
:rows="3"
@blur="handleOptionsBlur"
/>
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" :min="0" :max="9999" 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>
</a-modal>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
PlusOutlined,
DeleteOutlined,
CheckOutlined,
CloseOutlined,
} from '@ant-design/icons-vue'
import systemApi from '@/api/system'
import scTable from '@/components/scTable/index.vue'
import scUpload from '@/components/scUpload/index.vue'
defineOptions({
name: 'ConfigManagement',
})
const searchParams = ref({
keyword: '',
group: undefined,
status: undefined,
})
const loading = ref(false)
const dataSource = ref([])
const pagination = ref({
current: 1,
pageSize: 20,
total: 0,
})
const selectedRowKeys = ref([])
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys
},
}))
const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '配置分组', dataIndex: 'group', key: 'group', width: 120 },
{ title: '配置键', dataIndex: 'key', key: 'key', width: 200 },
{ title: '配置名称', dataIndex: 'name', key: 'name', width: 150 },
{ title: '数据类型', key: 'type', width: 100, align: 'center' },
{ title: '配置值', key: 'value', width: 200 },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'action', width: 150, fixed: 'right' },
]
const groups = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增配置')
const formData = ref({})
const formRef = ref(null)
const formRules = {
group: [{ required: true, message: '请选择配置分组', trigger: 'change' }],
key: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
type: [{ required: true, message: '请选择数据类型', trigger: 'change' }],
}
const arrayValue = ref('')
const optionsValue = ref('')
const fetchData = async () => {
loading.value = true
try {
const res = await systemApi.configs.list.get({
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
})
dataSource.value = res.data.list
pagination.value.total = res.data.total
} catch (error) {
message.error('获取配置列表失败')
} finally {
loading.value = false
}
}
const fetchGroups = async () => {
try {
const res = await systemApi.configs.groups.get()
groups.value = res.data
} catch (error) {
message.error('获取配置分组失败')
}
}
const handleSearch = () => {
pagination.value.current = 1
fetchData()
}
const handleReset = () => {
searchParams.value = {
keyword: '',
group: undefined,
status: undefined,
}
pagination.value.current = 1
fetchData()
}
const handlePageChange = (page) => {
pagination.value.current = page
fetchData()
}
const handleAdd = () => {
modalTitle.value = '新增配置'
formData.value = {
status: 1,
sort: 0,
type: 'string',
}
arrayValue.value = ''
optionsValue.value = ''
modalVisible.value = true
}
const handleEdit = (record) => {
modalTitle.value = '编辑配置'
formData.value = { ...record }
if (record.type === 'array') {
arrayValue.value = typeof record.value === 'string' ? record.value : JSON.stringify(record.value)
}
if (record.options) {
optionsValue.value = Array.isArray(record.options) ? record.options.join('\n') : record.options
}
modalVisible.value = true
}
const handleArrayBlur = () => {
try {
if (arrayValue.value) {
formData.value.value = JSON.parse(arrayValue.value)
}
} catch (error) {
message.error('数组格式错误,请输入正确的JSON格式')
}
}
const handleOptionsBlur = () => {
if (optionsValue.value) {
formData.value.options = optionsValue.value.split('\n').filter((item) => item.trim())
}
}
const handleSubmit = async () => {
try {
await formRef.value.validate()
const submitData = { ...formData.value }
if (submitData.type === 'array' && arrayValue.value) {
submitData.value = JSON.parse(arrayValue.value)
}
if (submitData.type === 'boolean') {
submitData.value = submitData.value === 'true' || submitData.value === true
}
if (optionsValue.value) {
submitData.options = optionsValue.value.split('\n').filter((item) => item.trim())
}
if (submitData.id) {
await systemApi.configs.edit.put(submitData.id, submitData)
message.success('更新成功')
} else {
await systemApi.configs.add.post(submitData)
message.success('创建成功')
}
modalVisible.value = false
fetchData()
} catch (error) {
if (error.errorFields) {
return
}
message.error(error.message || '操作失败')
}
}
const handleCancel = () => {
modalVisible.value = false
formData.value = {}
arrayValue.value = ''
optionsValue.value = ''
formRef.value?.resetFields()
}
const handleDelete = async (id) => {
try {
await systemApi.configs.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) {
message.error('删除失败')
}
}
const handleBatchDelete = async () => {
try {
await systemApi.configs.batchDelete.post({ ids: selectedRowKeys.value })
message.success('批量删除成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('批量删除失败')
}
}
const handleBatchStatus = async (status = 1) => {
try {
await systemApi.configs.batchStatus.post({ ids: selectedRowKeys.value, status })
message.success(status ? '批量启用成功' : '批量禁用成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('操作失败')
}
}
const getTypeColor = (type) => {
const colors = {
string: 'blue',
number: 'green',
boolean: 'orange',
array: 'purple',
image: 'cyan',
file: 'geekblue',
}
return colors[type] || 'default'
}
const getTypeLabel = (type) => {
const labels = {
string: '字符串',
number: '数字',
boolean: '布尔值',
array: '数组',
image: '图片',
file: '文件',
}
return labels[type] || type
}
const formatValue = (value, type) => {
if (type === 'array') {
try {
const arr = typeof value === 'string' ? JSON.parse(value) : value
return Array.isArray(arr) ? arr.join(', ') : value
} catch {
return value
}
}
if (type === 'boolean') {
return value === 'true' || value === true ? '是' : '否'
}
if (typeof value === 'string' && value.length > 50) {
return value.substring(0, 50) + '...'
}
return value
}
onMounted(() => {
fetchData()
fetchGroups()
})
</script>
<style scoped lang="scss">
.config-management {
padding: 16px;
.search-card {
margin-bottom: 16px;
}
.table-card {
:deep(.ant-card-body) {
padding: 16px;
}
}
.value-preview {
display: flex;
align-items: center;
gap: 8px;
}
.value-text {
color: #666;
font-size: 13px;
}
}
</style>
@@ -1,463 +0,0 @@
<template>
<div class="dictionary-management">
<!-- 搜索表单 -->
<a-card class="search-card" :bordered="false">
<a-form :model="searchParams" layout="inline">
<a-form-item label="关键词">
<a-input v-model:value="searchParams.keyword" placeholder="字典名称/编码" allow-clear style="width: 200px" />
</a-form-item>
<a-form-item label="状态">
<a-select v-model:value="searchParams.status" allow-clear placeholder="请选择状态" style="width: 120px">
<a-select-option :value="1">启用</a-select-option>
<a-select-option :value="0">禁用</a-select-option>
</a-select>
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleSearch">
<template #icon><SearchOutlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<!-- 操作按钮 -->
<a-card class="table-card" :bordered="false">
<template #title>
<a-space>
<a-button type="primary" @click="handleAdd">
<template #icon><PlusOutlined /></template>
新增
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchDelete" danger>
<template #icon><DeleteOutlined /></template>
批量删除
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus">
<template #icon><CheckOutlined /></template>
批量启用
</a-button>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchStatus(false)" danger>
<template #icon><CloseOutlined /></template>
批量禁用
</a-button>
</a-space>
</template>
<!-- 数据表格 -->
<sc-table
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'item_count'">
<a-tag color="blue">{{ record.item_count || 0 }} </a-tag>
</template>
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleItems(record)">字典项</a-button>
<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
<a-popconfirm title="确定要删除该字典吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</sc-table>
</a-card>
<!-- 新增/编辑弹窗 -->
<a-modal
v-model:open="modalVisible"
:title="modalTitle"
:width="600"
@ok="handleSubmit"
@cancel="handleCancel"
>
<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }">
<a-form-item label="字典名称" name="name">
<a-input v-model:value="formData.name" placeholder="请输入字典名称" />
</a-form-item>
<a-form-item label="字典编码" name="code">
<a-input v-model:value="formData.code" placeholder="请输入字典编码,如:user_status" :disabled="!!formData.id" />
</a-form-item>
<a-form-item label="描述" name="description">
<a-textarea v-model:value="formData.description" placeholder="请输入描述" :rows="3" />
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="formData.sort" :min="0" :max="9999" 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>
</a-modal>
<!-- 字典项弹窗 -->
<a-modal
v-model:open="itemModalVisible"
:title="`字典项 - ${currentDictionary?.name}`"
:width="900"
:footer="null"
>
<div class="dictionary-items">
<a-space style="margin-bottom: 16px">
<a-button type="primary" @click="handleAddItem">
<template #icon><PlusOutlined /></template>
新增字典项
</a-button>
</a-space>
<a-table
:columns="itemColumns"
:data-source="itemDataSource"
:loading="itemLoading"
:pagination="false"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'success' : 'error'">
{{ record.status === 1 ? '启用' : '禁用' }}
</a-tag>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleEditItem(record)">编辑</a-button>
<a-popconfirm title="确定要删除该字典项吗?" @confirm="handleDeleteItem(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</div>
</a-modal>
<!-- 字典项编辑弹窗 -->
<a-modal
v-model:open="itemEditVisible"
:title="itemEditTitle"
:width="500"
@ok="handleItemSubmit"
@cancel="itemEditVisible = false"
>
<a-form ref="itemFormRef" :model="itemFormData" :rules="itemFormRules" :label-col="{ span: 6 }">
<a-form-item label="显示标签" name="label">
<a-input v-model:value="itemFormData.label" placeholder="请输入显示标签" />
</a-form-item>
<a-form-item label="实际值" name="value">
<a-input v-model:value="itemFormData.value" placeholder="请输入实际值" />
</a-form-item>
<a-form-item label="排序" name="sort">
<a-input-number v-model:value="itemFormData.sort" :min="0" :max="9999" style="width: 100%" />
</a-form-item>
<a-form-item label="状态" name="status">
<a-radio-group v-model:value="itemFormData.status">
<a-radio :value="1">启用</a-radio>
<a-radio :value="0">禁用</a-radio>
</a-radio-group>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
PlusOutlined,
DeleteOutlined,
CheckOutlined,
CloseOutlined,
} from '@ant-design/icons-vue'
import systemApi from '@/api/system'
import scTable from '@/components/scTable/index.vue'
defineOptions({
name: 'DictionaryManagement',
})
const searchParams = ref({
keyword: '',
status: undefined,
})
const loading = ref(false)
const dataSource = ref([])
const pagination = ref({
current: 1,
pageSize: 20,
total: 0,
})
const selectedRowKeys = ref([])
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys
},
}))
const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '字典名称', dataIndex: 'name', key: 'name', width: 200 },
{ title: '字典编码', dataIndex: 'code', key: 'code', width: 200 },
{ title: '描述', dataIndex: 'description', key: 'description', width: 250 },
{ title: '字典项', key: 'item_count', width: 100, align: 'center' },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'action', width: 200, fixed: 'right' },
]
const modalVisible = ref(false)
const modalTitle = ref('新增字典')
const formData = ref({})
const formRef = ref(null)
const formRules = {
name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
code: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
}
const itemModalVisible = ref(false)
const itemLoading = ref(false)
const itemDataSource = ref([])
const currentDictionary = ref(null)
const itemColumns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '显示标签', dataIndex: 'label', key: 'label', width: 200 },
{ title: '实际值', dataIndex: 'value', key: 'value', width: 200 },
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 80, align: 'center' },
{ title: '状态', key: 'status', width: 80, align: 'center' },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'action', width: 150, fixed: 'right' },
]
const itemEditVisible = ref(false)
const itemEditTitle = ref('新增字典项')
const itemFormData = ref({})
const itemFormRef = ref(null)
const itemFormRules = {
label: [{ required: true, message: '请输入显示标签', trigger: 'blur' }],
value: [{ required: true, message: '请输入实际值', trigger: 'blur' }],
}
const fetchData = async () => {
loading.value = true
try {
const res = await systemApi.dictionaries.list.get({
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
})
dataSource.value = res.data.list
pagination.value.total = res.data.total
} catch (error) {
message.error('获取字典列表失败')
} finally {
loading.value = false
}
}
const handleSearch = () => {
pagination.value.current = 1
fetchData()
}
const handleReset = () => {
searchParams.value = {
keyword: '',
status: undefined,
}
pagination.value.current = 1
fetchData()
}
const handlePageChange = (page) => {
pagination.value.current = page
fetchData()
}
const handleAdd = () => {
modalTitle.value = '新增字典'
formData.value = {
status: 1,
sort: 0,
}
modalVisible.value = true
}
const handleEdit = (record) => {
modalTitle.value = '编辑字典'
formData.value = { ...record }
modalVisible.value = true
}
const handleSubmit = async () => {
try {
await formRef.value.validate()
if (formData.value.id) {
await systemApi.dictionaries.edit.put(formData.value.id, formData.value)
message.success('更新成功')
} else {
await systemApi.dictionaries.add.post(formData.value)
message.success('创建成功')
}
modalVisible.value = false
fetchData()
} catch (error) {
if (error.errorFields) {
return
}
message.error(error.message || '操作失败')
}
}
const handleCancel = () => {
modalVisible.value = false
formData.value = {}
formRef.value?.resetFields()
}
const handleDelete = async (id) => {
try {
await systemApi.dictionaries.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) {
message.error('删除失败')
}
}
const handleBatchDelete = async () => {
try {
await systemApi.dictionaries.batchDelete.post({ ids: selectedRowKeys.value })
message.success('批量删除成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('批量删除失败')
}
}
const handleBatchStatus = async (status = 1) => {
try {
await systemApi.dictionaries.batchStatus.post({ ids: selectedRowKeys.value, status })
message.success(status ? '批量启用成功' : '批量禁用成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('操作失败')
}
}
const handleItems = async (record) => {
currentDictionary.value = record
itemModalVisible.value = true
await fetchDictionaryItems(record.id)
}
const fetchDictionaryItems = async (dictionaryId) => {
itemLoading.value = true
try {
const res = await systemApi.dictionaryItems.list.get({ dictionary_id: dictionaryId })
itemDataSource.value = res.data.list || res.data
} catch (error) {
message.error('获取字典项失败')
} finally {
itemLoading.value = false
}
}
const handleAddItem = () => {
itemEditTitle.value = '新增字典项'
itemFormData.value = {
dictionary_id: currentDictionary.value.id,
status: 1,
sort: 0,
}
itemEditVisible.value = true
}
const handleEditItem = (record) => {
itemEditTitle.value = '编辑字典项'
itemFormData.value = { ...record }
itemEditVisible.value = true
}
const handleItemSubmit = async () => {
try {
await itemFormRef.value.validate()
if (itemFormData.value.id) {
await systemApi.dictionaryItems.edit.put(itemFormData.value.id, itemFormData.value)
message.success('更新成功')
} else {
await systemApi.dictionaryItems.add.post(itemFormData.value)
message.success('创建成功')
}
itemEditVisible.value = false
fetchDictionaryItems(currentDictionary.value.id)
} catch (error) {
if (error.errorFields) {
return
}
message.error(error.message || '操作失败')
}
}
const handleDeleteItem = async (id) => {
try {
await systemApi.dictionaryItems.delete.delete(id)
message.success('删除成功')
fetchDictionaryItems(currentDictionary.value.id)
} catch (error) {
message.error('删除失败')
}
}
onMounted(() => {
fetchData()
})
</script>
<style scoped lang="scss">
.dictionary-management {
padding: 16px;
.search-card {
margin-bottom: 16px;
}
.table-card {
:deep(.ant-card-body) {
padding: 16px;
}
}
.dictionary-items {
padding: 0;
}
}
</style>
@@ -1,368 +0,0 @@
<template>
<div class="log-management">
<!-- 搜索表单 -->
<a-card class="search-card" :bordered="false">
<a-form :model="searchParams" layout="inline">
<a-form-item label="关键词">
<a-input v-model:value="searchParams.keyword" placeholder="日志内容" allow-clear style="width: 200px" />
</a-form-item>
<a-form-item label="日志类型">
<a-select v-model:value="searchParams.type" allow-clear placeholder="请选择类型" style="width: 120px">
<a-select-option value="info">信息</a-select-option>
<a-select-option value="warning">警告</a-select-option>
<a-select-option value="error">错误</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="时间范围">
<a-range-picker
v-model:value="searchParams.date_range"
show-time
format="YYYY-MM-DD HH:mm:ss"
placeholder="['开始时间', '结束时间']"
style="width: 350px"
/>
</a-form-item>
<a-form-item>
<a-space>
<a-button type="primary" @click="handleSearch">
<template #icon><SearchOutlined /></template>
搜索
</a-button>
<a-button @click="handleReset">
<template #icon><RedoOutlined /></template>
重置
</a-button>
<a-button @click="handleExport">
<template #icon><ExportOutlined /></template>
导出
</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<!-- 操作按钮 -->
<a-card class="table-card" :bordered="false">
<template #title>
<a-space>
<a-button v-if="selectedRowKeys.length > 0" @click="handleBatchDelete" danger>
<template #icon><DeleteOutlined /></template>
批量删除
</a-button>
<a-popconfirm title="确定要清空所有日志吗?" @confirm="handleClearAll">
<a-button danger>
<template #icon><ClearOutlined /></template>
清空日志
</a-button>
</a-popconfirm>
</a-space>
</template>
<!-- 数据表格 -->
<sc-table
:columns="columns"
:data-source="dataSource"
:loading="loading"
:pagination="pagination"
:row-selection="rowSelection"
@page-change="handlePageChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'type'">
<a-tag :color="getTypeColor(record.type)">
<template #icon>
<InfoCircleOutlined v-if="record.type === 'info'" />
<WarningOutlined v-else-if="record.type === 'warning'" />
<CloseCircleOutlined v-else-if="record.type === 'error'" />
</template>
{{ getTypeLabel(record.type) }}
</a-tag>
</template>
<template v-if="column.key === 'message'">
<a-tooltip :title="record.message">
<span class="log-message">{{ record.message }}</span>
</a-tooltip>
</template>
<template v-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="handleDetail(record)">详情</a-button>
<a-popconfirm title="确定要删除该日志吗?" @confirm="handleDelete(record.id)">
<a-button type="link" size="small" danger>删除</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</sc-table>
</a-card>
<!-- 日志详情弹窗 -->
<a-modal
v-model:open="detailVisible"
title="日志详情"
:width="800"
:footer="null"
>
<div class="log-detail" v-if="currentLog">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="ID">{{ currentLog.id }}</a-descriptions-item>
<a-descriptions-item label="日志类型">
<a-tag :color="getTypeColor(currentLog.type)">
{{ getTypeLabel(currentLog.type) }}
</a-tag>
</a-descriptions-item>
<a-descriptions-item label="用户">{{ currentLog.username || '-' }}</a-descriptions-item>
<a-descriptions-item label="IP地址">{{ currentLog.ip || '-' }}</a-descriptions-item>
<a-descriptions-item label="请求方法">{{ currentLog.method || '-' }}</a-descriptions-item>
<a-descriptions-item label="请求路径">{{ currentLog.url || '-' }}</a-descriptions-item>
<a-descriptions-item label="User Agent">
<span class="user-agent">{{ currentLog.user_agent || '-' }}</span>
</a-descriptions-item>
<a-descriptions-item label="日志内容">
<pre class="log-content">{{ currentLog.message }}</pre>
</a-descriptions-item>
<a-descriptions-item v-if="currentLog.context" label="上下文">
<pre class="log-context">{{ formatJson(currentLog.context) }}</pre>
</a-descriptions-item>
<a-descriptions-item label="创建时间">{{ currentLog.created_at }}</a-descriptions-item>
</a-descriptions>
</div>
</a-modal>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
SearchOutlined,
RedoOutlined,
DeleteOutlined,
ExportOutlined,
ClearOutlined,
InfoCircleOutlined,
WarningOutlined,
CloseCircleOutlined,
} from '@ant-design/icons-vue'
import systemApi from '@/api/system'
import scTable from '@/components/scTable/index.vue'
import dayjs from 'dayjs'
defineOptions({
name: 'LogManagement',
})
const searchParams = ref({
keyword: '',
type: undefined,
date_range: undefined,
})
const loading = ref(false)
const dataSource = ref([])
const pagination = ref({
current: 1,
pageSize: 20,
total: 0,
})
const selectedRowKeys = ref([])
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys
},
}))
const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '日志类型', key: 'type', width: 100, align: 'center' },
{ title: '日志内容', key: 'message', width: 400 },
{ title: '用户', dataIndex: 'username', key: 'username', width: 120 },
{ title: 'IP地址', dataIndex: 'ip', key: 'ip', width: 130 },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'action', width: 150, fixed: 'right' },
]
const detailVisible = ref(false)
const currentLog = ref(null)
const fetchData = async () => {
loading.value = true
try {
const params = {
page: pagination.value.current,
page_size: pagination.value.pageSize,
...searchParams.value,
}
if (params.date_range && params.date_range.length === 2) {
params.start_time = dayjs(params.date_range[0]).format('YYYY-MM-DD HH:mm:ss')
params.end_time = dayjs(params.date_range[1]).format('YYYY-MM-DD HH:mm:ss')
}
delete params.date_range
const res = await systemApi.logs.list.get(params)
dataSource.value = res.data.list
pagination.value.total = res.data.total
} catch (error) {
message.error('获取日志列表失败')
} finally {
loading.value = false
}
}
const handleSearch = () => {
pagination.value.current = 1
fetchData()
}
const handleReset = () => {
searchParams.value = {
keyword: '',
type: undefined,
date_range: undefined,
}
pagination.value.current = 1
fetchData()
}
const handlePageChange = (page) => {
pagination.value.current = page
fetchData()
}
const handleDetail = (record) => {
currentLog.value = record
detailVisible.value = true
}
const handleDelete = async (id) => {
try {
await systemApi.logs.delete.delete(id)
message.success('删除成功')
fetchData()
} catch (error) {
message.error('删除失败')
}
}
const handleBatchDelete = async () => {
try {
await systemApi.logs.batchDelete.post({ ids: selectedRowKeys.value })
message.success('批量删除成功')
selectedRowKeys.value = []
fetchData()
} catch (error) {
message.error('批量删除失败')
}
}
const handleClearAll = async () => {
try {
await systemApi.logs.clear.post()
message.success('清空日志成功')
fetchData()
} catch (error) {
message.error('清空日志失败')
}
}
const handleExport = async () => {
try {
const params = { ...searchParams.value }
if (params.date_range && params.date_range.length === 2) {
params.start_time = dayjs(params.date_range[0]).format('YYYY-MM-DD HH:mm:ss')
params.end_time = dayjs(params.date_range[1]).format('YYYY-MM-DD HH:mm:ss')
}
delete params.date_range
const res = await systemApi.logs.export.get(params)
const url = window.URL.createObjectURL(new Blob([res]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', `logs_${Date.now()}.xlsx`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
message.success('导出成功')
} catch (error) {
message.error('导出失败')
}
}
const getTypeColor = (type) => {
const colors = {
info: 'blue',
warning: 'orange',
error: 'red',
}
return colors[type] || 'default'
}
const getTypeLabel = (type) => {
const labels = {
info: '信息',
warning: '警告',
error: '错误',
}
return labels[type] || type
}
const formatJson = (data) => {
try {
return typeof data === 'string' ? data : JSON.stringify(data, null, 2)
} catch {
return String(data)
}
}
onMounted(() => {
fetchData()
})
</script>
<style scoped lang="scss">
.log-management {
padding: 16px;
.search-card {
margin-bottom: 16px;
}
.table-card {
:deep(.ant-card-body) {
padding: 16px;
}
}
.log-message {
display: inline-block;
max-width: 380px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #666;
}
.log-detail {
.user-agent {
word-break: break-all;
color: #666;
font-size: 13px;
}
.log-content,
.log-context {
margin: 0;
max-height: 300px;
overflow: auto;
background: #f5f5f5;
padding: 12px;
border-radius: 4px;
font-size: 13px;
line-height: 1.6;
}
}
}
</style>