Files
JayuCloud/JC-Salon-Frontend/src/views/admin/PermissionsView.vue
T

836 lines
35 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="permissions">
<a-page-header v-if="!isMobile" title="权限管理" sub-title="管理系统权限和用户权限分配" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">权限管理</h1>
<p class="admin-page-intro__subtitle">
手机端拆成“权限列表”和“用户权限”两段流程,先选人再分配,避免保留桌面双栏布局。
</p>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">权限 {{ permissionList.length }}</span>
<span class="admin-page-chip">用户 {{ filteredUserList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<a-tabs v-model:activeKey="activeTab">
<a-tab-pane key="permissions" tab="权限列表">
<div style="margin-bottom: 16px;" :style="isMobile ? {} : { textAlign: 'right' }">
<a-button v-if="!isMobile && hasPermission('permission:create')" type="primary" @click="showAddPermissionModal">
<template #icon>
<PlusOutlined />
</template>
新增权限
</a-button>
</div>
<a-table
v-if="!isMobile"
:columns="permissionColumns"
:data-source="permissionList"
:loading="loading"
:pagination="permissionPagination"
:scroll="{ x: 'max-content' }"
@change="handlePermissionTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'permissionGroup'">
<a-tag color="purple">{{ record.permissionGroup }}</a-tag>
</template>
<template v-else-if="column.key === 'permissionCode'">
<div style="max-width: 220px;">
<TableEllipsisText :text="record.permissionCode" />
</div>
</template>
<template v-else-if="column.key === 'permissionName'">
<div style="max-width: 180px;">
<TableEllipsisText :text="record.permissionName" />
</div>
</template>
<template v-else-if="column.key === 'description'">
<div style="max-width: 320px;">
<TableEllipsisText :text="record.description" :lines="2" />
</div>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('permission:edit')" type="link" size="small" @click="showEditPermissionModal(record)">
编辑
</a-button>
<a-popconfirm
v-if="hasPermission('permission:delete')"
title="确定要删除这个权限吗?"
@confirm="handleDeletePermission(record)"
>
<a-button type="link" size="small" danger>
删除
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="permissionList" empty-description="暂无权限数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<div class="admin-mobile-card__head">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.permissionName }}</div>
<div class="admin-mobile-card__subtitle">{{ item.permissionCode }}</div>
</div>
<a-tag color="purple">{{ item.permissionGroup }}</a-tag>
</div>
<div class="admin-mobile-card__description">{{ item.description }}</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>创建时间</span>
<strong>{{ item.createTime }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button v-if="hasPermission('permission:edit')" size="small" @click="showEditPermissionModal(item)">编辑</a-button>
<a-button v-if="hasPermission('permission:delete')" size="small" danger @click="handleDeletePermission(item)">删除</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-tab-pane>
<a-tab-pane v-if="hasPermission('permission:assign')" key="user-permissions" tab="用户权限分配">
<template v-if="!isMobile">
<a-row :gutter="16">
<a-col :span="8">
<a-card title="选择用户" :bordered="false">
<a-input-search
v-model:value="userSearchText"
placeholder="搜索用户"
style="margin-bottom: 16px"
@search="handleUserSearch"
/>
<a-list
:data-source="filteredUserList"
:loading="userLoading"
item-layout="horizontal"
size="small"
>
<template #renderItem="{ item }">
<a-list-item
:class="{ selected: sameId(selectedUser?.id, item.id) }"
style="cursor: pointer;"
@click="selectUser(item)"
>
<a-list-item-meta>
<template #avatar>
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
</template>
<template #title>{{ item.nickname }}</template>
<template #description>{{ item.account }} - {{ getUserTypeText(item.type) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</a-col>
<a-col :span="16">
<a-card
title="分配权限"
:bordered="false"
>
<template #extra>
<a-button v-if="selectedUser && hasPermission('permission:assign')" type="primary" @click="handleSaveUserPermissions">
保存权限
</a-button>
</template>
<template v-if="selectedUser">
<a-alert
:message="`当前用户: ${selectedUser.nickname}`"
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
type="info"
show-icon
style="margin-bottom: 16px"
/>
<a-alert
v-if="disabledPermissionCount > 0"
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁止选择`"
type="warning"
show-icon
style="margin-bottom: 16px"
/>
<a-spin :spinning="assignLoading">
<a-checkbox-group v-model:value="selectedPermissions">
<a-collapse v-model:activeKey="activeCollapseKeys">
<a-collapse-panel
v-for="(permissions, group) in groupedPermissions"
:key="group"
:header="group"
>
<a-space direction="vertical" style="width: 100%">
<a-checkbox
v-for="permission in permissions"
:key="permission.id"
:value="permission.id"
:disabled="isPermissionDisabled(permission)"
>
{{ permission.permissionName }}
<span style="color: var(--text-secondary); font-size: 12px; margin-left: 8px;">
({{ permission.permissionCode }})
</span>
<span
v-if="isPermissionDisabled(permission)"
style="color: #ff4d4f; font-size: 12px; margin-left: 8px;"
>
不可分配
</span>
</a-checkbox>
</a-space>
</a-collapse-panel>
</a-collapse>
</a-checkbox-group>
</a-spin>
</template>
<a-empty v-else description="请先选择一个用户" />
</a-card>
</a-col>
</a-row>
</template>
<template v-else>
<div class="mobile-permission-flow">
<template v-if="mobilePermissionStep === 'users' || !selectedUser">
<a-input-search
v-model:value="userSearchText"
placeholder="搜索用户"
style="margin-bottom: 16px"
@search="handleUserSearch"
/>
<AdminMobileCardList :items="filteredUserList" empty-description="暂无可分配权限的用户">
<template #item="{ item }">
<article class="admin-mobile-card" @click="selectUser(item)">
<div class="admin-mobile-card__head">
<div class="mobile-user-pick">
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.nickname }}</div>
<div class="admin-mobile-card__subtitle">{{ item.account }} · {{ getUserTypeText(item.type) }}</div>
</div>
</div>
<span class="admin-mobile-card__badge">选择</span>
</div>
</article>
</template>
</AdminMobileCardList>
</template>
<template v-else>
<div class="mobile-assign-actions">
<a-button @click="mobilePermissionStep = 'users'">返回选用户</a-button>
<a-button type="primary" @click="handleSaveUserPermissions">保存权限</a-button>
</div>
<a-alert
:message="`当前用户: ${selectedUser.nickname}`"
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
type="info"
show-icon
style="margin-bottom: 16px"
/>
<a-alert
v-if="disabledPermissionCount > 0"
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁用`"
type="warning"
show-icon
style="margin-bottom: 16px"
/>
<a-spin :spinning="assignLoading">
<a-checkbox-group v-model:value="selectedPermissions" style="width: 100%">
<a-collapse v-model:activeKey="activeCollapseKeys">
<a-collapse-panel
v-for="(permissions, group) in groupedPermissions"
:key="group"
:header="group"
>
<a-space direction="vertical" style="width: 100%">
<a-checkbox
v-for="permission in permissions"
:key="permission.id"
:value="permission.id"
:disabled="isPermissionDisabled(permission)"
>
{{ permission.permissionName }}
<span style="color: var(--text-secondary); font-size: 12px; margin-left: 8px;">
({{ permission.permissionCode }})
</span>
</a-checkbox>
</a-space>
</a-collapse-panel>
</a-collapse>
</a-checkbox-group>
</a-spin>
</template>
</div>
</template>
</a-tab-pane>
</a-tabs>
</a-card>
<AdminResponsiveModal
v-model:open="permissionModalVisible"
:title="isEditPermission ? '编辑权限' : '新增权限'"
@ok="handlePermissionModalOk"
@cancel="handlePermissionModalCancel"
:confirmLoading="permissionModalLoading"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="permissionFormRef"
:model="permissionFormState"
:rules="permissionFormRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="权限编码" name="permissionCode">
<a-input v-model:value="permissionFormState.permissionCode" placeholder="例如:product:add" />
</a-form-item>
<a-form-item label="权限名称" name="permissionName">
<a-input v-model:value="permissionFormState.permissionName" placeholder="例如:添加作品" />
</a-form-item>
<a-form-item label="权限分组" name="permissionGroup">
<a-select v-model:value="permissionFormState.permissionGroup" placeholder="请选择权限分组">
<a-select-option value="作品管理">作品管理</a-select-option>
<a-select-option value="店铺管理">店铺管理</a-select-option>
<a-select-option value="用户管理">用户管理</a-select-option>
<a-select-option value="权限管理">权限管理</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="权限描述" name="description">
<a-textarea
v-model:value="permissionFormState.description"
placeholder="请输入权限描述"
:rows="3"
/>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && activeTab === 'permissions' && hasPermission('permission:create') && !permissionModalVisible"
label="新增权限"
@click="showAddPermissionModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* PermissionsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
import { DEFAULT_AVATAR } from '@/constants'
/**
* Purpose: UserVO supports PermissionsView.vue by holding or executing the user vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { userApi, type UserVO } from '@/api/admin'
/**
* Purpose: PermissionVO supports PermissionsView.vue by holding or executing the permission vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { permissionApi, type PermissionVO } from '@/api/permission'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** activeTab is a reactive state variable used by the template and event handlers. */
const activeTab = ref('permissions')
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/**
* Purpose: permissionList supports PermissionsView.vue by holding or executing the permission list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const permissionList = ref<PermissionVO[]>([])
/** permissionModalVisible is a reactive state variable used by the template and event handlers. */
const permissionModalVisible = ref(false)
/** permissionModalLoading is a reactive state variable used by the template and event handlers. */
const permissionModalLoading = ref(false)
/** isEditPermission is a reactive state variable used by the template and event handlers. */
const isEditPermission = ref(false)
/**
* Purpose: permissionFormRef supports PermissionsView.vue by holding or executing the permission form ref page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const permissionFormRef = ref<FormInstance>()
/**
* Purpose: currentPermission supports PermissionsView.vue by holding or executing the current permission page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const currentPermission = ref<PermissionVO | null>(null)
/**
* Purpose: draftSavedAt supports PermissionsView.vue by holding or executing the draft saved at page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const draftSavedAt = ref<number | null>(null)
/**
* Purpose: permissionPagination supports PermissionsView.vue by holding or executing the permission pagination page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const permissionPagination = reactive({
current: 1,
pageSize: 20,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/**
* Purpose: permissionFormState supports PermissionsView.vue by holding or executing the permission form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const permissionFormState = reactive({
permissionCode: '',
permissionName: '',
permissionGroup: '',
description: ''
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-permissions', isEditPermission.value ? 'edit' : 'create', currentPermission.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
permissionCode: permissionFormState.permissionCode,
permissionName: permissionFormState.permissionName,
permissionGroup: permissionFormState.permissionGroup,
description: permissionFormState.description
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(permissionFormState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const permissionFormRules: Record<string, Rule[]> = {
permissionCode: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
permissionGroup: [{ required: true, message: '请选择权限分组', trigger: 'change' }],
description: [{ required: true, message: '请输入权限描述', trigger: 'blur' }]
}
/**
* Purpose: permissionColumns supports PermissionsView.vue by holding or executing the permission columns page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const permissionColumns = [
{ title: '权限编码', dataIndex: 'permissionCode', key: 'permissionCode' },
{ title: '权限名称', dataIndex: 'permissionName', key: 'permissionName' },
{ title: '权限分组', key: 'permissionGroup', width: 120 },
{ title: '权限描述', dataIndex: 'description', key: 'description' },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** userLoading is a reactive state variable used by the template and event handlers. */
const userLoading = ref(false)
/** userSearchText is a reactive state variable used by the template and event handlers. */
const userSearchText = ref('')
/**
* Purpose: userList supports PermissionsView.vue by holding or executing the user list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const userList = ref<UserVO[]>([])
/**
* Purpose: selectedUser supports PermissionsView.vue by holding or executing the selected user page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const selectedUser = ref<UserVO | null>(null)
/** assignLoading is a reactive state variable used by the template and event handlers. */
const assignLoading = ref(false)
/**
* Purpose: selectedPermissions supports PermissionsView.vue by holding or executing the selected permissions page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const selectedPermissions = ref<IdType[]>([])
/**
* Purpose: assignablePermissionIds supports PermissionsView.vue by holding or executing the assignable permission ids page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const assignablePermissionIds = ref<IdType[]>([])
/**
* Purpose: activeCollapseKeys supports PermissionsView.vue by holding or executing the active collapse keys page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const activeCollapseKeys = ref<string[]>(['作品管理', '店铺管理', '用户管理', '权限管理'])
/**
* Purpose: currentLoginUser supports PermissionsView.vue by holding or executing the current login user page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const currentLoginUser = ref<UserVO | null>(null)
/**
* Purpose: mobilePermissionStep supports PermissionsView.vue by holding or executing the mobile permission step page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const mobilePermissionStep = ref<'users' | 'assign'>('users')
// 权限 ID 同样可能以字符串形式返回,所以这里统一转成字符串集合做包含判断。
/** assignablePermissionIdSet is a reactive state variable used by the template and event handlers. */
const assignablePermissionIdSet = computed(() => new Set(assignablePermissionIds.value.map(id => String(id))))
/** disabledPermissionCount is a reactive state variable used by the template and event handlers. */
const disabledPermissionCount = computed(() =>
permissionList.value.filter(permission => !assignablePermissionIdSet.value.has(String(permission.id))).length
)
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
permissionList.value.forEach(p => {
const groupName = p.permissionGroup
if (!groups[groupName]) {
groups[groupName] = []
}
groups[groupName]!.push(p)
})
return groups
})
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number) => {
const map: Record<number, string> = {
0: '用户',
2: '店长',
3: '美甲师',
4: '管理员'
}
return map[type] || '未知'
}
/** filteredUserList is a reactive state variable used by the template and event handlers. */
const filteredUserList = computed(() => {
if (!currentLoginUser.value) return []
const currentUserId = currentLoginUser.value.id
// 管理员可以看到所有用户(除了普通用户和自己)
if (currentLoginUser.value.type === 4) {
return userList.value.filter(user => user.type !== 0 && !sameId(user.id, currentUserId))
}
// 店长只能看到美甲师(除了自己)
if (currentLoginUser.value.type === 2) {
return userList.value.filter(user => user.type === 3 && !sameId(user.id, currentUserId))
}
// 其他用户类型(如美甲师)不能管理权限
return []
})
/** isPermissionDisabled is a local helper used by this page script. */
const isPermissionDisabled = (permission: PermissionVO) => {
if (!selectedUser.value) {
return true
}
return !assignablePermissionIdSet.value.has(String(permission.id))
}
/** resolveRequestErrorMessage is a local helper used by this page script. */
const resolveRequestErrorMessage = (error: any, fallback: string) => {
return error?.response?.data?.message || error?.message || fallback
}
/** fetchCurrentUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCurrentUser = async () => {
try {
// 尝试从API获取用户信息
try {
const res = await userApi.getUserInfo()
currentLoginUser.value = res as unknown as UserVO
} catch (apiError) {
// 如果API调用失败,尝试从本地存储获取
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
try {
const userInfo = JSON.parse(userInfoStr)
currentLoginUser.value = userInfo as UserVO
} catch (parseError) {
console.error('解析本地存储的用户信息失败:', parseError)
}
} else {
console.error('获取当前用户信息失败,本地存储也没有用户信息')
}
}
} catch (error) {
console.error('获取当前用户信息失败:', error)
}
}
/** fetchPermissionList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchPermissionList = async () => {
loading.value = true
try {
const res = await permissionApi.listAllPermissions() as unknown as PermissionVO[]
permissionList.value = res || []
permissionPagination.total = res?.length || 0
} catch (error) {
message.error('获取权限列表失败')
} finally {
loading.value = false
}
}
/** fetchUserList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserList = async () => {
userLoading.value = true
try {
const params: any = {
page: 1,
size: 100,
keyword: userSearchText.value
}
// 如果当前用户不是管理员,只获取当前店铺的用户
if (currentLoginUser.value && currentLoginUser.value.type !== 4 && currentLoginUser.value.shopId) {
params.shopId = currentLoginUser.value.shopId
}
const res = await userApi.listUsers(params) as unknown as { list: UserVO[] }
userList.value = res.list || []
} catch (error) {
message.error('获取用户列表失败')
} finally {
userLoading.value = false
}
}
/** handlePermissionTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePermissionTableChange = async (pag: any) => {
permissionPagination.current = pag.current
permissionPagination.pageSize = pag.pageSize
await runWithGlobalLoading(() => fetchPermissionList())
}
/** handleUserSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUserSearch = async () => {
await runWithGlobalLoading(() => fetchUserList())
}
/** selectUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const selectUser = async (user: UserVO) => {
selectedUser.value = user
assignLoading.value = true
try {
await runWithGlobalLoading(async () => {
// 已分配权限和“当前角色允许分配的权限”需要分开拿,前端只保留交集,避免保存时越权。
const [assignedPermissions, allowedIds] = await Promise.all([
permissionApi.getUserPermissions(user.id) as unknown as Promise<PermissionVO[]>,
permissionApi.getAssignablePermissionIds(user.id) as unknown as Promise<IdType[]>
])
assignablePermissionIds.value = allowedIds || []
const allowedIdSet = new Set(assignablePermissionIds.value.map(id => String(id)))
/** assignedIds is a local helper used by this page script. */
const assignedIds = (assignedPermissions || []).map((p: PermissionVO) => p.id)
selectedPermissions.value = assignedIds.filter(id => allowedIdSet.has(String(id)))
const trimmedCount = assignedIds.length - selectedPermissions.value.length
if (trimmedCount > 0) {
message.warning(`已自动排除 ${trimmedCount} 项超出当前角色允许范围的权限`)
}
})
} catch (error: any) {
message.error(resolveRequestErrorMessage(error, '获取用户权限失败'))
assignablePermissionIds.value = []
selectedPermissions.value = []
} finally {
assignLoading.value = false
if (isMobile.value) {
mobilePermissionStep.value = 'assign'
}
}
}
/** handleSaveUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSaveUserPermissions = async () => {
if (!selectedUser.value) return
const userId = selectedUser.value.id
try {
await runWithGlobalLoading(async () => {
await permissionApi.assignUserPermissions(userId, selectedPermissions.value)
message.success('权限保存成功')
// 重新加载当前用户的权限
await loadUserPermissions()
})
} catch (error: any) {
message.error(resolveRequestErrorMessage(error, '权限保存失败'))
}
}
/** showAddPermissionModal is a local helper used by this page script. */
const showAddPermissionModal = () => {
isEditPermission.value = false
currentPermission.value = null
Object.assign(permissionFormState, {
permissionCode: '',
permissionName: '',
permissionGroup: '',
description: ''
})
restoreDraft()
permissionModalVisible.value = true
}
/** showEditPermissionModal is a local helper used by this page script. */
const showEditPermissionModal = (record: Record<string, any>) => {
isEditPermission.value = true
currentPermission.value = record as PermissionVO
Object.assign(permissionFormState, {
permissionCode: record.permissionCode,
permissionName: record.permissionName,
permissionGroup: record.permissionGroup,
description: record.description
})
restoreDraft()
permissionModalVisible.value = true
}
/** handlePermissionModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePermissionModalOk = async () => {
try {
await permissionFormRef.value?.validate()
permissionModalLoading.value = true
await runWithGlobalLoading(async () => {
if (isEditPermission.value && currentPermission.value) {
await permissionApi.updatePermission(currentPermission.value.id, permissionFormState)
message.success('更新成功')
} else {
await permissionApi.createPermission(permissionFormState)
message.success('创建成功')
}
handleClearDraft(false)
permissionModalVisible.value = false
await fetchPermissionList()
})
} catch (error) {
console.error(error)
} finally {
permissionModalLoading.value = false
}
}
/** handlePermissionModalCancel is a local helper used by this page script. */
const handlePermissionModalCancel = () => {
permissionModalVisible.value = false
permissionFormRef.value?.resetFields()
}
/** handleDeletePermission is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDeletePermission = async (record: Record<string, any>) => {
try {
await runWithGlobalLoading(async () => {
await permissionApi.deletePermission((record as PermissionVO).id)
message.success('删除成功')
await fetchPermissionList()
})
} catch (error) {
message.error('删除失败')
}
}
onMounted(async () => {
await fetchCurrentUser()
await loadUserPermissions()
fetchPermissionList()
// 确保在获取当前用户信息后再获取用户列表
setTimeout(() => {
fetchUserList()
}, 100)
})
watch(
() => activeTab.value,
value => {
if (value !== 'user-permissions') {
mobilePermissionStep.value = 'users'
}
}
)
</script>
<style scoped>
.permissions {
padding: 0;
}
.selected {
background: var(--theme-primary-soft) !important;
border-left: 3px solid var(--theme-primary);
}
.mobile-permission-flow {
display: grid;
gap: 16px;
}
.mobile-user-pick {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.mobile-assign-actions {
display: flex;
justify-content: space-between;
gap: 10px;
}
</style>