refactor: 调整页面组件位置

This commit is contained in:
2026-08-14 14:37:54 +08:00
parent 5f824531ce
commit c51e13f4b4
82 changed files with 1 additions and 1 deletions
@@ -0,0 +1,389 @@
<script lang="ts" setup>
import type { AccountDTO, AccountVO } from '#/api/organization/account';
import type { DepartmentVO } from '#/api/organization/department';
import type { PositionVO } from '#/api/organization/position';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Cascader, Form, Input, message, Select } from 'ant-design-vue';
import {
admin_createAccountApi,
admin_updateAccountApi,
} from '#/api/organization/account';
import { getDepartmentTreeApi } from '#/api/organization/department';
import { getPositionPageApi } from '#/api/organization/position';
interface Emits {
(e: 'success'): void;
}
defineOptions({ name: 'AccountFormModal' });
const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[500px]',
onCancel() {
handleCancel();
},
onConfirm() {
handleSubmit();
},
});
// 响应式数据
const formRef = ref();
const loading = ref(false);
const isEdit = ref(false);
const currentAccountData = ref<AccountVO.AccountInfoVO | null>(null);
const departmentOptionsLoading = ref(false);
const positionOptionsLoading = ref(false);
const selectorsLoaded = ref(false);
interface DepartmentCascaderOption {
children?: DepartmentCascaderOption[];
label: string;
value: number;
}
interface PositionSelectOption {
departmentId?: number;
label: string;
value: number;
}
// 表单数据
const formData = ref<AccountDTO.CreateAccountDTO & { status?: number }>({
password: '',
phone: '',
realName: '',
departmentId: undefined,
positionId: undefined,
remark: '',
});
const departmentPath = ref<number[]>([]);
const departmentTreeOptions = ref<DepartmentCascaderOption[]>([]);
const allPositionOptions = ref<PositionSelectOption[]>([]);
const positionOptions = computed(() => {
const selectedDepartmentId = formData.value.departmentId;
if (!selectedDepartmentId) return allPositionOptions.value;
return allPositionOptions.value.filter(
(item) => !item.departmentId || item.departmentId === selectedDepartmentId,
);
});
// 模态框标题
const modalTitle = computed(() => (isEdit.value ? '编辑账户' : '添加账户'));
// 状态选项
const statusOptions = [
{ label: '正常', value: 0 },
{ label: '删除', value: 1 },
{ label: '停用', value: 2 },
{ label: '冻结', value: 3 },
];
// 重置表单
function resetForm() {
formData.value = {
password: '',
phone: '',
realName: '',
departmentId: undefined,
positionId: undefined,
remark: '',
};
departmentPath.value = [];
formRef.value?.resetFields();
}
// 处理模态框关闭
function handleCancel() {
modalApi.close();
}
// 暴露给父组件的方法
function buildDepartmentTreeOptions(
departments: DepartmentVO.DepartmentInfoVO[],
): DepartmentCascaderOption[] {
return departments.map((item) => ({
children:
item.children && item.children.length > 0
? buildDepartmentTreeOptions(item.children)
: undefined,
label: item.name,
value: item.id,
}));
}
function findDepartmentPathById(
options: DepartmentCascaderOption[],
departmentId: number,
currentPath: number[] = [],
): null | number[] {
for (const option of options) {
const nextPath = [...currentPath, option.value];
if (option.value === departmentId) return nextPath;
if (option.children?.length) {
const result = findDepartmentPathById(
option.children,
departmentId,
nextPath,
);
if (result) return result;
}
}
return null;
}
async function loadDepartmentOptions() {
try {
departmentOptionsLoading.value = true;
const data = await getDepartmentTreeApi();
departmentTreeOptions.value = buildDepartmentTreeOptions(data || []);
} catch (error) {
console.error('获取部门树失败:', error);
message.error('获取部门树失败');
departmentTreeOptions.value = [];
} finally {
departmentOptionsLoading.value = false;
}
}
async function loadPositionOptions() {
try {
positionOptionsLoading.value = true;
const params: PageQueryDTO = {
page: 1,
pageSize: 1000,
};
const data = await getPositionPageApi(params);
const list = data.records || [];
allPositionOptions.value = list.map((item: PositionVO.PositionInfoVO) => ({
departmentId: item.departmentId,
label: item.name,
value: item.id,
}));
} catch (error) {
console.error('获取职位列表失败:', error);
message.error('获取职位列表失败');
allPositionOptions.value = [];
} finally {
positionOptionsLoading.value = false;
}
}
async function ensureSelectorOptionsLoaded() {
if (selectorsLoaded.value) return;
await Promise.all([loadDepartmentOptions(), loadPositionOptions()]);
selectorsLoaded.value = true;
}
function syncDepartmentPathByDepartmentId() {
if (!formData.value.departmentId) {
departmentPath.value = [];
return;
}
const path = findDepartmentPathById(
departmentTreeOptions.value,
formData.value.departmentId,
);
departmentPath.value = path || [];
}
function handleDepartmentChange(value: number[]) {
departmentPath.value = value || [];
const selectedDepartmentId = departmentPath.value.at(-1) || 0;
const previousDepartmentId = formData.value.departmentId;
formData.value.departmentId = selectedDepartmentId;
if (
previousDepartmentId !== selectedDepartmentId &&
formData.value.positionId &&
!positionOptions.value.some(
(item) => item.value === formData.value.positionId,
)
) {
formData.value.positionId = undefined;
}
}
async function open(accountData?: AccountVO.AccountInfoVO | null) {
await ensureSelectorOptionsLoaded();
isEdit.value = !!accountData;
currentAccountData.value = accountData || null;
resetForm();
if (accountData) {
formData.value = {
password: '', // 编辑时密码为空
phone: accountData.phone || '',
realName: accountData.realName,
departmentId: accountData.departmentId,
positionId: accountData.positionId || undefined,
remark: accountData.remark || '',
status: accountData.status,
};
}
syncDepartmentPathByDepartmentId();
modalApi.open();
}
// 处理表单提交
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
if (isEdit.value && currentAccountData.value) {
const { password: _, ...updateData } = formData.value;
await admin_updateAccountApi(currentAccountData.value.id, updateData);
message.success('更新成功');
} else {
await admin_createAccountApi(formData.value);
message.success('创建成功');
}
emit('success');
modalApi.close();
} catch (error: any) {
console.error('保存账户失败:', error);
const errorMessage =
error?.response?.data?.message || error?.message || '保存账户失败';
message.error(errorMessage);
} finally {
loading.value = false;
}
}
// 监听 modal 关闭状态
watch(
() => modalApi.useStore()?.value?.isOpen,
(newVal) => {
if (!newVal) {
resetForm();
}
},
);
watch(
() => formData.value.departmentId,
() => {
if (
formData.value.positionId &&
!positionOptions.value.some(
(item) => item.value === formData.value.positionId,
)
) {
formData.value.positionId = undefined;
}
},
);
// 暴露方法给父组件
defineExpose({
open,
});
</script>
<template>
<Modal :title="modalTitle" :confirm-loading="loading">
<Form
ref="formRef"
:model="formData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item
label="手机号"
name="phone"
:rules="[
{ required: true, message: '请输入手机号' },
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
]"
>
<Input v-model:value="formData.phone" placeholder="请输入手机号" />
</Form.Item>
<Form.Item
v-if="!isEdit"
label="密码"
name="password"
:rules="[
{ min: 6, max: 20, message: '密码长度为6-20个字符' },
]"
>
<Input
v-model:value="formData.password"
type="password"
placeholder="新用户必填;手机号已存在可留空"
/>
</Form.Item>
<Form.Item
label="真实姓名"
name="realName"
:rules="[{ required: true, message: '请输入真实姓名' }]"
>
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
</Form.Item>
<Form.Item
label="所属部门"
name="departmentId"
:rules="[{ required: true, message: '请选择所属部门' }]"
>
<Cascader
:value="departmentPath"
:options="departmentTreeOptions"
:loading="departmentOptionsLoading"
placeholder="请选择所属部门"
:field-names="{
label: 'label',
value: 'value',
children: 'children',
}"
change-on-select
class="w-full"
@change="(value) => handleDepartmentChange((value || []) as number[])"
/>
</Form.Item>
<Form.Item
label="职位"
name="positionId"
:rules="[{ required: true, message: '请选择职位' }]"
>
<Select
v-model:value="formData.positionId"
:loading="positionOptionsLoading"
:options="positionOptions"
placeholder="请选择职位"
:disabled="positionOptionsLoading"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input v-model:value="formData.remark" placeholder="请输入备注" />
</Form.Item>
<Form.Item v-if="isEdit" label="状态" name="status">
<Select
v-model:value="formData.status"
placeholder="请选择状态"
:options="statusOptions"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,367 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { AccountDTO, AccountVO } from '#/api/organization/account';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
admin_deleteAccountApi,
admin_getAccountPageApi,
} from '#/api/organization/account';
import AccountFormModal from './components/AccountFormModal.vue';
defineOptions({ name: 'CompanyAccountManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据
const loading = ref(false);
const accountFormModalRef = ref();
// 搜索表单
const searchForm = ref({
loginCode: undefined as string | undefined,
realName: undefined as string | undefined,
phone: undefined as string | undefined,
companyId: undefined as number | undefined,
departmentId: undefined as number | undefined,
positionId: undefined as number | undefined,
role: undefined as string | undefined,
status: undefined as number | undefined,
});
// 状态选项
const statusOptions = [
{ label: '正常', value: 0 },
{ label: '删除', value: 1 },
{ label: '停用', value: 2 },
{ label: '冻结', value: 3 },
];
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schemas: [
{
fieldName: 'loginCode',
label: '登录账号',
component: 'Input',
componentProps: {
placeholder: '请输入登录账号(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
},
{
fieldName: 'realName',
label: '真实姓名',
component: 'Input',
componentProps: {
placeholder: '请输入真实姓名(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
},
{
fieldName: 'phone',
label: '手机号',
component: 'Input',
componentProps: {
placeholder: '请输入手机号(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
options: statusOptions,
placeholder: '请选择状态',
onChange: () => gridReloadRef.value?.(),
},
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
field: 'loginCode',
title: '登录账号',
minWidth: 120,
},
{
field: 'realName',
title: '真实姓名',
minWidth: 120,
},
{
field: 'phone',
title: '手机号',
minWidth: 120,
},
{
field: 'companyName',
title: '公司',
minWidth: 150,
},
{
field: 'departmentName',
title: '部门',
minWidth: 120,
},
{
field: 'positionName',
title: '职位',
minWidth: 120,
},
{
field: 'role',
title: '角色',
minWidth: 100,
},
{
field: 'status',
title: '状态',
minWidth: 80,
slots: { default: 'status' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
title: '操作',
width: 120,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<AccountDTO.AccountFilterDTO> = {
page: page.currentPage,
pageSize: page.pageSize,
...searchForm.value,
};
const response = await admin_getAccountPageApi(params);
return {
items: response.records,
total: response.total,
};
} catch (error: any) {
console.error('查询数据失败:', error);
const errorMessage =
error?.response?.data?.message || error?.message || '查询数据失败';
message.error(errorMessage);
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 表格实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '账户管理',
});
gridReloadRef.value = () => gridApi.reload();
// 计算属性
const hasSelected = computed(() => {
const vxeTable = (gridApi as any).grid;
return vxeTable?.getCheckboxRecords?.()?.length > 0;
});
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
}
}
const handleAdd = () => {
accountFormModalRef.value?.open();
};
const handleEdit = (row: AccountVO.AccountInfoVO) => {
accountFormModalRef.value?.open(row);
};
const handleDelete = async (row: AccountVO.AccountInfoVO) => {
try {
await admin_deleteAccountApi(row.id);
message.success('删除成功');
refreshTable();
} catch (error: any) {
console.error('删除失败:', error);
const errorMessage =
error?.response?.data?.message || error?.message || '删除失败';
message.error(errorMessage);
}
};
const handleBatchDelete = async () => {
const vxeTable = (gridApi as any).grid;
const selectedRows = vxeTable?.getCheckboxRecords?.();
if (!selectedRows?.length) {
message.warning('请选择要删除的数据');
return;
}
try {
const deletePromises = selectedRows.map((row: AccountVO.AccountInfoVO) =>
admin_deleteAccountApi(row.id),
);
await Promise.all(deletePromises);
message.success(`成功删除 ${selectedRows.length} 条记录`);
refreshTable();
} catch (error: any) {
console.error('批量删除失败:', error);
const errorMessage =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(errorMessage);
}
};
// 获取状态文本
const getStatusText = (status: number) => {
const statusMap = {
0: '正常',
1: '删除',
2: '停用',
3: '冻结',
};
return statusMap[status as keyof typeof statusMap] || '未知';
};
// 获取状态颜色
const getStatusColor = (status: number) => {
const colorMap = {
0: 'green',
1: 'red',
2: 'orange',
3: 'purple',
};
return colorMap[status as keyof typeof colorMap] || 'default';
};
// 处理模态框成功回调
function handleModalSuccess() {
refreshTable();
}
</script>
<template>
<Page title="账户管理" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理公司账户信息,支持账户的增删改查操作
</div>
</template>
<!-- VbenVxeGrid 表格 -->
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加账户
</Button>
<Button v-if="hasSelected" danger @click="handleBatchDelete">
批量删除
</Button>
</Space>
</template>
<!-- 状态列 -->
<template #status="{ row }">
<Tag :color="getStatusColor(row.status)">
{{ getStatusText(row.status) }}
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Popconfirm
title="确定要删除这个账户吗?"
@confirm="handleDelete(row)"
>
<Button size="small" danger> 删除 </Button>
</Popconfirm>
</Space>
</template>
</Grid>
<!-- 账户表单弹窗 -->
<AccountFormModal ref="accountFormModalRef" @success="handleModalSuccess" />
</Page>
</template>