Files
ecom-dmb/ecom-dmb-frontend/apps/web-antd/src/components/CompanyMenuDrawer.vue
T

577 lines
15 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.
<script setup lang="ts">
import type { MenuVO } from '#/api/sys/menu/types';
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { Button, message, Select, Spin, Tree } from 'ant-design-vue';
import {
batchUpdateCompanyMenusApi,
getCompanyMenuIdsApi,
} from '#/api/company/menu';
import { getAllMenusApi } from '#/api/sys/menu';
interface Props {
company?: any;
}
interface Emits {
(e: 'success'): void;
(e: 'close'): void;
}
defineOptions({
name: 'CompanyMenuDrawer',
});
defineProps<Props>();
const emit = defineEmits<Emits>();
// 系统菜单列表数据
const systemMenuList = ref<MenuVO.MenuInfo[]>([]);
// 公司菜单ID列表
const companyMenuIds = ref<number[]>([]);
// 加载状态
const loading = ref(false);
// 保存状态
const saving = ref(false);
// 当前公司信息
const currentCompany = ref<any>();
// 选中的菜单ID
const checkedKeys = ref<number[]>([]);
// 展开的节点键
const expandedKeys = ref<number[]>([]);
// 分组选择
const selectedGroup = ref<'normal' | 'super' | undefined>(undefined);
// 分组选项
const groupOptions = [
{ label: '超管菜单', value: 'super' as const },
{ label: '普通菜单', value: 'normal' as const },
];
// 创建抽屉组件
const [MainDrawer, mainDrawerApi] = useVbenDrawer({
title: '公司菜单权限管理',
placement: 'right',
class: 'w-[800px]',
zIndex: 1001,
confirmText: '保存权限配置',
cancelText: '取消',
onConfirm: async () => {
await handleSave();
},
onCancel() {
handleClose();
},
onClosed() {
emit('close');
},
});
// 将菜单列表转换为树形结构
const menuTreeData = computed(() => {
const menuMap = new Map<number, any>();
const rootMenus: any[] = [];
// 先创建所有节点
systemMenuList.value.forEach((menu) => {
menuMap.set(menu.id, {
key: menu.id,
title: menu.name,
type: menu.type,
superMenu: menu.superMenu,
status: menu.status,
disabled: menu.status === 0, // 禁用状态的菜单不可选择
children: [],
});
});
// 构建树形结构
systemMenuList.value.forEach((menu) => {
const node = menuMap.get(menu.id)!;
if (menu.parentId && menuMap.has(menu.parentId)) {
const parent = menuMap.get(menu.parentId)!;
parent.children.push(node);
} else {
rootMenus.push(node);
}
});
return rootMenus;
});
// 统计信息
const stats = computed(() => {
const totalMenus = systemMenuList.value.length;
const companyMenus = companyMenuIds.value.length;
const selectedMenus = calculateCorrectSelectedCount(checkedKeys.value);
return {
total: totalMenus,
company: companyMenus,
selected: selectedMenus,
};
});
// 计算正确的选中数量(处理父节点逻辑)
function calculateCorrectSelectedCount(menuIds: number[]): number {
// 使用与提交时相同的逻辑,确保统计数量与提交数量一致
const finalMenuIds = ensureParentMenuIds(menuIds);
return finalMenuIds.length;
}
// 清理根节点,只保留叶子节点
function cleanRootNodes(menuIds: number[]): number[] {
return menuIds.filter((menuId) => {
const menu = systemMenuList.value.find((m) => m.id === menuId);
if (!menu) return false;
// 检查是否有其他菜单将此菜单作为父菜单
const hasChildren = systemMenuList.value.some(
(otherMenu) => otherMenu.parentId === menuId,
);
// 只保留叶子节点(没有子节点的菜单)
return !hasChildren;
});
}
// 加载数据
async function loadData() {
if (!currentCompany.value?.id) return;
loading.value = true;
try {
const [systemData, companyData] = await Promise.all([
getAllMenusApi(),
getCompanyMenuIdsApi(currentCompany.value.id),
]);
systemMenuList.value = systemData;
companyMenuIds.value = companyData;
// 清理根节点,只保留叶子节点
const leafMenuIds = cleanRootNodes(companyData);
checkedKeys.value = leafMenuIds;
// 自动展开所有节点
expandedKeys.value = systemData.map((menu) => menu.id);
} catch (error: any) {
message.error(error?.message || '加载数据失败');
} finally {
loading.value = false;
}
}
// 保存所有更改
async function handleSave() {
if (!currentCompany.value?.id) return;
saving.value = true;
try {
// 确保提交时包含必要的父菜单ID
const finalMenuIds = ensureParentMenuIds(checkedKeys.value);
await batchUpdateCompanyMenusApi(currentCompany.value.id, finalMenuIds);
message.success('权限配置保存成功');
emit('success');
handleClose();
} catch (error: any) {
message.error(error?.message || '保存失败');
throw error; // 重新抛出错误,让抽屉知道保存失败
} finally {
saving.value = false;
}
}
// 一键全选
function handleSelectAll() {
// 获取所有可选择的菜单ID(排除禁用的)
let selectableMenus = systemMenuList.value.filter(
(menu) => menu.status === 1,
);
// 如果选择了分组,则只选择该分组的菜单
if (selectedGroup.value) {
if (selectedGroup.value === 'super') {
selectableMenus = selectableMenus.filter((menu) => menu.superMenu === 1);
} else if (selectedGroup.value === 'normal') {
selectableMenus = selectableMenus.filter((menu) => menu.superMenu !== 1);
}
}
// 只选择叶子节点(没有子节点的菜单)
const leafMenus = selectableMenus.filter((menu) => {
// 检查是否有其他菜单将此菜单作为父菜单
const hasChildren = systemMenuList.value.some(
(otherMenu) => otherMenu.parentId === menu.id,
);
return !hasChildren;
});
if (selectedGroup.value) {
// 保留其他分组的选中状态,只替换当前分组的选中状态
const otherGroupCheckedKeys = checkedKeys.value.filter((id) => {
const menu = systemMenuList.value.find((m) => m.id === id);
if (!menu) return false;
if (selectedGroup.value === 'super') {
return menu.superMenu !== 1;
} else if (selectedGroup.value === 'normal') {
return menu.superMenu === 1;
}
return false;
});
checkedKeys.value = [
...otherGroupCheckedKeys,
...leafMenus.map((menu) => menu.id),
];
} else {
// 如果没有选择分组,全选所有叶子节点
checkedKeys.value = leafMenus.map((menu) => menu.id);
}
}
// 取消全选
function handleSelectNone() {
if (selectedGroup.value) {
// 如果选择了分组,只取消该分组的叶子节点选中状态
const leafMenuIds = new Set(
systemMenuList.value
.filter((menu) => {
// 只处理叶子节点
const hasChildren = systemMenuList.value.some(
(otherMenu) => otherMenu.parentId === menu.id,
);
if (hasChildren) return false;
// 根据分组过滤
if (selectedGroup.value === 'super') {
return menu.superMenu === 1;
} else if (selectedGroup.value === 'normal') {
return menu.superMenu !== 1;
}
return false;
})
.map((menu) => menu.id),
);
checkedKeys.value = checkedKeys.value.filter((id) => !leafMenuIds.has(id));
} else {
// 如果没有选择分组,取消所有叶子节点的选中状态
const allLeafMenuIds = new Set(
systemMenuList.value
.filter((menu) => {
// 只处理叶子节点
return !systemMenuList.value.some(
(otherMenu) => otherMenu.parentId === menu.id,
);
})
.map((menu) => menu.id),
);
checkedKeys.value = checkedKeys.value.filter(
(id) => !allLeafMenuIds.has(id),
);
}
}
// 处理树形控件的选中变化
function handleTreeCheckChange(
checked: (number | string)[] | { checked: (number | string)[]; halfChecked: (number | string)[] },
) {
const checkedKeysValue = Array.isArray(checked) ? checked : checked.checked;
// 对比新旧值,找出被取消勾选的节点
const oldKeys = new Set<number>(checkedKeys.value);
const newKeys = new Set<number>(checkedKeysValue as number[]);
// 找出移除的(取消勾选)的节点
const removedKeys = oldKeys.difference(newKeys);
// 如果是取消勾选,需要把取消节点的子节点也一并移除
if (removedKeys.size > 0) {
// 构建 parentId -> childIds 的映射
const parentToChildren = new Map<number, number[]>();
for (const menu of systemMenuList.value) {
if (menu.parentId) {
const children = parentToChildren.get(menu.parentId) || [];
children.push(menu.id);
parentToChildren.set(menu.parentId, children);
}
}
// 递归移除子节点
function removeDescendants(nodeId: number) {
const children = parentToChildren.get(nodeId) || [];
for (const childId of children) {
newKeys.delete(childId);
removeDescendants(childId);
}
}
for (const removedId of removedKeys) {
removeDescendants(removedId);
}
}
checkedKeys.value = [...newKeys];
}
// 确保提交时包含必要的父菜单ID(递归添加所有层级的父菜单)
function ensureParentMenuIds(menuIds: number[]): number[] {
const result = new Set(menuIds);
// 递归添加所有父菜单ID
function addAllParentIds(menuId: number) {
const menu = systemMenuList.value.find((m) => m.id === menuId);
if (menu && menu.parentId) {
result.add(menu.parentId);
// 递归添加父菜单的父菜单
addAllParentIds(menu.parentId);
}
}
// 为每个选中的菜单添加其所有父菜单ID
menuIds.forEach((menuId) => {
addAllParentIds(menuId);
});
const finalResult = [...result];
return finalResult;
}
// 关闭抽屉
function handleClose() {
mainDrawerApi.close();
checkedKeys.value = [];
expandedKeys.value = [];
selectedGroup.value = undefined;
}
// 暴露打开方法
defineExpose({
open: (company: any) => {
// 设置公司信息
currentCompany.value = company;
// 打开抽屉
mainDrawerApi.open();
// 加载数据
if (company?.id) {
loadData();
}
},
close: () => mainDrawerApi.close(),
});
</script>
<template>
<MainDrawer>
<div class="permission-drawer">
<!-- 头部信息 -->
<div class="drawer-header">
<div class="company-info">
<span class="company-name">{{ currentCompany?.name }}</span>
<span class="company-id">(ID: {{ currentCompany?.id }})</span>
</div>
<div class="stats-section">
<div class="stats-left">
<div class="stat-item">
<span class="label">系统菜单:</span>
<span class="value">{{ stats.total }}</span>
</div>
<div class="stat-item">
<span class="label">已配置:</span>
<span class="value success">{{ stats.company }}</span>
</div>
<div class="stat-item">
<span class="label">当前选择:</span>
<span class="value primary">{{ stats.selected }}</span>
</div>
</div>
<div class="stats-right">
<Select
v-model:value="selectedGroup"
placeholder="选择分组"
allow-clear
style="width: 120px; margin-right: 8px"
>
<Select.Option
v-for="option in groupOptions"
:key="option.value || 'all'"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
<Button type="primary" @click="handleSelectAll"> 一键全选 </Button>
<Button @click="handleSelectNone"> 取消全选 </Button>
</div>
</div>
</div>
<!-- 菜单树 -->
<div class="menu-tree-container">
<Spin :spinning="loading">
<Tree
v-model:checked-keys="checkedKeys"
v-model:expanded-keys="expandedKeys"
:tree-data="menuTreeData"
checkable
class="menu-tree"
@check="handleTreeCheckChange"
>
<template #title="{ title, status, disabled, superMenu }">
<div class="menu-item">
<span class="menu-name">{{ title }}</span>
<span v-if="superMenu === 1" class="menu-tag super">
超管
</span>
<span v-if="status === 0" class="menu-status disabled">
已禁用
</span>
<span v-if="disabled" class="menu-status disabled">
不可选择
</span>
</div>
</template>
</Tree>
</Spin>
</div>
</div>
</MainDrawer>
</template>
<style lang="scss" scoped>
.permission-drawer {
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
.drawer-header {
padding: 16px 0;
border-bottom: 1px solid var(--border);
margin-bottom: 16px;
background-color: var(--background-color);
flex-shrink: 0;
.company-info {
margin-bottom: 12px;
.company-name {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
}
.company-id {
font-size: 12px;
color: var(--text-secondary);
margin-left: 8px;
}
}
.stats-section {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 12px 16px;
background-color: var(--background-secondary);
border-radius: 6px;
.stats-left {
display: flex;
gap: 16px;
}
.stats-right {
display: flex;
gap: 8px;
}
.stat-item {
display: flex;
align-items: center;
gap: 4px;
.label {
font-size: 12px;
color: var(--text-secondary);
}
.value {
font-weight: 600;
font-size: 14px;
&.success {
color: var(--success);
}
&.primary {
color: var(--primary);
}
}
}
}
}
.menu-tree-container {
flex: 1;
overflow-y: auto;
min-height: 0;
.menu-tree {
padding: 12px;
border: 1px solid var(--border);
border-radius: 6px;
.menu-item {
display: flex;
align-items: center;
gap: 8px;
.menu-name {
font-weight: 500;
color: var(--text-primary);
}
.menu-tag {
font-size: 12px;
padding: 2px 6px;
border-radius: 3px;
&.super {
color: var(--warning);
background-color: var(--warning-light);
}
}
.menu-status {
font-size: 12px;
padding: 2px 6px;
border-radius: 3px;
&.disabled {
color: var(--error);
background-color: var(--error-light);
}
}
}
}
}
}
// 响应式设计
@media (max-width: 768px) {
.stats-section {
flex-wrap: wrap;
}
}
</style>