prettier: 代码格式化

This commit is contained in:
ah--desktop
2025-10-31 22:42:03 +08:00
parent 91ee49f45f
commit dfc6de49e0
62 changed files with 6814 additions and 5256 deletions
@@ -1,6 +1,7 @@
import { baseRequestClient, requestClient } from '#/api/request';
import { useAccessStore } from '@vben/stores';
import { baseRequestClient, requestClient } from '#/api/request';
export namespace AuthApi {
/** 登录接口参数 */
export interface LoginParams {
@@ -73,16 +74,20 @@ export async function loginApi(data: AuthApi.LoginParams) {
*/
export async function refreshTokenApi() {
const accessStore = useAccessStore();
if (!accessStore.refreshToken) {
throw new Error('RefreshToken不存在,无法刷新token');
}
return baseRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
refreshToken: accessStore.refreshToken,
}, {
withCredentials: true,
});
return baseRequestClient.post<AuthApi.RefreshTokenResult>(
'/auth/refresh',
{
refreshToken: accessStore.refreshToken,
},
{
withCredentials: true,
},
);
}
/**
@@ -1,7 +1,7 @@
import { requestClient } from '#/api/request';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
export namespace CompanyApi {
/** 公司信息 */
export interface CompanyInfo {
@@ -135,52 +135,92 @@ export namespace PositionApi {
}
// 公司管理API
export async function getCompanyPageApi(params: PageQueryDTO<CompanyApi.CompanyFilter>) {
return requestClient.post<PageResultVO<CompanyApi.CompanyInfo>>('/company/page', params);
export async function getCompanyPageApi(
params: PageQueryDTO<CompanyApi.CompanyFilter>,
) {
return requestClient.post<PageResultVO<CompanyApi.CompanyInfo>>(
'/company/page',
params,
);
}
export async function createCompanyApi(data: CompanyApi.CreateCompanyParams) {
return requestClient.post<CompanyApi.CompanyInfo>('/company/create', data);
}
export async function updateCompanyApi(id: number, data: CompanyApi.UpdateCompanyParams) {
return requestClient.put<CompanyApi.CompanyInfo>(`/company/update/${id}`, data);
export async function updateCompanyApi(
id: number,
data: CompanyApi.UpdateCompanyParams,
) {
return requestClient.put<CompanyApi.CompanyInfo>(
`/company/update/${id}`,
data,
);
}
export async function deleteCompanyApi(id: number) {
return requestClient.delete<void>(`/company/delete/${id}`);
return requestClient.delete(`/company/delete/${id}`);
}
// 部门管理API
export async function getDepartmentPageApi(params: PageQueryDTO<DepartmentApi.DepartmentFilter>) {
return requestClient.post<PageResultVO<DepartmentApi.DepartmentInfo>>('/department/page', params);
export async function getDepartmentPageApi(
params: PageQueryDTO<DepartmentApi.DepartmentFilter>,
) {
return requestClient.post<PageResultVO<DepartmentApi.DepartmentInfo>>(
'/department/page',
params,
);
}
export async function createDepartmentApi(data: DepartmentApi.CreateDepartmentParams) {
return requestClient.post<DepartmentApi.DepartmentInfo>('/department/create', data);
export async function createDepartmentApi(
data: DepartmentApi.CreateDepartmentParams,
) {
return requestClient.post<DepartmentApi.DepartmentInfo>(
'/department/create',
data,
);
}
export async function updateDepartmentApi(id: number, data: DepartmentApi.UpdateDepartmentParams) {
return requestClient.put<DepartmentApi.DepartmentInfo>(`/department/update/${id}`, data);
export async function updateDepartmentApi(
id: number,
data: DepartmentApi.UpdateDepartmentParams,
) {
return requestClient.put<DepartmentApi.DepartmentInfo>(
`/department/update/${id}`,
data,
);
}
export async function deleteDepartmentApi(id: number) {
return requestClient.delete<void>(`/department/delete/${id}`);
return requestClient.delete(`/department/delete/${id}`);
}
// 岗位管理API
export async function getPositionPageApi(params: PageQueryDTO<PositionApi.PositionFilter>) {
return requestClient.post<PageResultVO<PositionApi.PositionInfo>>('/position/page', params);
export async function getPositionPageApi(
params: PageQueryDTO<PositionApi.PositionFilter>,
) {
return requestClient.post<PageResultVO<PositionApi.PositionInfo>>(
'/position/page',
params,
);
}
export async function createPositionApi(data: PositionApi.CreatePositionParams) {
export async function createPositionApi(
data: PositionApi.CreatePositionParams,
) {
return requestClient.post<PositionApi.PositionInfo>('/position/create', data);
}
export async function updatePositionApi(id: number, data: PositionApi.UpdatePositionParams) {
return requestClient.put<PositionApi.PositionInfo>(`/position/update/${id}`, data);
export async function updatePositionApi(
id: number,
data: PositionApi.UpdatePositionParams,
) {
return requestClient.put<PositionApi.PositionInfo>(
`/position/update/${id}`,
data,
);
}
export async function deletePositionApi(id: number) {
return requestClient.delete<void>(`/position/delete/${id}`);
return requestClient.delete(`/position/delete/${id}`);
}
@@ -1,5 +1,4 @@
import type { UserInfo } from '@vben/types';
import type { RouteRecordStringComponent } from '@vben/types';
import type { RouteRecordStringComponent, UserInfo } from '@vben/types';
import { requestClient } from '#/api/request';
@@ -2,11 +2,11 @@
* 电商模块API导出
*/
// 订单相关API
export * from './order.apis';
// 订单状态相关API
export * from './order-status.apis';
// 订单相关API
export * from './order.apis';
// 推广费类型相关API
export * from './promotion-fee-type.apis';
@@ -1,7 +1,7 @@
import { requestClient } from '#/api/request';
import type { OrderStatusDTO, OrderStatusVO } from './types';
import { requestClient } from '#/api/request';
/**
* 订单状态管理API
*/
@@ -17,14 +17,14 @@ export async function createOrderStatusApi(data: OrderStatusDTO.Create) {
* 更新订单状态
*/
export async function updateOrderStatusApi(data: OrderStatusDTO.Update) {
return requestClient.put<void>('/ec/order-status', data);
return requestClient.put('/ec/order-status', data);
}
/**
* 删除订单状态
*/
export async function deleteOrderStatusApi(id: number) {
return requestClient.delete<void>(`/ec/order-status/${id}`);
return requestClient.delete(`/ec/order-status/${id}`);
}
/**
@@ -1,7 +1,8 @@
import { requestClient } from '#/api/request';
import type { BatchImportResultVO, OrderDTO, OrderVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import type { OrderDTO, OrderVO, BatchImportResultVO } from './types';
import { requestClient } from '#/api/request';
/**
* 订单管理API
@@ -11,7 +12,10 @@ import type { OrderDTO, OrderVO, BatchImportResultVO } from './types';
* 分页获取订单列表
*/
export async function getOrderPageApi(params: PageQueryDTO<OrderDTO.Filters>) {
return requestClient.post<PageResultVO<OrderVO.Info>>('/ec/order/page', params);
return requestClient.post<PageResultVO<OrderVO.Info>>(
'/ec/order/page',
params,
);
}
/**
@@ -32,7 +36,7 @@ export async function updateOrderApi(id: number, data: OrderDTO.Update) {
* 删除订单
*/
export async function deleteOrderApi(id: number) {
return requestClient.delete<void>(`/ec/order/delete/${id}`);
return requestClient.delete(`/ec/order/delete/${id}`);
}
/**
@@ -46,5 +50,8 @@ export async function getOrderByIdApi(id: number) {
* 批量导入订单
*/
export async function batchImportOrdersApi(data: OrderDTO.BatchImport) {
return requestClient.post<BatchImportResultVO.Info>('/ec/order/batch-import', data);
return requestClient.post<BatchImportResultVO.Info>(
'/ec/order/batch-import',
data,
);
}
@@ -1,7 +1,7 @@
import { requestClient } from '#/api/request';
import type { PromotionFeeTypeDTO, PromotionFeeTypeVO } from './types';
import { requestClient } from '#/api/request';
/**
* 推广费类型管理API
*/
@@ -9,41 +9,51 @@ import type { PromotionFeeTypeDTO, PromotionFeeTypeVO } from './types';
/**
* 创建推广费类型
*/
export async function createPromotionFeeTypeApi(data: PromotionFeeTypeDTO.Create) {
export async function createPromotionFeeTypeApi(
data: PromotionFeeTypeDTO.Create,
) {
return requestClient.post<number>('/ec/promotion-fee-type', data);
}
/**
* 更新推广费类型
*/
export async function updatePromotionFeeTypeApi(data: PromotionFeeTypeDTO.Update) {
return requestClient.put<void>('/ec/promotion-fee-type', data);
export async function updatePromotionFeeTypeApi(
data: PromotionFeeTypeDTO.Update,
) {
return requestClient.put('/ec/promotion-fee-type', data);
}
/**
* 删除推广费类型
*/
export async function deletePromotionFeeTypeApi(id: number) {
return requestClient.delete<void>(`/ec/promotion-fee-type/${id}`);
return requestClient.delete(`/ec/promotion-fee-type/${id}`);
}
/**
* 获取推广费类型详情
*/
export async function getPromotionFeeTypeByIdApi(id: number) {
return requestClient.get<PromotionFeeTypeVO.Info>(`/ec/promotion-fee-type/${id}`);
return requestClient.get<PromotionFeeTypeVO.Info>(
`/ec/promotion-fee-type/${id}`,
);
}
/**
* 获取启用的推广费类型列表
*/
export async function getActivePromotionFeeTypeListApi() {
return requestClient.get<PromotionFeeTypeVO.Info[]>('/ec/promotion-fee-type/active');
return requestClient.get<PromotionFeeTypeVO.Info[]>(
'/ec/promotion-fee-type/active',
);
}
/**
* 获取所有推广费类型列表
*/
export async function getAllPromotionFeeTypeListApi() {
return requestClient.get<PromotionFeeTypeVO.Info[]>('/ec/promotion-fee-type/all');
return requestClient.get<PromotionFeeTypeVO.Info[]>(
'/ec/promotion-fee-type/all',
);
}
@@ -7,8 +7,8 @@ export * from './dto.order';
export * from './dto.order-status';
export * from './dto.promotion-fee-type';
export * from './vo.batch-import-result';
// VO类型导出
export * from './vo.order';
export * from './vo.order-status';
export * from './vo.promotion-fee-type';
export * from './vo.batch-import-result';
@@ -1,56 +1,63 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useVbenDrawer } from '@vben/common-ui'
import { Button, message, Select, Spin, Tree } from 'ant-design-vue'
import { getAllMenusApi } from '#/api/system/menu'
import { getCompanyMenuIdsApi, batchUpdateCompanyMenusApi } from '#/api/organization/company-menu'
import type { MenuVO } from '#/api/system/menu/types'
import type { MenuVO } from '#/api/system/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/organization/company-menu';
import { getAllMenusApi } from '#/api/system/menu';
interface Props {
company?: any
company?: any;
}
interface Emits {
(e: 'success'): void
(e: 'close'): void
(e: 'success'): void;
(e: 'close'): void;
}
defineOptions({
name: 'CompanyMenuDrawer',
})
});
defineProps<Props>()
const emit = defineEmits<Emits>()
defineProps<Props>();
const emit = defineEmits<Emits>();
// 系统菜单列表数据
const systemMenuList = ref<MenuVO.MenuInfo[]>([])
const systemMenuList = ref<MenuVO.MenuInfo[]>([]);
// 公司菜单ID列表
const companyMenuIds = ref<number[]>([])
const companyMenuIds = ref<number[]>([]);
// 加载状态
const loading = ref(false)
const loading = ref(false);
// 保存状态
const saving = ref(false)
const saving = ref(false);
// 当前公司信息
const currentCompany = ref<any>()
const currentCompany = ref<any>();
// 选中的菜单ID
const checkedKeys = ref<number[]>([])
const checkedKeys = ref<number[]>([]);
// 展开的节点键
const expandedKeys = ref<number[]>([])
const expandedKeys = ref<number[]>([]);
// 分组选择
const selectedGroup = ref<'super' | 'normal' | undefined>(undefined)
const selectedGroup = ref<'normal' | 'super' | undefined>(undefined);
// 分组选项
const groupOptions = [
{ label: '超管菜单', value: 'super' as const },
{ label: '普通菜单', value: 'normal' as const },
]
];
// 创建抽屉组件
const [MainDrawer, mainDrawerApi] = useVbenDrawer({
@@ -61,20 +68,20 @@ const [MainDrawer, mainDrawerApi] = useVbenDrawer({
confirmText: '保存权限配置',
cancelText: '取消',
onConfirm: async () => {
await handleSave()
await handleSave();
},
onCancel() {
handleClose()
handleClose();
},
onClosed() {
emit('close')
emit('close');
},
})
});
// 将菜单列表转换为树形结构
const menuTreeData = computed(() => {
const menuMap = new Map<number, any>()
const rootMenus: any[] = []
const menuMap = new Map<number, any>();
const rootMenus: any[] = [];
// 先创建所有节点
systemMenuList.value.forEach((menu) => {
@@ -86,97 +93,99 @@ const menuTreeData = computed(() => {
status: menu.status,
disabled: menu.status === 0, // 禁用状态的菜单不可选择
children: [],
})
})
});
});
// 构建树形结构
systemMenuList.value.forEach((menu) => {
const node = menuMap.get(menu.id)!
const node = menuMap.get(menu.id)!;
if (menu.parentId && menuMap.has(menu.parentId)) {
const parent = menuMap.get(menu.parentId)!
parent.children.push(node)
const parent = menuMap.get(menu.parentId)!;
parent.children.push(node);
} else {
rootMenus.push(node)
rootMenus.push(node);
}
})
});
return rootMenus
})
return rootMenus;
});
// 统计信息
const stats = computed(() => {
const totalMenus = systemMenuList.value.length
const companyMenus = companyMenuIds.value.length
const selectedMenus = calculateCorrectSelectedCount(checkedKeys.value)
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
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 menu = systemMenuList.value.find((m) => m.id === menuId);
if (!menu) return false;
// 检查是否有其他菜单将此菜单作为父菜单
const hasChildren = systemMenuList.value.some((otherMenu) => otherMenu.parentId === menuId)
const hasChildren = systemMenuList.value.some(
(otherMenu) => otherMenu.parentId === menuId,
);
// 只保留叶子节点(没有子节点的菜单)
return !hasChildren
})
return !hasChildren;
});
}
// 加载数据
async function loadData() {
if (!currentCompany.value?.id) return
loading.value = true
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
]);
systemMenuList.value = systemData;
companyMenuIds.value = companyData;
// 清理根节点,只保留叶子节点
const leafMenuIds = cleanRootNodes(companyData)
checkedKeys.value = leafMenuIds
const leafMenuIds = cleanRootNodes(companyData);
checkedKeys.value = leafMenuIds;
// 自动展开所有节点
expandedKeys.value = systemData.map((menu) => menu.id)
expandedKeys.value = systemData.map((menu) => menu.id);
} catch (error: any) {
message.error(error?.message || '加载数据失败')
message.error(error?.message || '加载数据失败');
} finally {
loading.value = false
loading.value = false;
}
}
// 保存所有更改
async function handleSave() {
if (!currentCompany.value?.id) return
saving.value = true
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()
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 // 重新抛出错误,让抽屉知道保存失败
message.error(error?.message || '保存失败');
throw error; // 重新抛出错误,让抽屉知道保存失败
} finally {
saving.value = false
saving.value = false;
}
}
@@ -185,41 +194,46 @@ 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)
selectableMenus = selectableMenus.filter((menu) => menu.superMenu === 1);
} else if (selectedGroup.value === 'normal') {
selectableMenus = selectableMenus.filter((menu) => menu.superMenu !== 1)
selectableMenus = selectableMenus.filter((menu) => menu.superMenu !== 1);
}
}
// 只选择叶子节点(没有子节点的菜单)
const leafMenus = selectableMenus.filter((menu) => {
// 检查是否有其他菜单将此菜单作为父菜单
const hasChildren = systemMenuList.value.some((otherMenu) => otherMenu.parentId === menu.id)
return !hasChildren
})
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
const menu = systemMenuList.value.find((m) => m.id === id);
if (!menu) return false;
if (selectedGroup.value === 'super') {
return menu.superMenu !== 1
return menu.superMenu !== 1;
} else if (selectedGroup.value === 'normal') {
return menu.superMenu === 1
return menu.superMenu === 1;
}
return false
})
checkedKeys.value = [...otherGroupCheckedKeys, ...leafMenus.map((menu) => menu.id)]
return false;
});
checkedKeys.value = [
...otherGroupCheckedKeys,
...leafMenus.map((menu) => menu.id),
];
} else {
// 如果没有选择分组,全选所有叶子节点
checkedKeys.value = leafMenus.map((menu) => menu.id)
checkedKeys.value = leafMenus.map((menu) => menu.id);
}
}
@@ -227,87 +241,96 @@ function handleSelectAll() {
function handleSelectNone() {
if (selectedGroup.value) {
// 如果选择了分组,只取消该分组的叶子节点选中状态
const leafMenuIds = 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.includes(id))
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 = systemMenuList.value
.filter((menu) => {
// 只处理叶子节点
return !systemMenuList.value.some((otherMenu) => otherMenu.parentId === menu.id)
})
.map((menu) => menu.id)
checkedKeys.value = checkedKeys.value.filter((id) => !allLeafMenuIds.includes(id))
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(checkedKeysValue: any) {
checkedKeys.value = checkedKeysValue
checkedKeys.value = checkedKeysValue;
}
// 确保提交时包含必要的父菜单ID(递归添加所有层级的父菜单)
function ensureParentMenuIds(menuIds: number[]): number[] {
const result = new Set(menuIds)
const result = new Set(menuIds);
// 递归添加所有父菜单ID
function addAllParentIds(menuId: number) {
const menu = systemMenuList.value.find((m) => m.id === menuId)
const menu = systemMenuList.value.find((m) => m.id === menuId);
if (menu && menu.parentId) {
result.add(menu.parentId)
result.add(menu.parentId);
// 递归添加父菜单的父菜单
addAllParentIds(menu.parentId)
addAllParentIds(menu.parentId);
}
}
// 为每个选中的菜单添加其所有父菜单ID
menuIds.forEach((menuId) => {
addAllParentIds(menuId)
})
const finalResult = [...result]
return finalResult
}
addAllParentIds(menuId);
});
const finalResult = [...result];
return finalResult;
}
// 关闭抽屉
function handleClose() {
mainDrawerApi.close()
checkedKeys.value = []
expandedKeys.value = []
selectedGroup.value = undefined
mainDrawerApi.close();
checkedKeys.value = [];
expandedKeys.value = [];
selectedGroup.value = undefined;
}
// 暴露打开方法
defineExpose({
open: (company: any) => {
// 设置公司信息
currentCompany.value = company
currentCompany.value = company;
// 打开抽屉
mainDrawerApi.open()
mainDrawerApi.open();
// 加载数据
if (company?.id) {
loadData()
loadData();
}
},
close: () => mainDrawerApi.close(),
})
});
</script>
<template>
@@ -349,12 +372,8 @@ defineExpose({
{{ option.label }}
</Select.Option>
</Select>
<Button type="primary" @click="handleSelectAll">
一键全选
</Button>
<Button @click="handleSelectNone">
取消全选
</Button>
<Button type="primary" @click="handleSelectAll"> 一键全选 </Button>
<Button @click="handleSelectNone"> 取消全选 </Button>
</div>
</div>
</div>
@@ -1,283 +1,286 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Form, Select, Card, Avatar, message, Spin } from 'ant-design-vue'
import { useVbenModal } from '@vben/common-ui'
import { useAccessStore } from '@vben/stores'
import { switchAccountApi } from '#/api/core/auth'
import { getCompanyPageApi } from '#/api/organization/company'
import { getUserPageApi } from '#/api/system/user'
import type { CompanyVO } from '#/api/organization/company/types'
import type { UserVO } from '#/api/system/user/types'
import type { PageQueryDTO } from '#/types/common'
import type { CompanyVO } from '#/api/organization/company/types';
import type { UserVO } from '#/api/system/user/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useAccessStore } from '@vben/stores';
import { Avatar, Card, Form, message, Select, Spin } from 'ant-design-vue';
import { switchAccountApi } from '#/api/core/auth';
import { getCompanyPageApi } from '#/api/organization/company';
import { getUserPageApi } from '#/api/system/user';
// 响应式数据
const formRef = ref()
const formRef = ref();
const formData = ref({
companyId: undefined as number | undefined,
userId: undefined as number | undefined,
})
});
// 公司相关数据
const companyList = ref<CompanyVO.CompanyInfoVO[]>([])
const companyLoading = ref(false)
const companySearchValue = ref('')
const companyPage = ref(1)
const companyPageSize = ref(20)
const companyHasMore = ref(true)
const companyList = ref<CompanyVO.CompanyInfoVO[]>([]);
const companyLoading = ref(false);
const companySearchValue = ref('');
const companyPage = ref(1);
const companyPageSize = ref(20);
const companyHasMore = ref(true);
// 用户相关数据
const userList = ref<UserVO.UserInfoVO[]>([])
const userLoading = ref(false)
const userSearchValue = ref('')
const userPage = ref(1)
const userPageSize = ref(20)
const userHasMore = ref(true)
const userList = ref<UserVO.UserInfoVO[]>([]);
const userLoading = ref(false);
const userSearchValue = ref('');
const userPage = ref(1);
const userPageSize = ref(20);
const userHasMore = ref(true);
// 选中的用户信息
const selectedUser = ref<UserVO.UserInfoVO | null>(null)
const selectedUser = ref<null | UserVO.UserInfoVO>(null);
// 公司选项
const companyOptions = computed(() =>
companyList.value.map(company => ({
const companyOptions = computed(() =>
companyList.value.map((company) => ({
label: company.name,
value: company.id,
company
}))
)
company,
})),
);
// 用户选项
const userOptions = computed(() =>
userList.value.map(user => ({
const userOptions = computed(() =>
userList.value.map((user) => ({
label: `${user.realName} (${user.loginCode})`,
value: user.id,
user
}))
)
user,
})),
);
// 监听公司选择变化
watch(() => formData.value.companyId, (newCompanyId) => {
if (newCompanyId) {
// 重置用户数据
formData.value.userId = undefined
userList.value = []
userPage.value = 1
userHasMore.value = true
selectedUser.value = null
// 加载该公司的用户
loadUsers()
}
})
watch(
() => formData.value.companyId,
(newCompanyId) => {
if (newCompanyId) {
// 重置用户数据
formData.value.userId = undefined;
userList.value = [];
userPage.value = 1;
userHasMore.value = true;
selectedUser.value = null;
// 加载该公司的用户
loadUsers();
}
},
);
// 监听用户选择变化
watch(() => formData.value.userId, (newUserId) => {
if (newUserId) {
const user = userList.value.find(u => u.id === newUserId)
selectedUser.value = user || null
} else {
selectedUser.value = null
}
})
watch(
() => formData.value.userId,
(newUserId) => {
if (newUserId) {
const user = userList.value.find((u) => u.id === newUserId);
selectedUser.value = user || null;
} else {
selectedUser.value = null;
}
},
);
// 加载公司列表
const loadCompanies = async (reset = false) => {
if (companyLoading.value) return
if (companyLoading.value) return;
try {
companyLoading.value = true
companyLoading.value = true;
if (reset) {
companyList.value = []
companyPage.value = 1
companyHasMore.value = true
companyList.value = [];
companyPage.value = 1;
companyHasMore.value = true;
}
const params: PageQueryDTO<{ name?: string }> = {
page: companyPage.value,
pageSize: companyPageSize.value,
filters: {
name: companySearchValue.value || undefined,
}
}
const result = await getCompanyPageApi(params)
},
};
const result = await getCompanyPageApi(params);
if (reset) {
companyList.value = result.records
companyList.value = result.records;
} else {
companyList.value.push(...result.records)
companyList.value.push(...result.records);
}
companyHasMore.value = result.records.length === companyPageSize.value
companyPage.value++
companyHasMore.value = result.records.length === companyPageSize.value;
companyPage.value++;
} catch (error) {
console.error('加载公司列表失败:', error)
message.error('加载公司列表失败')
console.error('加载公司列表失败:', error);
message.error('加载公司列表失败');
} finally {
companyLoading.value = false
companyLoading.value = false;
}
}
};
// 加载用户列表
const loadUsers = async (reset = false) => {
if (userLoading.value || !formData.value.companyId) return
if (userLoading.value || !formData.value.companyId) return;
try {
userLoading.value = true
userLoading.value = true;
if (reset) {
userList.value = []
userPage.value = 1
userHasMore.value = true
userList.value = [];
userPage.value = 1;
userHasMore.value = true;
}
const params: PageQueryDTO<{ realName?: string; loginCode?: string; companyId?: number }> = {
const params: PageQueryDTO<{
companyId?: number;
loginCode?: string;
realName?: string;
}> = {
page: userPage.value,
pageSize: userPageSize.value,
filters: {
realName: userSearchValue.value || undefined,
loginCode: userSearchValue.value || undefined,
companyId: formData.value.companyId,
}
}
const result = await getUserPageApi(params)
},
};
const result = await getUserPageApi(params);
if (reset) {
userList.value = result.records
userList.value = result.records;
} else {
userList.value.push(...result.records)
userList.value.push(...result.records);
}
userHasMore.value = result.records.length === userPageSize.value
userPage.value++
userHasMore.value = result.records.length === userPageSize.value;
userPage.value++;
} catch (error) {
console.error('加载用户列表失败:', error)
message.error('加载用户列表失败')
console.error('加载用户列表失败:', error);
message.error('加载用户列表失败');
} finally {
userLoading.value = false
userLoading.value = false;
}
}
};
// 公司搜索
const handleCompanySearch = (value: string) => {
companySearchValue.value = value
loadCompanies(true)
}
companySearchValue.value = value;
loadCompanies(true);
};
// 用户搜索
const handleUserSearch = (value: string) => {
userSearchValue.value = value
loadUsers(true)
}
userSearchValue.value = value;
loadUsers(true);
};
// 公司下拉框滚动加载更多
const handleCompanyScroll = (e: any) => {
const { target } = e
if (target.scrollTop + target.offsetHeight === target.scrollHeight && companyHasMore.value) {
loadCompanies()
const { target } = e;
if (
target.scrollTop + target.offsetHeight === target.scrollHeight &&
companyHasMore.value
) {
loadCompanies();
}
}
};
// 用户下拉框滚动加载更多
const handleUserScroll = (e: any) => {
const { target } = e
if (target.scrollTop + target.offsetHeight === target.scrollHeight && userHasMore.value) {
loadUsers()
const { target } = e;
if (
target.scrollTop + target.offsetHeight === target.scrollHeight &&
userHasMore.value
) {
loadUsers();
}
}
};
// 切换账户
const handleSwitchAccount = async () => {
console.log('🔄 切换账户函数被调用', { userId: formData.value.userId })
if (!formData.value.userId) {
message.warning('请选择要切换的用户')
return
message.warning('请选择要切换的用户');
return;
}
try {
modalApi.setState({ loading: true })
console.log('📡 开始调用切换账户接口...')
const result = await switchAccountApi(formData.value.userId)
console.log('✅ 切换账户接口调用成功', result)
modalApi.setState({ loading: true });
const result = await switchAccountApi(formData.value.userId);
// 设置新的token
const accessStore = useAccessStore()
const accessStore = useAccessStore();
accessStore.setTokens(
result.accessToken,
result.refreshToken,
result.accessTokenExpiresAt,
result.refreshTokenExpiresAt
)
result.refreshTokenExpiresAt,
);
// 重置权限检查状态,让路由守卫重新生成菜单和路由
accessStore.setIsAccessChecked(false)
message.success('切换账户成功')
modalApi.close()
accessStore.setIsAccessChecked(false);
message.success('切换账户成功');
modalApi.close();
// 刷新页面
window.location.reload()
window.location.reload();
} catch (error: any) {
console.error('切换账户失败:', error)
message.error(error?.message || '切换账户失败')
console.error('切换账户失败:', error);
message.error(error?.message || '切换账户失败');
} finally {
modalApi.setState({ loading: false })
modalApi.setState({ loading: false });
}
}
};
// 创建模态框
const [ModalComponent, modalApi] = useVbenModal({
onCancel() {
console.log('❌ 模态框取消按钮被点击')
modalApi.close()
modalApi.close();
},
onConfirm: async () => {
console.log('🎯 模态框确认按钮被点击')
await handleSwitchAccount()
await handleSwitchAccount();
},
})
});
// 打开模态框
function openModal() {
modalApi.open()
modalApi.open();
// 重置表单数据
formData.value = {
companyId: undefined,
userId: undefined,
}
selectedUser.value = null
};
selectedUser.value = null;
// 加载公司列表
loadCompanies(true)
loadCompanies(true);
}
// 关闭模态框
function closeModal() {
modalApi.close()
modalApi.close();
}
// 暴露方法
defineExpose({
open: openModal,
close: closeModal,
})
});
</script>
<template>
<ModalComponent
title="切换账户"
width="800px"
>
<Form
ref="formRef"
:model="formData"
layout="vertical"
class="mt-4"
>
<ModalComponent title="切换账户" width="800px">
<Form ref="formRef" :model="formData" layout="vertical" class="mt-4">
<Form.Item label="选择公司" required>
<Select
v-model:value="formData.companyId"
@@ -289,13 +292,11 @@ defineExpose({
@popup-scroll="handleCompanyScroll"
>
<template #notFoundContent>
<div v-if="companyLoading" class="text-center py-4">
<div v-if="companyLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="text-center py-4 text-gray-400">
暂无数据
</div>
<div v-else class="py-4 text-center text-gray-400">暂无数据</div>
</template>
<Select.Option
v-for="option in companyOptions"
@@ -307,7 +308,7 @@ defineExpose({
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="选择用户" required>
<Select
v-model:value="formData.userId"
@@ -320,16 +321,17 @@ defineExpose({
@popup-scroll="handleUserScroll"
>
<template #notFoundContent>
<div v-if="userLoading" class="text-center py-4">
<div v-if="userLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else-if="!formData.companyId" class="text-center py-4 text-gray-400">
<div
v-else-if="!formData.companyId"
class="py-4 text-center text-gray-400"
>
请先选择公司
</div>
<div v-else class="text-center py-4 text-gray-400">
暂无数据
</div>
<div v-else class="py-4 text-center text-gray-400">暂无数据</div>
</template>
<Select.Option
v-for="option in userOptions"
@@ -342,7 +344,7 @@ defineExpose({
</Select>
</Form.Item>
</Form>
<!-- 用户信息展示 -->
<Card v-if="selectedUser" title="用户信息" class="mt-4">
<div class="flex items-center space-x-4">
@@ -350,11 +352,17 @@ defineExpose({
{{ selectedUser.realName?.charAt(0) }}
</Avatar>
<div class="flex-1">
<div class="font-medium text-lg">{{ selectedUser.realName }}</div>
<div class="text-gray-500">登录账号: {{ selectedUser.loginCode }}</div>
<div class="text-gray-500">手机号码: {{ selectedUser.phone || '-' }}</div>
<div class="text-lg font-medium">{{ selectedUser.realName }}</div>
<div class="text-gray-500">
登录账号: {{ selectedUser.loginCode }}
</div>
<div class="text-gray-500">
手机号码: {{ selectedUser.phone || '-' }}
</div>
<div class="text-gray-500">角色: {{ selectedUser.role }}</div>
<div class="text-gray-500">状态: {{ selectedUser.status === 1 ? '正常' : '禁用' }}</div>
<div class="text-gray-500">
状态: {{ selectedUser.status === 1 ? '正常' : '禁用' }}
</div>
</div>
</div>
</Card>
@@ -17,10 +17,10 @@ import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
import { $t } from '#/locales';
import { useAuthStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
const notifications = ref<NotificationItem[]>([
{
@@ -66,7 +66,7 @@ const switchAccountModalRef = ref();
const menus = computed(() => {
const menuItems = [];
// 只有超级管理员才显示切换账户功能
if (accessStore.userRole === 'super') {
menuItems.push({
@@ -77,7 +77,7 @@ const menus = computed(() => {
text: '切换账户',
});
}
menuItems.push(
{
handler: () => {
@@ -105,9 +105,9 @@ const menus = computed(() => {
},
icon: CircleHelp,
text: $t('ui.widgets.qa'),
}
},
);
return menuItems;
});
@@ -175,7 +175,7 @@ watch(
<LockScreen :avatar @to-login="handleLogout" />
</template>
</BasicLayout>
<!-- 切换账户模态框 -->
<SwitchAccountModal ref="switchAccountModalRef" />
</template>
@@ -1,5 +1,7 @@
import type { Recordable, UserInfo } from '@vben/types';
import type { AuthApi } from '#/api/core/auth';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
@@ -10,9 +12,14 @@ import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi, registerApi } from '#/api';
import {
getAccessCodesApi,
getUserInfoApi,
loginApi,
logoutApi,
registerApi,
} from '#/api';
import { $t } from '#/locales';
import type { AuthApi } from '#/api/core/auth';
export const useAuthStore = defineStore('auth', () => {
const accessStore = useAccessStore();
@@ -39,11 +46,21 @@ export const useAuthStore = defineStore('auth', () => {
account: params.account,
password: params.password,
};
const { accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt } = await loginApi(loginParams);
const {
accessToken,
refreshToken,
accessTokenExpiresAt,
refreshTokenExpiresAt,
} = await loginApi(loginParams);
// 如果成功获取到 token
if (accessToken) {
accessStore.setTokens(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt);
accessStore.setTokens(
accessToken,
refreshToken,
accessTokenExpiresAt,
refreshTokenExpiresAt,
);
// 获取用户信息
userInfo = await fetchUserInfo();
@@ -103,11 +120,21 @@ export const useAuthStore = defineStore('auth', () => {
let userInfo: null | UserInfo = null;
try {
loginLoading.value = true;
const { accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt } = await registerApi(params as any);
const {
accessToken,
refreshToken,
accessTokenExpiresAt,
refreshTokenExpiresAt,
} = await registerApi(params as any);
// 如果成功获取到 token
if (accessToken) {
accessStore.setTokens(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt);
accessStore.setTokens(
accessToken,
refreshToken,
accessTokenExpiresAt,
refreshTokenExpiresAt,
);
// 获取用户信息
userInfo = await fetchUserInfo();
@@ -1,27 +1,27 @@
import Papa from 'papaparse'
import Papa from 'papaparse';
export interface CSVParseResult {
data: any[]
headers: string[]
errors: any[]
data: any[];
headers: string[];
errors: any[];
}
export interface FieldMapping {
csvField: string
standardField: string
customName?: string
csvField: string;
standardField: string;
customName?: string;
}
export interface ExportData {
metadata: {
source: string
totalRecords: number
exportTime: string
fieldMappings: Record<string, string>
customFieldNames: Record<string, string>
shopName?: string
}
data: any[]
customFieldNames: Record<string, string>;
exportTime: string;
fieldMappings: Record<string, string>;
shopName?: string;
source: string;
totalRecords: number;
};
data: any[];
}
/**
@@ -32,19 +32,19 @@ export function parseCSV(file: File): Promise<CSVParseResult> {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
encoding: 'UTF-8',
encoding: 'utf8',
complete: (results) => {
resolve({
data: results.data,
headers: results.meta.fields || [],
errors: results.errors
})
errors: results.errors,
});
},
error: (error) => {
reject(error)
}
})
})
reject(error);
},
});
});
}
/**
@@ -53,20 +53,20 @@ export function parseCSV(file: File): Promise<CSVParseResult> {
export function transformDataWithMapping(
csvData: any[],
fieldMappings: Record<string, string>,
customFieldNames: Record<string, string> = {}
customFieldNames: Record<string, string> = {},
): any[] {
return csvData.map(row => {
const transformedRow: any = {}
return csvData.map((row) => {
const transformedRow: any = {};
Object.entries(fieldMappings).forEach(([csvField, standardField]) => {
if (standardField && row[csvField] !== undefined) {
const fieldName = customFieldNames[csvField] || standardField
transformedRow[fieldName] = row[csvField]
const fieldName = customFieldNames[csvField] || standardField;
transformedRow[fieldName] = row[csvField];
}
})
return transformedRow
})
});
return transformedRow;
});
}
/**
@@ -76,7 +76,7 @@ export function generateExportData(
transformedData: any[],
fieldMappings: Record<string, string>,
customFieldNames: Record<string, string> = {},
shopName?: string
shopName?: string,
): ExportData {
return {
metadata: {
@@ -85,27 +85,27 @@ export function generateExportData(
exportTime: new Date().toISOString(),
fieldMappings,
customFieldNames,
shopName
shopName,
},
data: transformedData
}
data: transformedData,
};
}
/**
* 下载JSON文件
*/
export function downloadJSON(data: ExportData, filename?: string): void {
const jsonString = JSON.stringify(data, null, 2)
const blob = new Blob([jsonString], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename || `ecommerce-data-${new Date().getTime()}.json`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
const jsonString = JSON.stringify(data, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename || `ecommerce-data-${Date.now()}.json`;
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
/**
@@ -113,67 +113,76 @@ export function downloadJSON(data: ExportData, filename?: string): void {
*/
export function extractShopNameFromFilename(filename: string): string {
// 移除文件扩展名
const nameWithoutExt = filename.replace(/\.[^/.]+$/, '')
return nameWithoutExt
const nameWithoutExt = filename.replace(/\.[^/.]+$/, '');
return nameWithoutExt;
}
/**
* 验证CSV数据格式
*/
export function validateCSVData(data: any[]): { isValid: boolean; errors: string[] } {
const errors: string[] = []
export function validateCSVData(data: any[]): {
errors: string[];
isValid: boolean;
} {
const errors: string[] = [];
if (data.length === 0) {
errors.push('CSV文件为空')
errors.push('CSV文件为空');
}
// 检查必要字段
const requiredFields = ['商品', '订单号', '订单状态', '商品数量(件)', '商家实收金额(元)']
const firstRow = data[0]
const requiredFields = [
'商品',
'订单号',
'订单状态',
'商品数量(件)',
'商家实收金额(元)',
];
const firstRow = data[0];
if (firstRow) {
requiredFields.forEach(field => {
requiredFields.forEach((field) => {
if (!(field in firstRow)) {
errors.push(`缺少必要字段: ${field}`)
errors.push(`缺少必要字段: ${field}`);
}
})
});
}
return {
isValid: errors.length === 0,
errors
}
errors,
};
}
/**
* 数据清洗和格式化
*/
export function cleanAndFormatData(data: any[]): any[] {
return data.map(row => {
const cleanedRow: any = {}
return data.map((row) => {
const cleanedRow: any = {};
Object.entries(row).forEach(([key, value]) => {
if (value !== null && value !== undefined) {
// 去除首尾空格
let cleanedValue = String(value).trim()
let cleanedValue = String(value).trim();
// 处理数字字段
if (key.includes('数量') || key.includes('金额')) {
cleanedValue = cleanedValue.replace(/[^\d.-]/g, '')
if (cleanedValue && !isNaN(Number(cleanedValue))) {
cleanedValue = Number(cleanedValue).toString()
cleanedValue = cleanedValue.replaceAll(/[^\d.-]/g, '');
if (cleanedValue && !Number.isNaN(Number(cleanedValue))) {
cleanedValue = Number(cleanedValue).toString();
}
}
// 处理日期字段
if (key.includes('日期') || key.includes('时间')) {
// 这里可以添加日期格式化逻辑
}
cleanedRow[key] = cleanedValue
cleanedRow[key] = cleanedValue;
}
})
return cleanedRow
})
});
return cleanedRow;
});
}
@@ -107,10 +107,10 @@ function handleSubmit(value: Recordable<any>) {
// 这里可以添加错误提示
return;
}
// 移除不需要的字段
const { confirmPassword, agreePolicy, ...registerData } = value;
const { ...registerData } = value;
authStore.authRegister(registerData);
}
</script>
@@ -1,21 +1,22 @@
<script setup lang="ts">
import { createIconifyIcon } from '@vben/icons';
import { Card } from 'ant-design-vue';
defineOptions({ name: 'DataAnalysis' });
// 创建图标组件
const BarChartIcon = createIconifyIcon('lucide:bar-chart-3');
</script>
<template>
<div class="p-6">
<Card title="数据分析" class="mb-6">
<div class="text-center py-12">
<BarChartIcon class="w-16 h-16 mx-auto text-gray-400 mb-4" />
<h3 class="text-lg font-medium text-gray-700 mb-2">数据分析功能</h3>
<div class="py-12 text-center">
<BarChartIcon class="mx-auto mb-4 h-16 w-16 text-gray-400" />
<h3 class="mb-2 text-lg font-medium text-gray-700">数据分析功能</h3>
<p class="text-gray-500">此功能正在开发中,敬请期待...</p>
</div>
</Card>
</div>
</template>
<script setup lang="ts">
import { Card } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
// 创建图标组件
const BarChartIcon = createIconifyIcon('lucide:bar-chart-3');
defineOptions({ name: 'DataAnalysis' });
</script>
@@ -1,126 +1,17 @@
<template>
<Modal
:open="visible"
title="创建缺失的实体"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<div class="space-y-6">
<!-- 店铺创建 -->
<div v-if="entitiesToCreate.shops.length > 0" class="border border-gray-200 rounded-lg p-4">
<h3 class="text-lg font-medium text-gray-900 mb-4">需要创建的店铺 ({{ entitiesToCreate.shops.length }} 个)</h3>
<div class="space-y-3">
<div
v-for="(shopName, index) in entitiesToCreate.shops"
:key="`shop-${index}`"
class="flex items-center gap-4 p-3 bg-gray-50 rounded"
>
<span class="font-medium">{{ shopName }}</span>
<Button
type="primary"
size="small"
@click="openShopModal(shopName)"
>
创建店铺
</Button>
</div>
</div>
</div>
<!-- 商品创建 -->
<div v-if="entitiesToCreate.products.length > 0" class="border border-gray-200 rounded-lg p-4">
<h3 class="text-lg font-medium text-gray-900 mb-4">需要创建的商品 ({{ entitiesToCreate.products.length }} 个)</h3>
<div class="space-y-3">
<div
v-for="(productName, index) in entitiesToCreate.products"
:key="`product-${index}`"
class="flex items-center gap-4 p-3 bg-gray-50 rounded"
>
<span class="font-medium">{{ productName }}</span>
<Button
type="primary"
size="small"
@click="openProductModal(productName)"
>
创建商品
</Button>
</div>
</div>
</div>
<!-- 商品规格创建 -->
<div v-if="entitiesToCreate.specs.length > 0" class="border border-gray-200 rounded-lg p-4">
<h3 class="text-lg font-medium text-gray-900 mb-4">需要创建的商品规格 ({{ entitiesToCreate.specs.length }} 个)</h3>
<div class="space-y-3">
<div
v-for="(spec, index) in entitiesToCreate.specs"
:key="`spec-${index}`"
class="flex items-center gap-4 p-3 bg-gray-50 rounded"
>
<span class="font-medium">{{ spec.productName }} - {{ spec.specCode }}</span>
<Button
type="primary"
size="small"
@click="openProductSpecModal(spec)"
>
创建规格
</Button>
</div>
</div>
</div>
<!-- 提示信息 -->
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div class="flex items-start">
<div class="flex-shrink-0">
<svg class="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
</svg>
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-blue-800">提示</h3>
<div class="mt-2 text-sm text-blue-700">
<p>请先创建所有缺失的实体,然后再进行数据导入。创建完成后,系统将自动重新匹配数据。</p>
</div>
</div>
</div>
</div>
</div>
</Modal>
<!-- 店铺创建模态框 -->
<ShopFormModal
ref="shopFormModalRef"
@success="handleShopCreated"
/>
<!-- 商品创建模态框 -->
<ProductFormModal
ref="productFormModalRef"
@success="handleProductCreated"
/>
<!-- 商品规格创建模态框 -->
<ProductSpecModal
ref="productSpecModalRef"
@success="handleProductSpecCreated"
/>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { Modal, Button, message } from 'ant-design-vue';
import ShopFormModal from '#/views/shop/shop/components/ShopFormModal.vue';
import { Button, message, Modal } from 'ant-design-vue';
import ProductFormModal from '#/views/shop/product/components/ProductFormModal.vue';
import ProductSpecModal from '#/views/shop/product/components/ProductSpecModal.vue';
import ShopFormModal from '#/views/shop/shop/components/ShopFormModal.vue';
interface Props {
visible: boolean;
entitiesToCreate: {
shops: string[];
products: string[];
shops: string[];
specs: { productName: string; specCode: string; specName?: string }[];
};
csvData?: any[]; // 传递CSV数据用于获取更多信息
@@ -143,20 +34,25 @@ const productSpecModalRef = ref();
// 当前正在创建的实体
const currentCreatingShop = ref<string>('');
const currentCreatingProduct = ref<string>('');
const currentCreatingSpec = ref<{ productName: string; specCode: string } | null>(null);
const currentCreatingSpec = ref<null | {
productName: string;
specCode: string;
}>(null);
// 处理提交
function handleSubmit() {
// 检查是否还有未创建的实体
const { entitiesToCreate } = defineProps<Props>();
if (entitiesToCreate.shops.length > 0 ||
entitiesToCreate.products.length > 0 ||
entitiesToCreate.specs.length > 0) {
if (
entitiesToCreate.shops.length > 0 ||
entitiesToCreate.products.length > 0 ||
entitiesToCreate.specs.length > 0
) {
message.warning('请先创建所有缺失的实体');
return;
}
emit('success');
}
@@ -180,40 +76,43 @@ function openShopModal(shopName: string) {
// 打开商品创建模态框
function openProductModal(productName: string) {
currentCreatingProduct.value = productName;
// 从CSV数据中获取该商品的所有规格信息
const csvSpecs = props.csvData?.filter(row => row.productName === productName) || [];
const csvSpecs =
props.csvData?.filter((row) => row.productName === productName) || [];
// 对规格进行去重处理,使用Map来去重
const specMap = new Map<string, { specCode: string; specName: string }>();
csvSpecs.forEach(row => {
csvSpecs.forEach((row) => {
const specCode = row.specCode;
const specName = row.productSpecName;
if (specCode && !specMap.has(specCode)) {
specMap.set(specCode, {
specCode: specCode,
specName: specName || specCode // 如果没有规格名称,使用规格编码
specCode,
specName: specName || specCode, // 如果没有规格名称,使用规格编码
});
}
});
// 转换为数组
const uniqueSpecs = Array.from(specMap.values());
const uniqueSpecs = [...specMap.values()];
// 构建商品数据,包含规格信息
const productData = {
name: productName,
description: `从CSV文件导入的商品:${productName}`,
// 添加规格信息
specs: uniqueSpecs
specs: uniqueSpecs,
};
console.log('商品数据:', productData);
productFormModalRef.value?.open(false, productData);
}
// 打开商品规格创建模态框
function openProductSpecModal(spec: { productName: string; specCode: string; specName?: string }) {
function openProductSpecModal(spec: {
productName: string;
specCode: string;
specName?: string;
}) {
currentCreatingSpec.value = spec;
// 由于ProductSpecModal需要完整的商品对象,这里需要先创建商品
// 或者修改ProductSpecModal以支持部分数据
@@ -239,10 +138,144 @@ function handleProductCreated() {
// 处理商品规格创建成功
function handleProductSpecCreated() {
if (currentCreatingSpec.value) {
message.success(`商品规格 "${currentCreatingSpec.value.productName} - ${currentCreatingSpec.value.specCode}" 创建成功`);
message.success(
`商品规格 "${currentCreatingSpec.value.productName} - ${currentCreatingSpec.value.specCode}" 创建成功`,
);
currentCreatingSpec.value = null;
// 这里可以触发重新匹配
emit('success');
}
}
</script>
<template>
<Modal
:open="visible"
title="创建缺失的实体"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<div class="space-y-6">
<!-- 店铺创建 -->
<div
v-if="entitiesToCreate.shops.length > 0"
class="rounded-lg border border-gray-200 p-4"
>
<h3 class="mb-4 text-lg font-medium text-gray-900">
需要创建的店铺 ({{ entitiesToCreate.shops.length }} 个)
</h3>
<div class="space-y-3">
<div
v-for="(shopName, index) in entitiesToCreate.shops"
:key="`shop-${index}`"
class="flex items-center gap-4 rounded bg-gray-50 p-3"
>
<span class="font-medium">{{ shopName }}</span>
<Button
type="primary"
size="small"
@click="openShopModal(shopName)"
>
创建店铺
</Button>
</div>
</div>
</div>
<!-- 商品创建 -->
<div
v-if="entitiesToCreate.products.length > 0"
class="rounded-lg border border-gray-200 p-4"
>
<h3 class="mb-4 text-lg font-medium text-gray-900">
需要创建的商品 ({{ entitiesToCreate.products.length }} 个)
</h3>
<div class="space-y-3">
<div
v-for="(productName, index) in entitiesToCreate.products"
:key="`product-${index}`"
class="flex items-center gap-4 rounded bg-gray-50 p-3"
>
<span class="font-medium">{{ productName }}</span>
<Button
type="primary"
size="small"
@click="openProductModal(productName)"
>
创建商品
</Button>
</div>
</div>
</div>
<!-- 商品规格创建 -->
<div
v-if="entitiesToCreate.specs.length > 0"
class="rounded-lg border border-gray-200 p-4"
>
<h3 class="mb-4 text-lg font-medium text-gray-900">
需要创建的商品规格 ({{ entitiesToCreate.specs.length }} 个)
</h3>
<div class="space-y-3">
<div
v-for="(spec, index) in entitiesToCreate.specs"
:key="`spec-${index}`"
class="flex items-center gap-4 rounded bg-gray-50 p-3"
>
<span class="font-medium">
{{ spec.productName }} - {{ spec.specCode }}
</span>
<Button
type="primary"
size="small"
@click="openProductSpecModal(spec)"
>
创建规格
</Button>
</div>
</div>
</div>
<!-- 提示信息 -->
<div class="rounded-lg border border-blue-200 bg-blue-50 p-4">
<div class="flex items-start">
<div class="flex-shrink-0">
<svg
class="h-5 w-5 text-blue-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
clip-rule="evenodd"
/>
</svg>
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-blue-800">提示</h3>
<div class="mt-2 text-sm text-blue-700">
<p>
请先创建所有缺失的实体,然后再进行数据导入。创建完成后,系统将自动重新匹配数据。
</p>
</div>
</div>
</div>
</div>
</div>
</Modal>
<!-- 店铺创建模态框 -->
<ShopFormModal ref="shopFormModalRef" @success="handleShopCreated" />
<!-- 商品创建模态框 -->
<ProductFormModal ref="productFormModalRef" @success="handleProductCreated" />
<!-- 商品规格创建模态框 -->
<ProductSpecModal
ref="productSpecModalRef"
@success="handleProductSpecCreated"
/>
</template>
@@ -1,81 +1,36 @@
<template>
<div class="space-y-6">
<!-- 字段映射说明 -->
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div class="flex items-start space-x-2">
<InfoIcon class="w-5 h-5 text-blue-500 mt-0.5" />
<div>
<p class="font-medium text-blue-800">字段映射说明</p>
<p class="text-sm text-blue-600 mt-1">
请为每个CSV字段选择对应的标准字段,未映射的字段将被忽略。您也可以自定义字段名称。
</p>
</div>
</div>
</div>
<!-- 字段映射表格 -->
<div class="border rounded-lg">
<Table
:columns="mappingColumns"
:data-source="mappingData"
:pagination="false"
size="small"
/>
</div>
<!-- 数据预览 -->
<div v-if="previewData.length > 0">
<h4 class="text-md font-medium mb-3">映射后数据预览</h4>
<Table
:columns="previewColumns"
:data-source="previewData.slice(0, 5)"
:pagination="false"
size="small"
:scroll="{ x: 800 }"
/>
<p class="text-sm text-gray-500 mt-2">
显示前5条映射后的数据,共 {{ previewData.length }} 条记录
</p>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-3 pt-4 border-t">
<Button @click="$emit('cancel')">
取消
</Button>
<Button @click="handleExport" type="primary">
导出JSON
</Button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, h } from 'vue'
import { message, Table, Button } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import { transformDataWithMapping, generateExportData, downloadJSON } from '#/utils/csv-utils'
import { computed, h, ref, watch } from 'vue';
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info')
import { createIconifyIcon } from '@vben/icons';
// Props
interface Props {
csvHeaders: string[]
csvData: any[]
}
import { Button, message, Table } from 'ant-design-vue';
const props = defineProps<Props>()
import {
downloadJSON,
generateExportData,
transformDataWithMapping,
} from '#/utils/csv-utils';
const props = defineProps<Props>();
// Emits
const emit = defineEmits<{
confirm: [data: any]
cancel: []
}>()
cancel: [];
confirm: [data: any];
}>();
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info');
// Props
interface Props {
csvHeaders: string[];
csvData: any[];
}
// 响应式数据
const fieldMappings = ref<Record<string, string>>({})
const customFieldNames = ref<Record<string, string>>({})
const fieldMappings = ref<Record<string, string>>({});
const customFieldNames = ref<Record<string, string>>({});
// 标准字段选项
const standardFields = [
@@ -93,7 +48,7 @@ const standardFields = [
{ value: 'payment_method', label: '支付方式' },
{ value: 'delivery_address', label: '收货地址' },
{ value: 'remark', label: '备注' },
]
];
// 计算属性
const mappingData = computed(() => {
@@ -102,8 +57,8 @@ const mappingData = computed(() => {
csvField: header,
standardField: fieldMappings.value[header] || '',
customName: customFieldNames.value[header] || '',
}))
})
}));
});
const mappingColumns = [
{
@@ -124,10 +79,10 @@ const mappingColumns = [
allowClear: true,
options: standardFields,
onChange: (value: string) => {
fieldMappings.value[record.csvField] = value
}
})
}
fieldMappings.value[record.csvField] = value;
},
});
},
},
{
title: '自定义字段名',
@@ -139,10 +94,10 @@ const mappingColumns = [
value: record.customName,
placeholder: '可选:自定义字段名',
onChange: (e: any) => {
customFieldNames.value[record.csvField] = e.target.value
}
})
}
customFieldNames.value[record.csvField] = e.target.value;
},
});
},
},
{
title: '示例数据',
@@ -150,60 +105,114 @@ const mappingColumns = [
key: 'example',
ellipsis: true,
customRender: ({ record }: any) => {
const exampleValue = props.csvData[0]?.[record.csvField] || ''
return exampleValue.toString().substring(0, 50) + (exampleValue.toString().length > 50 ? '...' : '')
}
}
]
const exampleValue = props.csvData[0]?.[record.csvField] || '';
return (
exampleValue.toString().slice(0, 50) +
(exampleValue.toString().length > 50 ? '...' : '')
);
},
},
];
const previewData = computed(() => {
if (Object.keys(fieldMappings.value).length === 0) return []
if (Object.keys(fieldMappings.value).length === 0) return [];
return transformDataWithMapping(
props.csvData,
fieldMappings.value,
customFieldNames.value
)
})
customFieldNames.value,
);
});
const previewColumns = computed(() => {
const columns = Object.keys(previewData.value[0] || {}).map(field => ({
const columns = Object.keys(previewData.value[0] || {}).map((field) => ({
title: field,
dataIndex: field,
key: field,
width: 150,
ellipsis: true,
}))
return columns
})
}));
return columns;
});
// 监听字段映射变化,自动生成预览
watch([fieldMappings, customFieldNames], () => {
// 预览数据会自动更新
}, { deep: true })
watch(
[fieldMappings, customFieldNames],
() => {
// 预览数据会自动更新
},
{ deep: true },
);
// 导出JSON
const handleExport = () => {
if (previewData.value.length === 0) {
message.warning('请先配置字段映射')
return
message.warning('请先配置字段映射');
return;
}
const exportData = generateExportData(
previewData.value,
fieldMappings.value,
customFieldNames.value
)
// 使用工具函数下载JSON
downloadJSON(exportData)
message.success('JSON文件导出成功')
emit('confirm', exportData)
}
customFieldNames.value,
);
// 使用工具函数下载JSON
downloadJSON(exportData);
message.success('JSON文件导出成功');
emit('confirm', exportData);
};
</script>
<template>
<div class="space-y-6">
<!-- 字段映射说明 -->
<div class="rounded-lg border border-blue-200 bg-blue-50 p-4">
<div class="flex items-start space-x-2">
<InfoIcon class="mt-0.5 h-5 w-5 text-blue-500" />
<div>
<p class="font-medium text-blue-800">字段映射说明</p>
<p class="mt-1 text-sm text-blue-600">
请为每个CSV字段选择对应的标准字段,未映射的字段将被忽略。您也可以自定义字段名称。
</p>
</div>
</div>
</div>
<!-- 字段映射表格 -->
<div class="rounded-lg border">
<Table
:columns="mappingColumns"
:data-source="mappingData"
:pagination="false"
size="small"
/>
</div>
<!-- 数据预览 -->
<div v-if="previewData.length > 0">
<h4 class="text-md mb-3 font-medium">映射后数据预览</h4>
<Table
:columns="previewColumns"
:data-source="previewData.slice(0, 5)"
:pagination="false"
size="small"
:scroll="{ x: 800 }"
/>
<p class="mt-2 text-sm text-gray-500">
显示前5条映射后的数据,共 {{ previewData.length }} 条记录
</p>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-3 border-t pt-4">
<Button @click="$emit('cancel')"> 取消 </Button>
<Button @click="handleExport" type="primary"> 导出JSON </Button>
</div>
</div>
</template>
<style scoped>
.ant-table-tbody > tr > td {
padding: 8px 12px;
@@ -1,16 +1,291 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, Modal, Select } from 'ant-design-vue';
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info');
const CheckIcon = createIconifyIcon('lucide:check');
const XIcon = createIconifyIcon('lucide:x');
interface SystemField {
key: string;
label: string;
description: string;
required: boolean;
dataType: string;
}
interface Props {
visible: boolean;
csvHeaders: string[];
csvData: any[];
}
interface Emits {
(e: 'update:visible', value: boolean): void;
(e: 'confirm', mappings: Record<string, string>): void;
(e: 'cancel'): void;
}
const visible = ref(false);
// 系统字段定义
const systemFields: SystemField[] = [
{
key: 'shopName',
label: '店铺名称',
description: '订单所属店铺名称',
required: true,
dataType: 'string',
},
{
key: 'productName',
label: '商品名称',
description: '订单商品名称',
required: true,
dataType: 'string',
},
{
key: 'productSpecName',
label: '商品规格',
description: '商品规格名称',
required: false,
dataType: 'string',
},
{
key: 'specCode',
label: '规格编码',
description: '商品规格编码',
required: false,
dataType: 'string',
},
{
key: 'orderNumber',
label: '订单编号',
description: '平台订单编号',
required: true,
dataType: 'string',
},
{
key: 'orderStatusName',
label: '订单状态',
description: '订单状态名称',
required: true,
dataType: 'string',
},
{
key: 'quantity',
label: '商品数量',
description: '订单商品数量',
required: true,
dataType: 'number',
},
{
key: 'shopActualAmount',
label: '实收金额',
description: '商家实际收到金额',
required: true,
dataType: 'number',
},
{
key: 'unitPrice',
label: '销售单价',
description: '商品销售单价',
required: false,
dataType: 'number',
},
{
key: 'costPrice',
label: '成本价',
description: '商品成本价格',
required: false,
dataType: 'number',
},
{
key: 'orderDate',
label: '下单时间',
description: '订单创建时间',
required: false,
dataType: 'date',
},
{
key: 'shippingFee',
label: '运费',
description: '订单运费',
required: false,
dataType: 'number',
},
];
// 字段映射状态
const fieldMappings = ref<Record<string, string>>({});
// CSV字段选项
const csvFieldOptions = computed(() => {
return props.csvHeaders.map((header) => ({
label: header,
value: header,
}));
});
// 已映射字段数量
const mappedFieldsCount = computed(() => {
return Object.values(fieldMappings.value).filter(Boolean).length;
});
// 未映射字段数量
const unmappedFieldsCount = computed(() => {
return systemFields.length - mappedFieldsCount.value;
});
// 监听visible变化
watch(
() => props.visible,
(newVal) => {
visible.value = newVal;
if (newVal) {
// 初始化字段映射
initializeFieldMappings();
}
},
);
watch(visible, (newVal) => {
emit('update:visible', newVal);
});
// 初始化字段映射
const initializeFieldMappings = () => {
const mappings: Record<string, string> = {};
// 尝试自动匹配字段
systemFields.forEach((field) => {
const matchedHeader = findBestMatch(field.label, props.csvHeaders);
if (matchedHeader) {
mappings[field.key] = matchedHeader;
}
});
fieldMappings.value = mappings;
};
// 查找最佳匹配
const findBestMatch = (
systemFieldLabel: string,
csvHeaders: string[],
): null | string => {
const systemFieldLower = systemFieldLabel.toLowerCase();
// 精确匹配
for (const header of csvHeaders) {
if (header.toLowerCase() === systemFieldLower) {
return header;
}
}
// 包含匹配
for (const header of csvHeaders) {
if (
header.toLowerCase().includes(systemFieldLower) ||
systemFieldLower.includes(header.toLowerCase())
) {
return header;
}
}
// 关键词匹配
const keywords = {
店铺名称: ['店铺', 'shop', 'store'],
商品名称: ['商品', 'product', 'item'],
商品规格: ['规格', 'spec', '规格名称'],
规格编码: ['编码', 'code', '规格编码'],
订单编号: ['订单', 'order', '编号', 'number'],
订单状态: ['状态', 'status'],
商品数量: ['数量', 'quantity', 'qty'],
实收金额: ['实收', '金额', 'amount', 'received'],
销售单价: ['单价', 'price', 'unit'],
成本价: ['成本', 'cost'],
下单时间: ['时间', 'date', 'time', '下单'],
运费: ['运费', 'shipping', 'freight'],
};
const fieldKeywords =
keywords[systemFieldLabel as keyof typeof keywords] || [];
for (const header of csvHeaders) {
for (const keyword of fieldKeywords) {
if (header.toLowerCase().includes(keyword)) {
return header;
}
}
}
return null;
};
// 下拉框搜索过滤
const filterOption = (input: string, option: any) => {
return option.label.toLowerCase().includes(input.toLowerCase());
};
// 处理字段映射变化
const handleFieldMappingChange = (
fieldKey: string,
value: string | undefined,
) => {
fieldMappings.value[fieldKey] = value || '';
};
// 获取字段数据样本
const getFieldSamples = (fieldName: string) => {
if (!fieldName || props.csvData.length === 0) return [];
return props.csvData
.slice(0, 3)
.map((row) => row[fieldName] || '')
.filter((val) => val !== '');
};
// 处理确认
const handleConfirm = () => {
if (unmappedFieldsCount.value > 0) {
return;
}
emit('confirm', { ...fieldMappings.value });
visible.value = false;
};
// 处理取消
const handleCancel = () => {
visible.value = false;
emit('cancel');
};
// 处理重置
const handleReset = () => {
fieldMappings.value = {};
};
</script>
<template>
<Modal
v-model:open="visible"
title="字段匹配配置"
width="1200px"
:footer="null"
@cancel="handleCancel"
>
<Modal
v-model:open="visible"
title="字段匹配配置"
width="1200px"
:footer="null"
@cancel="handleCancel"
>
<div class="field-mapping-container">
<!-- 说明信息 -->
<div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
<div class="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-3">
<div class="flex items-center space-x-2">
<InfoIcon class="w-4 h-4 text-blue-500" />
<InfoIcon class="h-4 w-4 text-blue-500" />
<span class="text-sm text-blue-800">
请将左侧系统字段与右侧CSV文件字段进行匹配,重新组织数据结构以正确进行实体匹配
</span>
@@ -25,39 +300,37 @@
<h3 class="text-lg font-medium text-gray-800">系统字段</h3>
<p class="text-sm text-gray-600">系统预定义的订单字段,必须映射</p>
</div>
<div class="space-y-3 max-h-96 overflow-y-auto">
<div
v-for="field in systemFields"
<div class="max-h-96 space-y-3 overflow-y-auto">
<div
v-for="field in systemFields"
:key="field.key"
class="field-item p-3 border rounded-lg"
class="field-item rounded-lg border p-3"
:class="{
'border-green-200 bg-green-50': fieldMappings[field.key],
'border-gray-200 bg-gray-50': !fieldMappings[field.key]
'border-gray-200 bg-gray-50': !fieldMappings[field.key],
}"
>
<div class="flex items-center justify-between">
<div class="flex-1">
<div class="flex items-center space-x-2">
<span class="font-medium text-gray-800">{{ field.label }}</span>
<span
v-if="field.required"
class="text-red-500 text-xs"
>
<span class="font-medium text-gray-800">{{
field.label
}}</span>
<span v-if="field.required" class="text-xs text-red-500">
*
</span>
</div>
<div class="text-xs text-gray-500 mt-1">{{ field.description }}</div>
<div class="mt-1 text-xs text-gray-500">
{{ field.description }}
</div>
</div>
<div class="flex items-center space-x-2">
<CheckIcon
v-if="fieldMappings[field.key]"
class="w-4 h-4 text-green-500"
/>
<XIcon
v-else
class="w-4 h-4 text-gray-400"
<CheckIcon
v-if="fieldMappings[field.key]"
class="h-4 w-4 text-green-500"
/>
<XIcon v-else class="h-4 w-4 text-gray-400" />
</div>
</div>
</div>
@@ -70,35 +343,31 @@
<h3 class="text-lg font-medium text-gray-800">CSV字段映射</h3>
<p class="text-sm text-gray-600">选择CSV文件中的对应字段</p>
</div>
<div class="space-y-3 max-h-96 overflow-y-auto">
<div
v-for="field in systemFields"
<div class="max-h-96 space-y-3 overflow-y-auto">
<div
v-for="field in systemFields"
:key="field.key"
class="field-mapping-item p-3 border rounded-lg"
class="field-mapping-item rounded-lg border p-3"
>
<div class="flex items-center justify-between mb-2">
<div class="mb-2 flex items-center justify-between">
<div class="flex items-center space-x-2">
<span class="font-medium text-gray-800">{{ field.label }}</span>
<span
v-if="field.required"
class="text-red-500 text-xs"
>
<span class="font-medium text-gray-800">{{
field.label
}}</span>
<span v-if="field.required" class="text-xs text-red-500">
*
</span>
</div>
<div class="flex items-center space-x-2">
<CheckIcon
v-if="fieldMappings[field.key]"
class="w-4 h-4 text-green-500"
/>
<XIcon
v-else
class="w-4 h-4 text-gray-400"
<CheckIcon
v-if="fieldMappings[field.key]"
class="h-4 w-4 text-green-500"
/>
<XIcon v-else class="h-4 w-4 text-gray-400" />
</div>
</div>
<Select
v-model:value="fieldMappings[field.key]"
placeholder="请选择CSV字段"
@@ -107,7 +376,9 @@
:filter-option="filterOption"
show-search
allow-clear
@change="(value: any) => handleFieldMappingChange(field.key, value)"
@change="
(value: any) => handleFieldMappingChange(field.key, value)
"
>
<template #option="{ label, value }">
<div class="flex items-center justify-between">
@@ -116,12 +387,19 @@
</div>
</template>
</Select>
<!-- 字段预览 -->
<div v-if="fieldMappings[field.key]" class="mt-2">
<div class="text-xs text-gray-600 mb-1">数据预览:</div>
<div class="text-xs bg-gray-100 p-2 rounded max-h-20 overflow-y-auto">
<div v-for="(sample, index) in getFieldSamples(fieldMappings[field.key] || '')" :key="index">
<div class="mb-1 text-xs text-gray-600">数据预览:</div>
<div
class="max-h-20 overflow-y-auto rounded bg-gray-100 p-2 text-xs"
>
<div
v-for="(sample, index) in getFieldSamples(
fieldMappings[field.key] || '',
)"
:key="index"
>
{{ sample }}
</div>
</div>
@@ -132,33 +410,35 @@
</div>
<!-- 映射统计 -->
<div class="mt-6 p-4 bg-gray-50 border rounded-lg">
<div class="mt-6 rounded-lg border bg-gray-50 p-4">
<div class="grid grid-cols-3 gap-4 text-center">
<div>
<div class="text-2xl font-bold text-blue-600">{{ systemFields.length }}</div>
<div class="text-2xl font-bold text-blue-600">
{{ systemFields.length }}
</div>
<div class="text-sm text-gray-600">总字段数</div>
</div>
<div>
<div class="text-2xl font-bold text-green-600">{{ mappedFieldsCount }}</div>
<div class="text-2xl font-bold text-green-600">
{{ mappedFieldsCount }}
</div>
<div class="text-sm text-gray-600">已映射</div>
</div>
<div>
<div class="text-2xl font-bold text-red-600">{{ unmappedFieldsCount }}</div>
<div class="text-2xl font-bold text-red-600">
{{ unmappedFieldsCount }}
</div>
<div class="text-sm text-gray-600">未映射</div>
</div>
</div>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-3 mt-6">
<Button @click="handleCancel">
取消
</Button>
<Button @click="handleReset" type="default">
重置
</Button>
<Button
type="primary"
<div class="mt-6 flex justify-end space-x-3">
<Button @click="handleCancel"> 取消 </Button>
<Button @click="handleReset" type="default"> 重置 </Button>
<Button
type="primary"
@click="handleConfirm"
:disabled="unmappedFieldsCount > 0"
>
@@ -169,265 +449,6 @@
</Modal>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Modal, Button, Select } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info')
const CheckIcon = createIconifyIcon('lucide:check')
const XIcon = createIconifyIcon('lucide:x')
interface SystemField {
key: string
label: string
description: string
required: boolean
dataType: string
}
interface Props {
visible: boolean
csvHeaders: string[]
csvData: any[]
}
interface Emits {
(e: 'update:visible', value: boolean): void
(e: 'confirm', mappings: Record<string, string>): void
(e: 'cancel'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const visible = ref(false)
// 系统字段定义
const systemFields: SystemField[] = [
{
key: 'shopName',
label: '店铺名称',
description: '订单所属店铺名称',
required: true,
dataType: 'string'
},
{
key: 'productName',
label: '商品名称',
description: '订单商品名称',
required: true,
dataType: 'string'
},
{
key: 'productSpecName',
label: '商品规格',
description: '商品规格名称',
required: false,
dataType: 'string'
},
{
key: 'specCode',
label: '规格编码',
description: '商品规格编码',
required: false,
dataType: 'string'
},
{
key: 'orderNumber',
label: '订单编号',
description: '平台订单编号',
required: true,
dataType: 'string'
},
{
key: 'orderStatusName',
label: '订单状态',
description: '订单状态名称',
required: true,
dataType: 'string'
},
{
key: 'quantity',
label: '商品数量',
description: '订单商品数量',
required: true,
dataType: 'number'
},
{
key: 'shopActualAmount',
label: '实收金额',
description: '商家实际收到金额',
required: true,
dataType: 'number'
},
{
key: 'unitPrice',
label: '销售单价',
description: '商品销售单价',
required: false,
dataType: 'number'
},
{
key: 'costPrice',
label: '成本价',
description: '商品成本价格',
required: false,
dataType: 'number'
},
{
key: 'orderDate',
label: '下单时间',
description: '订单创建时间',
required: false,
dataType: 'date'
},
{
key: 'shippingFee',
label: '运费',
description: '订单运费',
required: false,
dataType: 'number'
}
]
// 字段映射状态
const fieldMappings = ref<Record<string, string>>({})
// CSV字段选项
const csvFieldOptions = computed(() => {
return props.csvHeaders.map(header => ({
label: header,
value: header
}))
})
// 已映射字段数量
const mappedFieldsCount = computed(() => {
return Object.values(fieldMappings.value).filter(value => value).length
})
// 未映射字段数量
const unmappedFieldsCount = computed(() => {
return systemFields.length - mappedFieldsCount.value
})
// 监听visible变化
watch(() => props.visible, (newVal) => {
visible.value = newVal
if (newVal) {
// 初始化字段映射
initializeFieldMappings()
}
})
watch(visible, (newVal) => {
emit('update:visible', newVal)
})
// 初始化字段映射
const initializeFieldMappings = () => {
const mappings: Record<string, string> = {}
// 尝试自动匹配字段
systemFields.forEach(field => {
const matchedHeader = findBestMatch(field.label, props.csvHeaders)
if (matchedHeader) {
mappings[field.key] = matchedHeader
}
})
fieldMappings.value = mappings
}
// 查找最佳匹配
const findBestMatch = (systemFieldLabel: string, csvHeaders: string[]): string | null => {
const systemFieldLower = systemFieldLabel.toLowerCase()
// 精确匹配
for (const header of csvHeaders) {
if (header.toLowerCase() === systemFieldLower) {
return header
}
}
// 包含匹配
for (const header of csvHeaders) {
if (header.toLowerCase().includes(systemFieldLower) ||
systemFieldLower.includes(header.toLowerCase())) {
return header
}
}
// 关键词匹配
const keywords = {
'店铺名称': ['店铺', 'shop', 'store'],
'商品名称': ['商品', 'product', 'item'],
'商品规格': ['规格', 'spec', '规格名称'],
'规格编码': ['编码', 'code', '规格编码'],
'订单编号': ['订单', 'order', '编号', 'number'],
'订单状态': ['状态', 'status'],
'商品数量': ['数量', 'quantity', 'qty'],
'实收金额': ['实收', '金额', 'amount', 'received'],
'销售单价': ['单价', 'price', 'unit'],
'成本价': ['成本', 'cost'],
'下单时间': ['时间', 'date', 'time', '下单'],
'运费': ['运费', 'shipping', 'freight']
}
const fieldKeywords = keywords[systemFieldLabel as keyof typeof keywords] || []
for (const header of csvHeaders) {
for (const keyword of fieldKeywords) {
if (header.toLowerCase().includes(keyword)) {
return header
}
}
}
return null
}
// 下拉框搜索过滤
const filterOption = (input: string, option: any) => {
return option.label.toLowerCase().includes(input.toLowerCase())
}
// 处理字段映射变化
const handleFieldMappingChange = (fieldKey: string, value: string | undefined) => {
fieldMappings.value[fieldKey] = value || ''
}
// 获取字段数据样本
const getFieldSamples = (fieldName: string) => {
if (!fieldName || !props.csvData.length) return []
return props.csvData.slice(0, 3).map(row => row[fieldName] || '').filter(val => val !== '')
}
// 处理确认
const handleConfirm = () => {
if (unmappedFieldsCount.value > 0) {
return
}
emit('confirm', { ...fieldMappings.value })
visible.value = false
}
// 处理取消
const handleCancel = () => {
visible.value = false
emit('cancel')
}
// 处理重置
const handleReset = () => {
fieldMappings.value = {}
}
</script>
<style scoped>
.field-mapping-container {
max-height: 80vh;
@@ -1,20 +1,109 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message } from 'ant-design-vue';
defineOptions({ name: 'FileUploadArea' });
const emit = defineEmits<Emits>();
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
// Emits
interface Emits {
(e: 'fileSelected', file: File): void;
}
// 响应式数据
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 文件验证
const validateFile = (file: File): boolean => {
const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv');
if (!isCSV) {
message.error('只能上传CSV格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
// 处理文件
const processFile = (file: File) => {
if (!validateFile(file)) return;
emit('fileSelected', file);
};
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
// 清空input值,允许重复选择同一文件
target.value = '';
};
</script>
<template>
<div
class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center transition-colors"
<div
class="rounded-lg border-2 border-dashed border-gray-300 p-8 text-center transition-colors"
:class="{ 'border-blue-500 bg-blue-50': isDragOver }"
@dragover.prevent="handleDragOver"
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
>
<div class="space-y-4">
<UploadIcon class="w-12 h-12 mx-auto text-gray-400" />
<UploadIcon class="mx-auto h-12 w-12 text-gray-400" />
<div>
<p class="text-lg font-medium text-gray-700">拖拽CSV文件到此处或点击上传</p>
<p class="text-lg font-medium text-gray-700">
拖拽CSV文件到此处或点击上传
</p>
<p class="text-sm text-gray-500">支持.csv格式,最大10MB</p>
</div>
<Button @click="triggerFileInput" type="primary" ghost>
选择文件
</Button>
<Button @click="triggerFileInput" type="primary" ghost> 选择文件 </Button>
</div>
<input
ref="fileInputRef"
@@ -26,93 +115,6 @@
</div>
</template>
<script setup lang="ts">
defineOptions({ name: 'FileUploadArea' })
import { ref } from 'vue'
import { message, Button } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload')
// Emits
interface Emits {
(e: 'file-selected', file: File): void
}
const emit = defineEmits<Emits>()
// 响应式数据
const isDragOver = ref(false)
const fileInputRef = ref<HTMLInputElement>()
// 文件验证
const validateFile = (file: File): boolean => {
const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv')
if (!isCSV) {
message.error('只能上传CSV格式的文件!')
return false
}
const isLt10M = file.size / 1024 / 1024 < 10
if (!isLt10M) {
message.error('文件大小不能超过10MB!')
return false
}
return true
}
// 处理文件
const processFile = (file: File) => {
if (!validateFile(file)) return
emit('file-selected', file)
}
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault()
isDragOver.value = true
}
const handleDragLeave = (e: DragEvent) => {
e.preventDefault()
isDragOver.value = false
}
const handleDrop = (e: DragEvent) => {
e.preventDefault()
isDragOver.value = false
const files = e.dataTransfer?.files
if (files && files.length > 0) {
const file = files[0]
if (file) {
processFile(file)
}
}
}
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click()
}
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement
const files = target.files
if (files && files.length > 0) {
const file = files[0]
if (file) {
processFile(file)
}
}
// 清空input值,允许重复选择同一文件
target.value = ''
}
</script>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
@@ -1,3 +1,150 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Modal } from 'ant-design-vue';
defineOptions({ name: 'FileUploadModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const CheckCircleIcon = createIconifyIcon('lucide:check-circle');
// Props
interface Props {
open: boolean;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'confirm', file: File): void;
(e: 'cancel'): void;
}
// 响应式数据
const visible = ref(false);
const uploadedFile = ref<File | null>(null);
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 监听props变化
watch(
() => props.open,
(newVal) => {
visible.value = newVal;
if (!newVal) {
// 关闭时重置状态
uploadedFile.value = null;
isDragOver.value = false;
}
},
);
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal);
});
// 文件验证
const validateFile = (file: File): boolean => {
const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv');
if (!isCSV) {
message.error('只能上传CSV格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
// 处理文件
const processFile = (file: File) => {
if (!validateFile(file)) return;
uploadedFile.value = file;
message.success('文件选择成功');
};
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
// 清空input值,允许重复选择同一文件
target.value = '';
};
// 清除文件
const clearFile = () => {
uploadedFile.value = null;
};
// 确认上传
const handleConfirm = () => {
if (uploadedFile.value) {
emit('confirm', uploadedFile.value);
visible.value = false;
}
};
// 取消
const handleCancel = () => {
emit('cancel');
visible.value = false;
};
// 格式化文件大小
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};
</script>
<template>
<Modal
v-model:open="visible"
@@ -8,17 +155,19 @@
>
<div class="space-y-6">
<!-- 文件拖拽上传区域 -->
<div
class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center transition-colors"
<div
class="rounded-lg border-2 border-dashed border-gray-300 p-8 text-center transition-colors"
:class="{ 'border-blue-500 bg-blue-50': isDragOver }"
@dragover.prevent="handleDragOver"
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
>
<div class="space-y-4">
<UploadIcon class="w-12 h-12 mx-auto text-gray-400" />
<UploadIcon class="mx-auto h-12 w-12 text-gray-400" />
<div>
<p class="text-lg font-medium text-gray-700">拖拽CSV文件到此处或点击上传</p>
<p class="text-lg font-medium text-gray-700">
拖拽CSV文件到此处或点击上传
</p>
<p class="text-sm text-gray-500">支持.csv格式,最大10MB</p>
</div>
<Button @click="triggerFileInput" type="primary" ghost>
@@ -35,29 +184,28 @@
</div>
<!-- 文件信息显示 -->
<div v-if="uploadedFile" class="bg-green-50 border border-green-200 rounded-lg p-4">
<div
v-if="uploadedFile"
class="rounded-lg border border-green-200 bg-green-50 p-4"
>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-2">
<CheckCircleIcon class="w-5 h-5 text-green-500" />
<CheckCircleIcon class="h-5 w-5 text-green-500" />
<span class="font-medium text-green-800">文件上传成功</span>
</div>
<Button @click="clearFile" size="small" type="text" danger>
清除文件
</Button>
</div>
<p class="text-sm text-green-600 mt-1">{{ uploadedFile.name }} ({{ formatFileSize(uploadedFile.size) }})</p>
<p class="mt-1 text-sm text-green-600">
{{ uploadedFile.name }} ({{ formatFileSize(uploadedFile.size) }})
</p>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-2">
<Button @click="handleCancel">
取消
</Button>
<Button
@click="handleConfirm"
type="primary"
:disabled="!uploadedFile"
>
<Button @click="handleCancel"> 取消 </Button>
<Button @click="handleConfirm" type="primary" :disabled="!uploadedFile">
确认导入
</Button>
</div>
@@ -65,149 +213,6 @@
</Modal>
</template>
<script setup lang="ts">
defineOptions({ name: 'FileUploadModal' })
import { ref, watch } from 'vue'
import { message, Button, Modal } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload')
const CheckCircleIcon = createIconifyIcon('lucide:check-circle')
// Props
interface Props {
open: boolean
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void
(e: 'confirm', file: File): void
(e: 'cancel'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
// 响应式数据
const visible = ref(false)
const uploadedFile = ref<File | null>(null)
const isDragOver = ref(false)
const fileInputRef = ref<HTMLInputElement>()
// 监听props变化
watch(() => props.open, (newVal) => {
visible.value = newVal
if (!newVal) {
// 关闭时重置状态
uploadedFile.value = null
isDragOver.value = false
}
})
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal)
})
// 文件验证
const validateFile = (file: File): boolean => {
const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv')
if (!isCSV) {
message.error('只能上传CSV格式的文件!')
return false
}
const isLt10M = file.size / 1024 / 1024 < 10
if (!isLt10M) {
message.error('文件大小不能超过10MB!')
return false
}
return true
}
// 处理文件
const processFile = (file: File) => {
if (!validateFile(file)) return
uploadedFile.value = file
message.success('文件选择成功')
}
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault()
isDragOver.value = true
}
const handleDragLeave = (e: DragEvent) => {
e.preventDefault()
isDragOver.value = false
}
const handleDrop = (e: DragEvent) => {
e.preventDefault()
isDragOver.value = false
const files = e.dataTransfer?.files
if (files && files.length > 0) {
const file = files[0]
if (file) {
processFile(file)
}
}
}
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click()
}
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement
const files = target.files
if (files && files.length > 0) {
const file = files[0]
if (file) {
processFile(file)
}
}
// 清空input值,允许重复选择同一文件
target.value = ''
}
// 清除文件
const clearFile = () => {
uploadedFile.value = null
}
// 确认上传
const handleConfirm = () => {
if (uploadedFile.value) {
emit('confirm', uploadedFile.value)
visible.value = false
}
}
// 取消
const handleCancel = () => {
emit('cancel')
visible.value = false
}
// 格式化文件大小
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
@@ -1,3 +1,254 @@
<script setup lang="ts">
import type { MatchDetail } from '../services/EntityMatchingService';
import { computed, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, Modal, Select } from 'ant-design-vue';
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
const CheckIcon = createIconifyIcon('lucide:check');
const XIcon = createIconifyIcon('lucide:x');
const AlertTriangleIcon = createIconifyIcon('lucide:alert-triangle');
const InfoIcon = createIconifyIcon('lucide:info');
interface Props {
visible: boolean;
matchDetail: MatchDetail | null;
fieldType: 'orderStatus' | 'product' | 'shop' | 'spec';
sameDataCount?: number;
}
interface Emits {
(e: 'update:visible', value: boolean): void;
(e: 'applyMatch', rowIndex: number, fieldType: string, matchId: string): void;
(e: 'applyToAll', rowIndex: number, fieldType: string, matchId: string): void;
}
const selectedMatchId = ref<string>('');
// 计算属性用于双向绑定
const visible = computed({
get: () => props.visible,
set: (value) => {
emit('update:visible', value);
},
});
watch(
() => props.visible,
(newVal) => {
if (newVal && props.matchDetail) {
// 初始化选中的匹配项
selectedMatchId.value = getCurrentMatchId() || '';
}
},
);
const getStatusText = (status: string) => {
switch (status) {
case 'failed': {
return '匹配失败';
}
case 'matched': {
return '匹配成功';
}
case 'partial': {
return '部分匹配';
}
default: {
return '未知状态';
}
}
};
// 获取模态框标题
const getModalTitle = () => {
const titles = {
shop: '店铺匹配切换',
product: '商品匹配切换',
spec: '规格匹配切换',
orderStatus: '订单状态匹配切换',
};
return titles[props.fieldType] || '匹配切换';
};
// 获取字段标题
const getFieldTitle = () => {
const titles = {
shop: '店铺',
product: '商品',
spec: '规格',
orderStatus: '订单状态',
};
return titles[props.fieldType] || '字段';
};
// 获取字段名称
const getFieldName = () => {
const names = {
shop: '店铺',
product: '商品',
spec: '规格',
orderStatus: '订单状态',
};
return names[props.fieldType] || '字段';
};
// 获取字段值
const getFieldValue = () => {
if (!props.matchDetail) return '';
switch (props.fieldType) {
case 'orderStatus': {
return props.matchDetail.originalData.orderStatusName;
}
case 'product': {
return props.matchDetail.originalData.productName;
}
case 'shop': {
return props.matchDetail.originalData.shopName;
}
case 'spec': {
return props.matchDetail.originalData.productSpecName;
}
default: {
return '';
}
}
};
// 获取当前匹配信息
const getCurrentMatchInfo = () => {
if (!props.matchDetail) return null;
switch (props.fieldType) {
case 'orderStatus': {
return props.matchDetail.matchedOrderStatusId
? {
name: props.matchDetail.originalData.orderStatusName,
id: props.matchDetail.matchedOrderStatusId,
}
: null;
}
case 'product': {
return props.matchDetail.matchedProduct
? {
name: props.matchDetail.matchedProduct.name,
id: props.matchDetail.matchedProduct.id,
}
: null;
}
case 'shop': {
return props.matchDetail.matchedShop
? {
name: props.matchDetail.matchedShop.name,
id: props.matchDetail.matchedShop.id,
}
: null;
}
case 'spec': {
return props.matchDetail.matchedSpec
? {
name: props.matchDetail.matchedSpec.name,
id: props.matchDetail.matchedSpec.id,
specCode: props.matchDetail.matchedSpec.specCode,
}
: null;
}
default: {
return null;
}
}
};
// 获取当前匹配ID
const getCurrentMatchId = () => {
const matchInfo = getCurrentMatchInfo();
return matchInfo?.id?.toString() || '';
};
// 获取字段匹配状态样式
const getFieldMatchStatusClass = () => {
const matchInfo = getCurrentMatchInfo();
return matchInfo ? 'bg-green-500' : 'bg-red-500';
};
// 获取字段匹配状态文本
const getFieldMatchStatusText = () => {
const matchInfo = getCurrentMatchInfo();
return matchInfo ? '已匹配' : '未匹配';
};
// 获取匹配选项(模拟数据,实际应该从API获取)
const getMatchOptions = () => {
// 这里应该根据fieldType从API获取可选的匹配项
// 暂时返回模拟数据
const mockOptions = {
shop: [
{ label: '锐泽创意家居', value: '123' },
{ label: '其他店铺1', value: '124' },
{ label: '其他店铺2', value: '125' },
],
product: [
{ label: '创意台灯', value: '456' },
{ label: '其他商品1', value: '457' },
{ label: '其他商品2', value: '458' },
],
spec: [
{ label: '白色', value: '789' },
{ label: '黑色', value: '790' },
{ label: '红色', value: '791' },
],
orderStatus: [
{ label: '已发货,待收货', value: '1' },
{ label: '未发货,退款成功', value: '2' },
{ label: '已取消', value: '3' },
],
};
return mockOptions[props.fieldType] || [];
};
// 处理匹配选择变化
const handleMatchChange = (value: string) => {
selectedMatchId.value = value;
};
// 处理应用匹配
const handleApplyMatch = () => {
if (props.matchDetail && selectedMatchId.value) {
emit(
'applyMatch',
props.matchDetail.rowIndex,
props.fieldType,
selectedMatchId.value,
);
}
visible.value = false;
};
// 处理应用到所有相同数据
const handleApplyToAll = () => {
if (props.matchDetail && selectedMatchId.value) {
emit(
'applyToAll',
props.matchDetail.rowIndex,
props.fieldType,
selectedMatchId.value,
);
}
visible.value = false;
};
const handleCancel = () => {
visible.value = false;
};
</script>
<template>
<Modal
v-model:open="visible"
@@ -8,26 +259,26 @@
>
<div v-if="matchDetail" class="space-y-4">
<!-- 当前匹配状态 -->
<div class="flex items-center space-x-2 mb-4">
<div
class="w-4 h-4 rounded-full flex items-center justify-center"
<div class="mb-4 flex items-center space-x-2">
<div
class="flex h-4 w-4 items-center justify-center rounded-full"
:class="{
'bg-green-500': matchDetail.status === 'matched',
'bg-red-500': matchDetail.status === 'failed',
'bg-yellow-500': matchDetail.status === 'partial'
'bg-yellow-500': matchDetail.status === 'partial',
}"
>
<CheckIcon
v-if="matchDetail.status === 'matched'"
class="w-3 h-3 text-white"
<CheckIcon
v-if="matchDetail.status === 'matched'"
class="h-3 w-3 text-white"
/>
<XIcon
v-else-if="matchDetail.status === 'failed'"
class="w-3 h-3 text-white"
<XIcon
v-else-if="matchDetail.status === 'failed'"
class="h-3 w-3 text-white"
/>
<AlertTriangleIcon
v-else-if="matchDetail.status === 'partial'"
class="w-3 h-3 text-white"
<AlertTriangleIcon
v-else-if="matchDetail.status === 'partial'"
class="h-3 w-3 text-white"
/>
</div>
<span class="font-medium">
@@ -37,43 +288,55 @@
</div>
<!-- 原始数据 -->
<div class="bg-gray-50 rounded-lg p-4">
<h4 class="font-medium text-gray-800 mb-3">原始数据</h4>
<div class="rounded-lg bg-gray-50 p-4">
<h4 class="mb-3 font-medium text-gray-800">原始数据</h4>
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<span class="text-gray-600">商品名称:</span>
<span class="ml-2 font-medium">{{ matchDetail.originalData.productName }}</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.productName
}}</span>
</div>
<div>
<span class="text-gray-600">订单编号:</span>
<span class="ml-2 font-medium">{{ matchDetail.originalData.orderNumber }}</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.orderNumber
}}</span>
</div>
<div>
<span class="text-gray-600">商品规格:</span>
<span class="ml-2 font-medium">{{ matchDetail.originalData.productSpecName }}</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.productSpecName
}}</span>
</div>
<div>
<span class="text-gray-600">规格编码:</span>
<span class="ml-2 font-medium">{{ matchDetail.originalData.specCode }}</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.specCode
}}</span>
</div>
<div>
<span class="text-gray-600">店铺名称:</span>
<span class="ml-2 font-medium">{{ matchDetail.originalData.shopName }}</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.shopName
}}</span>
</div>
<div>
<span class="text-gray-600">订单状态:</span>
<span class="ml-2 font-medium">{{ matchDetail.originalData.orderStatusName }}</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.orderStatusName
}}</span>
</div>
</div>
</div>
<!-- 当前字段匹配信息 -->
<div class="border rounded-lg p-4">
<div class="flex items-center justify-between mb-3">
<div class="rounded-lg border p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="font-medium text-gray-800">{{ getFieldTitle() }}</h4>
<div class="flex items-center space-x-2">
<div
class="w-3 h-3 rounded-full"
<div
class="h-3 w-3 rounded-full"
:class="getFieldMatchStatusClass()"
></div>
<span class="text-sm">
@@ -81,29 +344,36 @@
</span>
</div>
</div>
<!-- 当前匹配信息 -->
<div v-if="getCurrentMatchInfo()" class="bg-green-50 border border-green-200 rounded p-3 mb-3">
<div
v-if="getCurrentMatchInfo()"
class="mb-3 rounded border border-green-200 bg-green-50 p-3"
>
<div class="text-sm">
<div class="font-medium text-green-800">{{ getCurrentMatchInfo()?.name }}</div>
<div class="text-green-600">ID: {{ getCurrentMatchInfo()?.id }}</div>
<div class="font-medium text-green-800">
{{ getCurrentMatchInfo()?.name }}
</div>
<div class="text-green-600">
ID: {{ getCurrentMatchInfo()?.id }}
</div>
<div v-if="getCurrentMatchInfo()?.specCode" class="text-green-600">
编码: {{ getCurrentMatchInfo()?.specCode }}
</div>
</div>
</div>
<!-- 未匹配信息 -->
<div v-else class="bg-red-50 border border-red-200 rounded p-3 mb-3">
<div v-else class="mb-3 rounded border border-red-200 bg-red-50 p-3">
<div class="text-sm text-red-700">
{{ getFieldName() }} "{{ getFieldValue() }}" 未找到匹配
</div>
</div>
<!-- 匹配选项下拉框 -->
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">
<label class="mb-2 block text-sm font-medium text-gray-700">
选择匹配的{{ getFieldTitle() }}:
</label>
<Select
@@ -114,8 +384,11 @@
@change="(value: any) => handleMatchChange(value)"
/>
</div>
<div v-if="selectedMatchId" class="bg-blue-50 border border-blue-200 rounded p-3">
<div
v-if="selectedMatchId"
class="rounded border border-blue-200 bg-blue-50 p-3"
>
<div class="text-sm">
<div class="font-medium text-blue-800">已选择匹配项</div>
<div class="text-blue-600">ID: {{ selectedMatchId }}</div>
@@ -125,11 +398,15 @@
</div>
<!-- 相同数据提示 -->
<div v-if="sameDataCount && sameDataCount > 1" class="bg-blue-50 border border-blue-200 rounded-lg p-3">
<div
v-if="sameDataCount && sameDataCount > 1"
class="rounded-lg border border-blue-200 bg-blue-50 p-3"
>
<div class="flex items-center space-x-2">
<InfoIcon class="w-4 h-4 text-blue-500" />
<InfoIcon class="h-4 w-4 text-blue-500" />
<span class="text-sm text-blue-800">
检测到 {{ sameDataCount }} 条相同数据,切换匹配将同时应用到所有相同数据
检测到
{{ sameDataCount }} 条相同数据,切换匹配将同时应用到所有相同数据
</span>
</div>
</div>
@@ -138,17 +415,17 @@
<template #footer>
<div class="flex justify-end space-x-2">
<Button @click="handleCancel">关闭</Button>
<Button
type="primary"
@click="handleApplyMatch"
<Button
type="primary"
@click="handleApplyMatch"
:disabled="!selectedMatchId"
>
应用匹配
</Button>
<Button
<Button
v-if="sameDataCount && sameDataCount > 1"
type="primary"
@click="handleApplyToAll"
type="primary"
@click="handleApplyToAll"
:disabled="!selectedMatchId"
>
应用到所有相同数据
@@ -158,218 +435,6 @@
</Modal>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { Modal, Button, Select } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import type { MatchDetail } from '../services/EntityMatchingService'
// 创建图标组件
const CheckIcon = createIconifyIcon('lucide:check')
const XIcon = createIconifyIcon('lucide:x')
const AlertTriangleIcon = createIconifyIcon('lucide:alert-triangle')
const InfoIcon = createIconifyIcon('lucide:info')
interface Props {
visible: boolean
matchDetail: MatchDetail | null
fieldType: 'shop' | 'product' | 'spec' | 'orderStatus'
sameDataCount?: number
}
interface Emits {
(e: 'update:visible', value: boolean): void
(e: 'applyMatch', rowIndex: number, fieldType: string, matchId: string): void
(e: 'applyToAll', rowIndex: number, fieldType: string, matchId: string): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const visible = ref(false)
const selectedMatchId = ref<string>('')
watch(() => props.visible, (newVal) => {
visible.value = newVal
if (newVal && props.matchDetail) {
// 初始化选中的匹配项
selectedMatchId.value = getCurrentMatchId() || ''
}
})
watch(visible, (newVal) => {
emit('update:visible', newVal)
})
const getStatusText = (status: string) => {
switch (status) {
case 'matched':
return '匹配成功'
case 'failed':
return '匹配失败'
case 'partial':
return '部分匹配'
default:
return '未知状态'
}
}
// 获取模态框标题
const getModalTitle = () => {
const titles = {
shop: '店铺匹配切换',
product: '商品匹配切换',
spec: '规格匹配切换',
orderStatus: '订单状态匹配切换'
}
return titles[props.fieldType] || '匹配切换'
}
// 获取字段标题
const getFieldTitle = () => {
const titles = {
shop: '店铺',
product: '商品',
spec: '规格',
orderStatus: '订单状态'
}
return titles[props.fieldType] || '字段'
}
// 获取字段名称
const getFieldName = () => {
const names = {
shop: '店铺',
product: '商品',
spec: '规格',
orderStatus: '订单状态'
}
return names[props.fieldType] || '字段'
}
// 获取字段值
const getFieldValue = () => {
if (!props.matchDetail) return ''
switch (props.fieldType) {
case 'shop':
return props.matchDetail.originalData.shopName
case 'product':
return props.matchDetail.originalData.productName
case 'spec':
return props.matchDetail.originalData.productSpecName
case 'orderStatus':
return props.matchDetail.originalData.orderStatusName
default:
return ''
}
}
// 获取当前匹配信息
const getCurrentMatchInfo = () => {
if (!props.matchDetail) return null
switch (props.fieldType) {
case 'shop':
return props.matchDetail.matchedShop ? {
name: props.matchDetail.matchedShop.name,
id: props.matchDetail.matchedShop.id
} : null
case 'product':
return props.matchDetail.matchedProduct ? {
name: props.matchDetail.matchedProduct.name,
id: props.matchDetail.matchedProduct.id
} : null
case 'spec':
return props.matchDetail.matchedSpec ? {
name: props.matchDetail.matchedSpec.name,
id: props.matchDetail.matchedSpec.id,
specCode: props.matchDetail.matchedSpec.specCode
} : null
case 'orderStatus':
return props.matchDetail.matchedOrderStatusId ? {
name: props.matchDetail.originalData.orderStatusName,
id: props.matchDetail.matchedOrderStatusId
} : null
default:
return null
}
}
// 获取当前匹配ID
const getCurrentMatchId = () => {
const matchInfo = getCurrentMatchInfo()
return matchInfo?.id?.toString() || ''
}
// 获取字段匹配状态样式
const getFieldMatchStatusClass = () => {
const matchInfo = getCurrentMatchInfo()
return matchInfo ? 'bg-green-500' : 'bg-red-500'
}
// 获取字段匹配状态文本
const getFieldMatchStatusText = () => {
const matchInfo = getCurrentMatchInfo()
return matchInfo ? '已匹配' : '未匹配'
}
// 获取匹配选项(模拟数据,实际应该从API获取)
const getMatchOptions = () => {
// 这里应该根据fieldType从API获取可选的匹配项
// 暂时返回模拟数据
const mockOptions = {
shop: [
{ label: '锐泽创意家居', value: '123' },
{ label: '其他店铺1', value: '124' },
{ label: '其他店铺2', value: '125' }
],
product: [
{ label: '创意台灯', value: '456' },
{ label: '其他商品1', value: '457' },
{ label: '其他商品2', value: '458' }
],
spec: [
{ label: '白色', value: '789' },
{ label: '黑色', value: '790' },
{ label: '红色', value: '791' }
],
orderStatus: [
{ label: '已发货,待收货', value: '1' },
{ label: '未发货,退款成功', value: '2' },
{ label: '已取消', value: '3' }
]
}
return mockOptions[props.fieldType] || []
}
// 处理匹配选择变化
const handleMatchChange = (value: string) => {
selectedMatchId.value = value
}
// 处理应用匹配
const handleApplyMatch = () => {
if (props.matchDetail && selectedMatchId.value) {
emit('applyMatch', props.matchDetail.rowIndex, props.fieldType, selectedMatchId.value)
}
visible.value = false
}
// 处理应用到所有相同数据
const handleApplyToAll = () => {
if (props.matchDetail && selectedMatchId.value) {
emit('applyToAll', props.matchDetail.rowIndex, props.fieldType, selectedMatchId.value)
}
visible.value = false
}
const handleCancel = () => {
visible.value = false
}
</script>
<style scoped>
/* 自定义样式 */
</style>
File diff suppressed because it is too large Load Diff
@@ -3,11 +3,15 @@
* 用于匹配CSV数据中的实体(店铺、商品、规格、订单状态)到数据库中的ID
*/
import { getShopsByNamesApi } from '#/api/shop/shop';
import { getProductsByNamesApi, getProductSpecsByProductAndSpecsApi } from '#/api/shop/product';
import type { OrderDTO} from '#/api/ecommerce/types';
import type { ShopVO } from '#/api/shop/shop/types';
import type { OrderDTO } from '#/api/ecommerce/types';
import type { ProductVO } from '#/api/shop/product/types';
import type { ShopVO } from '#/api/shop/shop/types';
import {
getProductsByNamesApi,
getProductSpecsByProductAndSpecsApi,
} from '#/api/shop/product';
import { getShopsByNamesApi } from '#/api/shop/shop';
export interface EntityMatchingResult {
/** 匹配成功的订单数据 */
@@ -16,8 +20,8 @@ export interface EntityMatchingResult {
failedRecords: FailedRecord[];
/** 需要创建的实体 */
entitiesToCreate: {
shops: string[];
products: string[];
shops: string[];
specs: { productName: string; specCode: string }[];
};
/** 匹配详情信息 */
@@ -30,7 +34,7 @@ export interface MatchDetail {
/** 原始数据 */
originalData: CSVOrderData;
/** 匹配状态 */
status: 'matched' | 'failed' | 'partial';
status: 'failed' | 'matched' | 'partial';
/** 匹配的店铺信息 */
matchedShop?: ShopVO.Info;
/** 匹配的商品信息 */
@@ -74,15 +78,277 @@ export interface CSVOrderData {
}
export class EntityMatchingService {
private shopCache: Map<string, ShopVO.Info> = new Map();
private productCache: Map<string, ProductVO.Info> = new Map();
private specCache: Map<string, ProductVO.SpecInfo> = new Map();
private orderStatusMap: Map<string, number> = new Map();
private productCache: Map<string, ProductVO.Info> = new Map();
private shopCache: Map<string, ShopVO.Info> = new Map();
private specCache: Map<string, ProductVO.SpecInfo> = new Map();
constructor() {
this.initializeOrderStatusMap();
}
/**
* 获取订单状态ID
*/
getOrderStatusId(statusName: string): number | undefined {
return this.orderStatusMap.get(statusName);
}
/**
* 获取商品信息
*/
getProductByName(name: string): ProductVO.Info | undefined {
return this.productCache.get(name);
}
/**
* 获取商品规格信息
*/
getProductSpecByKey(
productName: string,
specCode: string,
): ProductVO.SpecInfo | undefined {
const key = `${productName}_${specCode}`;
return this.specCache.get(key);
}
/**
* 获取店铺信息
*/
getShopByName(name: string): ShopVO.Info | undefined {
return this.shopCache.get(name);
}
/**
* 匹配实体并生成订单数据
*/
async matchEntities(csvData: CSVOrderData[]): Promise<EntityMatchingResult> {
// 清空缓存
this.clearCache();
// 提取所有需要查询的实体名称
const shopNames = [...new Set(csvData.map((row) => row.shopName))];
const productNames = [...new Set(csvData.map((row) => row.productName))];
// 对规格查询进行去重处理
const specQueriesMap = new Map<
string,
{ productName: string; specCode: string }
>();
csvData.forEach((row) => {
const key = `${row.productName}_${row.specCode}`;
if (!specQueriesMap.has(key)) {
specQueriesMap.set(key, {
productName: row.productName,
specCode: row.specCode,
});
}
});
const specQueries = [...specQueriesMap.values()];
// 批量查询所有实体
await this.loadEntitiesBatch(shopNames, productNames, specQueries);
const matchedOrders: OrderDTO.Create[] = [];
const failedRecords: FailedRecord[] = [];
const matchDetails: MatchDetail[] = [];
const entitiesToCreate = {
shops: new Set<string>(),
products: new Set<string>(),
specs: new Set<{ productName: string; specCode: string }>(),
};
for (const [i, row] of csvData.entries()) {
// 检查行数据是否存在
if (!row) {
const failedRecord = {
rowIndex: i + 1,
originalData: null,
reason: '行数据为空',
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row || ({} as CSVOrderData),
status: 'failed',
failureReason: '行数据为空',
});
continue;
}
try {
// 匹配店铺
const shop = this.shopCache.get(row.shopName);
if (!shop) {
entitiesToCreate.shops.add(row.shopName);
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `店铺 "${row.shopName}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
failureReason: `店铺 "${row.shopName}" 不存在`,
});
continue;
}
// 匹配商品
const product = this.productCache.get(row.productName);
if (!product) {
entitiesToCreate.products.add(row.productName);
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `商品 "${row.productName}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
failureReason: `商品 "${row.productName}" 不存在`,
});
continue;
}
// 匹配商品规格
const specKey = `${row.productName}_${row.specCode}`;
const spec = this.specCache.get(specKey);
if (!spec) {
entitiesToCreate.specs.add({
productName: row.productName,
specCode: row.specCode,
});
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `商品规格 "${row.productName}" - "${row.specCode}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
matchedProduct: product,
failureReason: `商品规格 "${row.productName}" - "${row.specCode}" 不存在`,
});
continue;
}
// 匹配订单状态
const orderStatusId = this.orderStatusMap.get(row.orderStatusName);
if (!orderStatusId) {
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `订单状态 "${row.orderStatusName}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
matchedProduct: product,
matchedSpec: spec,
failureReason: `订单状态 "${row.orderStatusName}" 不存在`,
});
continue;
}
// 从订单号中提取日期信息(格式:250913-341248633251447,前6位是日期)
let orderDate = new Date().toISOString(); // 默认使用当前时间
if (row.orderNumber && row.orderNumber.length >= 6) {
try {
const dateStr = row.orderNumber.slice(0, 6); // 提取前6位
const year = `20${dateStr.slice(0, 2)}`; // 25 -> 2025
const month = dateStr.slice(2, 4); // 09
const day = dateStr.slice(4, 6); // 13
orderDate = new Date(
`${year}-${month}-${day}T00:00:00`,
).toISOString();
} catch {
console.warn(
'无法解析订单号中的日期,使用当前时间:',
row.orderNumber,
);
}
}
// 创建订单数据(新的合并结构)
const orderData: OrderDTO.Create = {
shopId: shop.id,
platformOrderNo: row.orderNumber,
statusId: orderStatusId,
receivedAmount: row.shopActualAmount,
shippingFee: 0, // 运费暂时设为0
orderDate,
productId: product.id,
productSpecId: spec.id,
productName: row.productName,
specName: row.productSpecName,
quantity: row.quantity,
unitPrice: row.shopActualAmount / row.quantity, // 根据实收金额和数量计算单价
costPrice: spec.costPrice || 0, // 使用规格的成本价
costTotal: (spec.costPrice || 0) * row.quantity, // 成本小计
};
matchedOrders.push(orderData);
// 添加匹配成功的详情
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'matched',
matchedShop: shop,
matchedProduct: product,
matchedSpec: spec,
matchedOrderStatusId: orderStatusId,
orderData,
});
} catch (error) {
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `处理失败: ${error instanceof Error ? error.message : '未知错误'}`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
failureReason: `处理失败: ${error instanceof Error ? error.message : '未知错误'}`,
});
}
}
return {
matchedOrders,
failedRecords,
entitiesToCreate: {
shops: [...entitiesToCreate.shops],
products: [...entitiesToCreate.products],
specs: [...entitiesToCreate.specs],
},
matchDetails,
};
}
/**
* 清空缓存
*/
private clearCache(): void {
this.shopCache.clear();
this.productCache.clear();
this.specCache.clear();
}
/**
* 初始化订单状态映射
*/
@@ -96,249 +362,46 @@ export class EntityMatchingService {
// 可以根据需要添加更多状态映射
}
/**
* 匹配实体并生成订单数据
*/
async matchEntities(csvData: CSVOrderData[]): Promise<EntityMatchingResult> {
// 清空缓存
this.clearCache();
// 提取所有需要查询的实体名称
const shopNames = [...new Set(csvData.map(row => row.shopName))];
const productNames = [...new Set(csvData.map(row => row.productName))];
// 对规格查询进行去重处理
const specQueriesMap = new Map<string, { productName: string; specCode: string }>();
csvData.forEach(row => {
const key = `${row.productName}_${row.specCode}`;
if (!specQueriesMap.has(key)) {
specQueriesMap.set(key, { productName: row.productName, specCode: row.specCode });
}
});
const specQueries = Array.from(specQueriesMap.values());
// 批量查询所有实体
await this.loadEntitiesBatch(shopNames, productNames, specQueries);
const matchedOrders: OrderDTO.Create[] = [];
const failedRecords: FailedRecord[] = [];
const matchDetails: MatchDetail[] = [];
const entitiesToCreate = {
shops: new Set<string>(),
products: new Set<string>(),
specs: new Set<{ productName: string; specCode: string }>()
};
for (let i = 0; i < csvData.length; i++) {
const row = csvData[i];
// 检查行数据是否存在
if (!row) {
const failedRecord = {
rowIndex: i + 1,
originalData: null,
reason: '行数据为空'
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row || {} as CSVOrderData,
status: 'failed',
failureReason: '行数据为空'
});
continue;
}
try {
// 匹配店铺
const shop = this.shopCache.get(row.shopName);
if (!shop) {
entitiesToCreate.shops.add(row.shopName);
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `店铺 "${row.shopName}" 不存在`
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
failureReason: `店铺 "${row.shopName}" 不存在`
});
continue;
}
// 匹配商品
const product = this.productCache.get(row.productName);
if (!product) {
entitiesToCreate.products.add(row.productName);
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `商品 "${row.productName}" 不存在`
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
failureReason: `商品 "${row.productName}" 不存在`
});
continue;
}
// 匹配商品规格
const specKey = `${row.productName}_${row.specCode}`;
const spec = this.specCache.get(specKey);
if (!spec) {
entitiesToCreate.specs.add({ productName: row.productName, specCode: row.specCode });
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `商品规格 "${row.productName}" - "${row.specCode}" 不存在`
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
matchedProduct: product,
failureReason: `商品规格 "${row.productName}" - "${row.specCode}" 不存在`
});
continue;
}
// 匹配订单状态
const orderStatusId = this.orderStatusMap.get(row.orderStatusName);
if (!orderStatusId) {
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `订单状态 "${row.orderStatusName}" 不存在`
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
matchedProduct: product,
matchedSpec: spec,
failureReason: `订单状态 "${row.orderStatusName}" 不存在`
});
continue;
}
// 从订单号中提取日期信息(格式:250913-341248633251447,前6位是日期)
let orderDate = new Date().toISOString(); // 默认使用当前时间
if (row.orderNumber && row.orderNumber.length >= 6) {
try {
const dateStr = row.orderNumber.substring(0, 6); // 提取前6位
const year = '20' + dateStr.substring(0, 2); // 25 -> 2025
const month = dateStr.substring(2, 4); // 09
const day = dateStr.substring(4, 6); // 13
orderDate = new Date(`${year}-${month}-${day}T00:00:00`).toISOString();
} catch (error) {
console.warn('无法解析订单号中的日期,使用当前时间:', row.orderNumber);
}
}
// 创建订单数据(新的合并结构)
const orderData: OrderDTO.Create = {
shopId: shop.id,
platformOrderNo: row.orderNumber,
statusId: orderStatusId,
receivedAmount: row.shopActualAmount,
shippingFee: 0, // 运费暂时设为0
orderDate: orderDate,
productId: product.id,
productSpecId: spec.id,
productName: row.productName,
specName: row.productSpecName,
quantity: row.quantity,
unitPrice: row.shopActualAmount / row.quantity, // 根据实收金额和数量计算单价
costPrice: spec.costPrice || 0, // 使用规格的成本价
costTotal: (spec.costPrice || 0) * row.quantity, // 成本小计
};
matchedOrders.push(orderData);
// 添加匹配成功的详情
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'matched',
matchedShop: shop,
matchedProduct: product,
matchedSpec: spec,
matchedOrderStatusId: orderStatusId,
orderData: orderData
});
} catch (error) {
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `处理失败: ${error instanceof Error ? error.message : '未知错误'}`
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
failureReason: `处理失败: ${error instanceof Error ? error.message : '未知错误'}`
});
}
}
return {
matchedOrders,
failedRecords,
entitiesToCreate: {
shops: Array.from(entitiesToCreate.shops),
products: Array.from(entitiesToCreate.products),
specs: Array.from(entitiesToCreate.specs)
},
matchDetails
};
}
/**
* 批量加载实体数据
*/
private async loadEntitiesBatch(
shopNames: string[],
productNames: string[],
specQueries: { productName: string; specCode: string }[]
shopNames: string[],
productNames: string[],
specQueries: { productName: string; specCode: string }[],
): Promise<void> {
try {
// 并行查询所有实体
const [shops, products, productsWithSpecs] = await Promise.all([
shopNames.length > 0 ? getShopsByNamesApi(shopNames) : Promise.resolve([]),
productNames.length > 0 ? getProductsByNamesApi(productNames) : Promise.resolve([]),
specQueries.length > 0 ? getProductSpecsByProductAndSpecsApi(specQueries) : Promise.resolve([])
shopNames.length > 0
? getShopsByNamesApi(shopNames)
: Promise.resolve([]),
productNames.length > 0
? getProductsByNamesApi(productNames)
: Promise.resolve([]),
specQueries.length > 0
? getProductSpecsByProductAndSpecsApi(specQueries)
: Promise.resolve([]),
]);
// 缓存店铺数据
shops.forEach(shop => {
shops.forEach((shop) => {
this.shopCache.set(shop.name, shop);
});
// 缓存商品数据
products.forEach(product => {
products.forEach((product) => {
this.productCache.set(product.name, product);
});
// 缓存包含规格信息的商品数据
productsWithSpecs.forEach(product => {
productsWithSpecs.forEach((product) => {
// 更新商品缓存
this.productCache.set(product.name, product);
// 缓存该商品的规格数据
if (product.specs && product.specs.length > 0) {
product.specs.forEach(spec => {
product.specs.forEach((spec) => {
const key = `${product.name}_${spec.specCode || ''}`;
this.specCache.set(key, spec);
});
@@ -348,42 +411,4 @@ export class EntityMatchingService {
console.error('批量加载实体数据失败:', error);
}
}
/**
* 清空缓存
*/
private clearCache(): void {
this.shopCache.clear();
this.productCache.clear();
this.specCache.clear();
}
/**
* 获取店铺信息
*/
getShopByName(name: string): ShopVO.Info | undefined {
return this.shopCache.get(name);
}
/**
* 获取商品信息
*/
getProductByName(name: string): ProductVO.Info | undefined {
return this.productCache.get(name);
}
/**
* 获取商品规格信息
*/
getProductSpecByKey(productName: string, specCode: string): ProductVO.SpecInfo | undefined {
const key = `${productName}_${specCode}`;
return this.specCache.get(key);
}
/**
* 获取订单状态ID
*/
getOrderStatusId(statusName: string): number | undefined {
return this.orderStatusMap.get(statusName);
}
}
@@ -46,13 +46,11 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'UTF-8', 'GB2312'];
let result: Papa.ParseResult<any> | null = null;
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: null | Papa.ParseResult<any> = null;
for (const encoding of encodings) {
try {
console.log(`尝试使用${encoding}编码解析文件...`);
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
@@ -63,24 +61,22 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
},
error: (error) => {
reject(error);
}
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(value =>
typeof value === 'string' && /[\u4e00-\u9fa5]/.test(value)
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
console.log(`成功使用${encoding}编码解析文件`);
break;
}
}
} catch (error) {
console.log(`使用${encoding}编码解析失败:`, error);
} catch {
continue;
}
}
@@ -91,7 +87,9 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
}
if (result.errors.length > 0) {
errors.push(`CSV解析错误: ${result.errors.map(e => e.message).join(', ')}`);
errors.push(
`CSV解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
@@ -101,23 +99,32 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
// 获取表头
headers = result.meta.fields || [];
console.log('解析到的表头:', headers);
// 验证表头 - 使用更灵活的表头匹配
const requiredHeaders = ['商品', '订单号', '订单状态', '商品数量(件)', '商品id', '商品规格', '商家编码-规格维度', '售后状态', '商家实收金额(元)'];
const missingHeaders = requiredHeaders.filter(requiredHeader => {
// 检查是否有匹配的表头(支持部分匹配)
return !headers.some(header =>
header.includes(requiredHeader) || requiredHeader.includes(header)
);
});
// 验证表头 - 使用更灵活的表头匹配
const requiredHeaders = [
'商品',
'订单号',
'订单状态',
'商品数量(件)',
'商品id',
'商品规格',
'商家编码-规格维度',
'售后状态',
'商家实收金额(元)',
];
const missingHeaders = requiredHeaders.filter((requiredHeader) => {
// 检查是否有匹配的表头(支持部分匹配)
return !headers.some(
(header) =>
header.includes(requiredHeader) || requiredHeader.includes(header),
);
});
if (missingHeaders.length > 0) {
console.log('缺少的列:', missingHeaders);
console.log('实际表头:', headers);
console.log('期望表头:', requiredHeaders);
// 不再阻止导入,只是记录警告
errors.push(`警告:缺少部分列: ${missingHeaders.join(', ')},可以在导入后手动处理`);
errors.push(
`警告:缺少部分列: ${missingHeaders.join(', ')},可以在导入后手动处理`,
);
}
// 解析数据行
@@ -129,8 +136,9 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
data.push(rowData);
}
} catch (error) {
errors.push(`第${i + 2}行解析失败: ${error instanceof Error ? error.message : '未知错误'}`);
console.log(`第${i + 2}行解析错误:`, error);
errors.push(
`第${i + 2}行解析失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
@@ -140,12 +148,19 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
/**
* 解析订单行数据 - 从papaparse对象格式
*/
function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData | null {
function parseOrderRowFromObject(
row: any,
rowNumber: number,
): null | ParsedOrderData {
try {
// 获取字段值,支持多种可能的字段名
const getValue = (fieldNames: string[]): string => {
for (const fieldName of fieldNames) {
if (row[fieldName] !== undefined && row[fieldName] !== null && row[fieldName] !== '') {
if (
row[fieldName] !== undefined &&
row[fieldName] !== null &&
row[fieldName] !== ''
) {
return String(row[fieldName]).trim();
}
}
@@ -155,13 +170,29 @@ function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData |
const productName = getValue(['商品', '商品名称', 'productName']);
const orderNumber = getValue(['订单号', '订单编号', 'orderNumber']);
const orderStatusName = getValue(['订单状态', 'orderStatus', '状态']);
const quantityStr = getValue(['商品数量(件)', '商品数量', '数量', 'quantity']);
const quantityStr = getValue([
'商品数量(件)',
'商品数量',
'数量',
'quantity',
]);
const productId = getValue(['商品id', '商品ID', 'productId', '商品编码']);
const productSpecName = getValue(['商品规格', '规格', 'spec', 'productSpec']);
const productSpecName = getValue([
'商品规格',
'规格',
'spec',
'productSpec',
]);
const specCode = getValue(['商家编码-规格维度', '规格编码', 'specCode']);
// 店铺名称应该从文件名获取,这里不设置shopName
const afterSaleStatus = getValue(['售后状态', '售后', 'afterSale']);
const shopActualAmountStr = getValue(['商家实收金额(元)', '店铺实际收入(元)', '店铺实际收入', '收入', 'amount']);
const shopActualAmountStr = getValue([
'商家实收金额(元)',
'店铺实际收入(元)',
'店铺实际收入',
'收入',
'amount',
]);
// 验证必填字段 - 只验证最核心的字段
if (!productName) {
@@ -170,14 +201,14 @@ function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData |
if (!orderNumber) {
throw new Error('订单编号不能为空');
}
// 其他字段可以为空,在后续处理中处理
// 解析数量 - 允许为0或空
const quantity = parseFloat(quantityStr) || 0;
const quantity = Number.parseFloat(quantityStr) || 0;
// 解析金额 - 允许为0或空
const shopActualAmount = parseFloat(shopActualAmountStr) || 0;
const shopActualAmount = Number.parseFloat(shopActualAmountStr) || 0;
return {
productName,
@@ -192,7 +223,9 @@ function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData |
shopActualAmount,
};
} catch (error) {
throw new Error(`第${rowNumber}行数据验证失败: ${error instanceof Error ? error.message : '未知错误'}`);
throw new Error(
`第${rowNumber}行数据验证失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
@@ -207,8 +240,11 @@ export function extractShopNameFromFilename(filename: string): string {
/**
* 转换为EntityMatchingService需要的格式
*/
export function convertToCSVOrderData(parsedData: ParsedOrderData[], shopName: string): any[] {
return parsedData.map(row => ({
export function convertToCSVOrderData(
parsedData: ParsedOrderData[],
shopName: string,
): any[] {
return parsedData.map((row) => ({
productName: row.productName,
orderNumber: row.orderNumber,
orderStatusName: row.orderStatusName,
@@ -216,8 +252,8 @@ export function convertToCSVOrderData(parsedData: ParsedOrderData[], shopName: s
productId: row.productId,
productSpecName: row.productSpecName,
specCode: row.specCode,
shopName: shopName, // 使用从文件名提取的店铺名称
shopName, // 使用从文件名提取的店铺名称
afterSaleStatus: row.afterSaleStatus,
shopActualAmount: row.shopActualAmount
shopActualAmount: row.shopActualAmount,
}));
}
@@ -1,3 +1,86 @@
<script setup lang="ts">
import type { FileDTO, FileVO } from '#/api/media/file/types';
import { ref, watch } from 'vue';
import { Form, Input, message, Modal } from 'ant-design-vue';
import { updateFileApi } from '#/api/media/file';
defineOptions({ name: 'FileEditModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// Props
interface Props {
open: boolean;
fileData?: FileVO.Info | null;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
// 响应式数据
const visible = ref(false);
const formRef = ref();
const formData = ref<FileDTO.Update>({
tags: '',
remark: '',
});
// 监听props变化
watch(
() => props.open,
(newVal) => {
visible.value = newVal;
if (newVal && props.fileData) {
// 填充表单数据
formData.value = {
tags: props.fileData.tags,
remark: props.fileData.remark,
};
}
},
);
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal);
});
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (props.fileData?.id) {
await updateFileApi(props.fileData.id, formData.value);
message.success('更新成功');
emit('success');
visible.value = false;
}
} catch {
message.error('更新失败');
}
};
// 取消操作
const handleCancel = () => {
emit('cancel');
visible.value = false;
// 重置表单数据
formData.value = {
tags: '',
remark: '',
};
};
</script>
<template>
<Modal
v-model:open="visible"
@@ -27,79 +110,3 @@
</Form>
</Modal>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { Modal, Form, Input, message } from 'ant-design-vue'
import { updateFileApi } from '#/api/media/file'
import type { FileDTO, FileVO } from '#/api/media/file/types'
defineOptions({ name: 'FileEditModal' })
// Props
interface Props {
open: boolean
fileData?: FileVO.Info | null
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void
(e: 'success'): void
(e: 'cancel'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
// 响应式数据
const visible = ref(false)
const formRef = ref()
const formData = ref<FileDTO.Update>({
tags: '',
remark: '',
})
// 监听props变化
watch(() => props.open, (newVal) => {
visible.value = newVal
if (newVal && props.fileData) {
// 填充表单数据
formData.value = {
tags: props.fileData.tags,
remark: props.fileData.remark,
}
}
})
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal)
})
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate()
if (props.fileData?.id) {
await updateFileApi(props.fileData.id, formData.value)
message.success('更新成功')
emit('success')
visible.value = false
}
} catch (error) {
message.error('更新失败')
}
}
// 取消操作
const handleCancel = () => {
emit('cancel')
visible.value = false
// 重置表单数据
formData.value = {
tags: '',
remark: '',
}
}
</script>
@@ -1,21 +1,34 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { FileDTO, FileVO } from '#/api/media/file/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import {
Button,
Upload,
message,
Tag,
Space,
Popconfirm,
Tooltip
} from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
message,
Popconfirm,
Space,
Tag,
Tooltip,
Upload,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
batchUploadFilesApi,
deleteFileApi,
getFilePageApi,
uploadFileApi,
} from '#/api/media/file';
import FileEditModal from './components/FileEditModal.vue';
defineOptions({ name: 'FileRepository' });
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const DeleteIcon = createIconifyIcon('lucide:trash-2');
@@ -23,17 +36,6 @@ const EditIcon = createIconifyIcon('lucide:edit');
const DownloadIcon = createIconifyIcon('lucide:download');
const EyeIcon = createIconifyIcon('lucide:eye');
import {
uploadFileApi,
batchUploadFilesApi,
deleteFileApi,
getFilePageApi,
} from '#/api/media/file';
import type { FileVO, FileDTO } from '#/api/media/file/types';
import type { PageQueryDTO } from '#/types/common';
defineOptions({ name: 'FileRepository' });
// 响应式数据
const loading = ref(false);
const fileList = ref<FileVO.Info[]>([]);
@@ -48,7 +50,6 @@ const searchForm = ref({
fileFormat: undefined as string | undefined,
});
// 文件格式选项
const fileFormatOptions = [
{ label: 'PDF', value: 'pdf' },
@@ -117,7 +118,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -195,7 +214,7 @@ const handleUpload = async (file: File) => {
await uploadFileApi(file);
message.success('文件上传成功');
refreshTable();
} catch (error) {
} catch {
message.error('文件上传失败');
} finally {
uploadLoading.value = false;
@@ -208,7 +227,7 @@ const handleBatchUpload = async (files: File[]) => {
await batchUploadFilesApi(files);
message.success(`成功上传 ${files.length} 个文件`);
refreshTable();
} catch (error) {
} catch {
message.error('批量上传失败');
} finally {
uploadLoading.value = false;
@@ -236,7 +255,7 @@ const handleDelete = async (id: number) => {
await deleteFileApi(id);
message.success('删除成功');
refreshTable();
} catch (error) {
} catch {
message.error('删除失败');
}
};
@@ -300,8 +319,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- 文件名列 -->
<template #filename="{ row }: { row: any }">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-weight: 500;">{{ row.filename }}</span>
<div style="display: flex; align-items: center; gap: 8px">
<span style="font-weight: 500">{{ row.filename }}</span>
<Tag color="blue" size="small">{{ row.fileFormat || '未知' }}</Tag>
</div>
</template>
@@ -313,12 +332,12 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- 标签列 -->
<template #tags="{ row }: { row: any }">
<div v-if="!row.tags" style="color: #999;">无标签</div>
<div v-else style="display: flex; flex-wrap: wrap; gap: 4px;">
<Tag
v-for="tag in row.tags.split(',').filter((t: string) => t.trim())"
:key="tag"
color="green"
<div v-if="!row.tags" style="color: #999">无标签</div>
<div v-else style="display: flex; flex-wrap: wrap; gap: 4px">
<Tag
v-for="tag in row.tags.split(',').filter((t: string) => t.trim())"
:key="tag"
color="green"
size="small"
>
{{ tag.trim() }}
@@ -329,11 +348,19 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- 描述列 -->
<template #remark="{ row }: { row: any }">
<Tooltip v-if="row.remark" :title="row.remark">
<span style="display: block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
<span
style="
display: block;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
"
>
{{ row.remark }}
</span>
</Tooltip>
<span v-else style="color: #999;">无描述</span>
<span v-else style="color: #999">无描述</span>
</template>
<!-- 操作列 -->
@@ -341,23 +368,26 @@ const [Grid, gridApi] = useVbenVxeGrid({
<Space>
<Tooltip title="预览">
<Button type="text" size="small" @click="handlePreview(row)">
<EyeIcon class="w-4 h-4" />
<EyeIcon class="h-4 w-4" />
</Button>
</Tooltip>
<Tooltip title="下载">
<Button type="text" size="small" @click="handleDownload(row)">
<DownloadIcon class="w-4 h-4" />
<DownloadIcon class="h-4 w-4" />
</Button>
</Tooltip>
<Tooltip title="编辑">
<Button type="text" size="small" @click="handleEdit(row)">
<EditIcon class="w-4 h-4" />
<EditIcon class="h-4 w-4" />
</Button>
</Tooltip>
<Popconfirm title="确定要删除这个文件吗?" @confirm="handleDelete(row.id)">
<Popconfirm
title="确定要删除这个文件吗?"
@confirm="handleDelete(row.id)"
>
<Tooltip title="删除">
<Button type="text" size="small" danger>
<DeleteIcon class="w-4 h-4" />
<DeleteIcon class="h-4 w-4" />
</Button>
</Tooltip>
</Popconfirm>
@@ -1,123 +0,0 @@
<script lang="ts" setup>
import { Card, Image, Tag, Button, Space, Popconfirm } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import type { ImageVO } from '#/api/media/image/types';
// 创建图标组件
const DownloadIcon = createIconifyIcon('lucide:download');
const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2');
interface Props {
image: ImageVO.Info;
}
interface Emits {
(e: 'download', image: ImageVO.Info): void;
(e: 'edit', image: ImageVO.Info): void;
(e: 'delete', id: number): void;
}
defineProps<Props>();
const emit = defineEmits<Emits>();
const handleDownload = (image: ImageVO.Info) => {
emit('download', image);
};
const handleEdit = (image: ImageVO.Info) => {
emit('edit', image);
};
const handleDelete = (id: number) => {
emit('delete', id);
};
const getTagColor = (category: string | undefined) => {
switch (category) {
case 'image':
return 'blue';
case 'avatar':
return 'green';
case 'logo':
return 'purple';
default:
return '#006BE6';
}
};
</script>
<template>
<Card
hoverable
:body-style="{ padding: '8px' }"
class="image-card"
>
<div class="relative overflow-hidden">
<Image
:src="image.url"
:alt="image.filename"
class="w-full h-32 object-cover rounded"
:preview="true"
/>
<div v-if="image.tags" class="absolute top-2 right-2 max-w-[calc(100%-16px)]">
<Tag
:color="getTagColor(image.category)"
class="max-w-full truncate"
:title="image.tags"
>
{{ image.tags }}
</Tag>
</div>
</div>
<div class="mt-2">
<div class="text-sm font-medium truncate" :title="image.filename">
{{ image.filename || '未命名' }}
</div>
<div class="text-xs text-gray-500 mt-1">
{{ image.uploadTime }}
</div>
<div class="flex justify-between items-center mt-2">
<Space size="small">
<Button
type="text"
size="small"
@click="handleDownload(image)"
>
<DownloadIcon class="w-4 h-4" />
</Button>
<Button
type="text"
size="small"
@click="handleEdit(image)"
>
<EditIcon class="w-4 h-4" />
</Button>
<Popconfirm
title="确定要删除这张图片吗?"
@confirm="handleDelete(image.id)"
>
<Button
type="text"
size="small"
danger
>
<TrashIcon class="w-4 h-4" />
</Button>
</Popconfirm>
</Space>
</div>
</div>
</Card>
</template>
<style scoped>
.image-card {
transition: all 0.3s ease;
}
.image-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
@@ -1,3 +1,86 @@
<script setup lang="ts">
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import { ref, watch } from 'vue';
import { Form, Input, message, Modal } from 'ant-design-vue';
import { updateImageApi } from '#/api/media/image';
defineOptions({ name: 'ImageEditModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// Props
interface Props {
open: boolean;
imageData?: ImageVO.Info | null;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
// 响应式数据
const visible = ref(false);
const formRef = ref();
const formData = ref<ImageDTO.Update>({
tags: '',
remark: '',
});
// 监听props变化
watch(
() => props.open,
(newVal) => {
visible.value = newVal;
if (newVal && props.imageData) {
// 填充表单数据
formData.value = {
tags: props.imageData.tags,
remark: props.imageData.remark,
};
}
},
);
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal);
});
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (props.imageData?.id) {
await updateImageApi(props.imageData.id, formData.value);
message.success('更新成功');
emit('success');
visible.value = false;
}
} catch {
message.error('更新失败');
}
};
// 取消操作
const handleCancel = () => {
emit('cancel');
visible.value = false;
// 重置表单数据
formData.value = {
tags: '',
remark: '',
};
};
</script>
<template>
<Modal
v-model:open="visible"
@@ -27,80 +110,3 @@
</Form>
</Modal>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { Modal, Form, Input, message } from 'ant-design-vue'
import { updateImageApi } from '#/api/media/image'
import type { ImageDTO, ImageVO } from '#/api/media/image/types'
defineOptions({ name: 'ImageEditModal' })
// Props
interface Props {
open: boolean
imageData?: ImageVO.Info | null
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void
(e: 'success'): void
(e: 'cancel'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
// 响应式数据
const visible = ref(false)
const formRef = ref()
const formData = ref<ImageDTO.Update>({
tags: '',
remark: '',
})
// 监听props变化
watch(() => props.open, (newVal) => {
visible.value = newVal
if (newVal && props.imageData) {
// 填充表单数据
formData.value = {
tags: props.imageData.tags,
remark: props.imageData.remark,
}
}
})
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal)
})
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate()
if (props.imageData?.id) {
await updateImageApi(props.imageData.id, formData.value)
message.success('更新成功')
emit('success')
visible.value = false
}
} catch (error) {
message.error('更新失败')
}
}
// 取消操作
const handleCancel = () => {
emit('cancel')
visible.value = false
// 重置表单数据
formData.value = {
tags: '',
remark: '',
}
}
</script>
@@ -1,272 +0,0 @@
<template>
<div class="image-grid-view h-full">
<!-- 工具栏 -->
<div class="mb-4 flex justify-between items-center">
<div class="flex items-center gap-4">
<Upload v-bind="uploadProps">
<Button type="primary" :loading="uploadLoading">
<UploadIcon class="w-4 h-4 mr-2" />
上传图片
</Button>
</Upload>
<span class="text-gray-500">支持批量上传,单个图片最大10MB</span>
</div>
<div class="text-gray-500">
共 {{ total }} 张图片
</div>
</div>
<!-- 搜索区域 -->
<div class="mb-4 p-4 bg-white rounded-lg shadow-sm">
<Form :model="searchForm" layout="inline">
<Form.Item label="文件名">
<Input
v-model:value="searchForm.filename"
placeholder="请输入文件名"
style="width: 200px"
@press-enter="handleSearch"
/>
</Form.Item>
<Form.Item label="图片分类">
<Select
v-model:value="searchForm.category"
placeholder="请选择图片分类"
style="width: 150px"
allow-clear
>
<Select.Option
v-for="option in categoryOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" @click="handleSearch">搜索</Button>
<Button @click="handleReset">重置</Button>
</Space>
</Form.Item>
</Form>
</div>
<!-- 网格内容 -->
<div class="bg-white rounded-lg shadow-sm p-4">
<Row :gutter="[16, 16]" v-loading="loading">
<Col
v-for="image in imageList"
:key="image.id"
:xs="12"
:sm="8"
:md="6"
:lg="4"
:xl="3"
>
<ImageCard
:image="image"
@download="handleDownload"
@edit="handleEdit"
@delete="handleDelete"
@preview="handlePreview"
/>
</Col>
</Row>
<!-- 空状态 -->
<div v-if="!loading && imageList.length === 0" class="text-center py-12">
<div class="text-gray-400 text-lg">暂无图片数据</div>
<div class="text-gray-400 text-sm mt-2">请上传图片或调整搜索条件</div>
</div>
<!-- 分页 -->
<div v-if="total > 0" class="mt-4 flex justify-center">
<Pagination
v-model:current="current"
v-model:page-size="pageSize"
:total="total"
:page-size-options="['12', '24', '48', '96']"
show-size-changer
show-quick-jumper
:show-total="(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`"
@change="handlePageChange"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { Form, Input, Select, Button, Space, Row, Col, Pagination, Upload, message } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import { getImagePageApi, uploadImageApi, batchUploadImagesApi } from '#/api/media/image'
import type { ImageVO, ImageDTO } from '#/api/media/image/types'
import type { PageQueryDTO } from '#/types/common'
import ImageCard from './ImageCard.vue'
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload')
defineOptions({ name: 'ImageGridView' })
// Props
interface Props {
searchForm: {
filename: string
category?: string
}
categoryOptions: Array<{ label: string; value: string }>
}
// Emits
interface Emits {
(e: 'edit', image: ImageVO.Info): void
(e: 'delete', id: number): void
(e: 'download', image: ImageVO.Info): void
(e: 'preview', image: ImageVO.Info): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
// 响应式数据
const loading = ref(false)
const uploadLoading = ref(false)
const imageList = ref<ImageVO.Info[]>([])
const total = ref(0)
const current = ref(1)
const pageSize = ref(24) // 网格视图默认24个
// 监听搜索表单变化
watch(() => props.searchForm, () => {
current.value = 1
loadImageList()
}, { deep: true })
// 加载图片列表
const loadImageList = async () => {
loading.value = true
try {
const params: PageQueryDTO<ImageDTO.Filters> = {
page: current.value,
pageSize: pageSize.value,
filters: {
filename: props.searchForm.filename || undefined,
category: props.searchForm.category || undefined,
}
}
const response = await getImagePageApi(params)
imageList.value = response.records
total.value = response.total
} catch (error) {
message.error('加载图片列表失败')
} finally {
loading.value = false
}
}
// 搜索
const handleSearch = () => {
current.value = 1
loadImageList()
}
// 重置
const handleReset = () => {
props.searchForm.filename = ''
props.searchForm.category = undefined
handleSearch()
}
// 分页变化
const handlePageChange = (page: number, size: number) => {
current.value = page
pageSize.value = size
loadImageList()
}
// 上传配置
const uploadProps = {
multiple: true,
showUploadList: false,
accept: 'image/*',
beforeUpload: (file: any) => {
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('只能上传图片文件');
return false;
}
const isValidSize = file.size / 1024 / 1024 < 10; // 10MB
if (!isValidSize) {
message.error('图片大小不能超过 10MB');
return false;
}
return true;
},
customRequest: (options: any) => {
const { file } = options;
if (Array.isArray(file)) {
handleBatchUpload(file);
} else {
handleUpload(file);
}
},
};
// 处理上传
const handleUpload = async (file: File) => {
uploadLoading.value = true;
try {
await uploadImageApi(file);
message.success('图片上传成功');
loadImageList();
} catch (error) {
message.error('图片上传失败');
} finally {
uploadLoading.value = false;
}
};
// 处理批量上传
const handleBatchUpload = async (files: File[]) => {
uploadLoading.value = true;
try {
await batchUploadImagesApi(files);
message.success(`成功上传 ${files.length} 张图片`);
loadImageList();
} catch (error) {
message.error('批量上传失败');
} finally {
uploadLoading.value = false;
}
};
// 事件处理
const handleEdit = (image: ImageVO.Info) => {
emit('edit', image)
}
const handleDelete = (id: number) => {
emit('delete', id)
}
const handleDownload = (image: ImageVO.Info) => {
emit('download', image)
}
const handlePreview = (image: ImageVO.Info) => {
emit('preview', image)
}
// 初始化
loadImageList()
</script>
<style scoped>
.image-grid-view {
width: 100%;
}
</style>
@@ -1,30 +1,41 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag, Upload, Image } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
uploadImageApi,
import {
Button,
Divider,
Flex,
Image,
message,
Space,
Tag,
Upload,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
batchUploadImagesApi,
deleteImageApi,
getImagePageApi,
uploadImageApi,
} from '#/api/media/image';
import type { ImageVO, ImageDTO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import ImageEditModal from './components/ImageEditModal.vue';
import ImageGridView from './components/ImageGridView.vue';
import ImageEditModal from './components/ImageEditModal.vue';
import ImageGridView from './views/ImageGridView/index.vue';
defineOptions({ name: 'ImageRepository' });
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const GridIcon = createIconifyIcon('lucide:grid-3x3');
const ListIcon = createIconifyIcon('lucide:list');
defineOptions({ name: 'ImageRepository' });
// 响应式数据
const loading = ref(false);
const editModalVisible = ref(false);
@@ -106,7 +117,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -191,7 +220,7 @@ const handleUpload = async (file: File) => {
await uploadImageApi(file);
message.success('图片上传成功');
refreshTable();
} catch (error) {
} catch {
message.error('图片上传失败');
} finally {
uploadLoading.value = false;
@@ -205,7 +234,7 @@ const handleBatchUpload = async (files: File[]) => {
await batchUploadImagesApi(files);
message.success(`成功上传 ${files.length} 张图片`);
refreshTable();
} catch (error) {
} catch {
message.error('批量上传失败');
} finally {
uploadLoading.value = false;
@@ -237,7 +266,7 @@ const handleDelete = async (id: number) => {
await deleteImageApi(id);
message.success('删除成功');
refreshTable();
} catch (error) {
} catch {
message.error('删除失败');
}
};
@@ -283,83 +312,86 @@ const uploadProps = {
// 获取分类标签颜色
const getCategoryColor = (category: string | undefined) => {
switch (category) {
case 'image':
return 'blue';
case 'avatar':
case 'avatar': {
return 'green';
case 'logo':
}
case 'image': {
return 'blue';
}
case 'logo': {
return 'purple';
default:
}
default: {
return 'default';
}
}
};
// 获取分类显示文本
const getCategoryText = (category: string | undefined) => {
switch (category) {
case 'image':
return '普通图片';
case 'avatar':
case 'avatar': {
return '头像';
case 'logo':
}
case 'image': {
return '普通图片';
}
case 'logo': {
return 'Logo';
default:
}
default: {
return '未分类';
}
}
};
// 获取标签列表
const getTagList = (tags: string | undefined) => {
if (!tags) return [];
return tags.split(',').map(tag => tag.trim()).filter(tag => tag);
return tags
.split(',')
.map((tag) => tag.trim())
.filter(Boolean);
};
</script>
<template>
<Page title="图片仓库" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理图片资源,支持上传、预览、编辑和分类管理
</div>
</template>
<Page :auto-content-height="true" content-class="flex-col">
<!-- 工具栏区域 -->
<template #extra>
<Space>
<Button
:type="viewMode === 'grid' ? 'primary' : 'default'"
@click="toggleViewMode"
>
<GridIcon class="w-4 h-4 mr-2" />
网格视图
</Button>
<Button
:type="viewMode === 'list' ? 'primary' : 'default'"
@click="toggleViewMode"
>
<ListIcon class="w-4 h-4 mr-2" />
列表视图
</Button>
</Space>
</template>
<!-- 列表视图 -->
<Grid
v-if="viewMode === 'list'"
:loading="loading"
>
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Flex gap="small" align="center">
<Space>
<Upload v-bind="uploadProps">
<Button type="primary" :loading="uploadLoading">
<UploadIcon class="w-4 h-4 mr-2" />
<UploadIcon class="mr-2 h-4 w-4" />
上传图片
</Button>
</Upload>
<span class="text-gray-500">支持批量上传,单个图片最大10MB</span>
</Space>
</template>
<Divider type="vertical" />
<Space>
<Button
:type="viewMode === 'grid' ? 'primary' : 'default'"
@click="toggleViewMode"
>
<GridIcon class="mr-2 h-4 w-4" />
网格视图
</Button>
<Button
:type="viewMode === 'list' ? 'primary' : 'default'"
@click="toggleViewMode"
>
<ListIcon class="mr-2 h-4 w-4" />
列表视图
</Button>
</Space>
</Flex>
</template>
<!-- 列表视图 -->
<Grid v-if="viewMode === 'list'" :loading="loading">
<!-- 预览列 -->
<template #preview="{ row }: { row: any }">
<Image
@@ -367,7 +399,7 @@ const getTagList = (tags: string | undefined) => {
:alt="row.filename"
width="60"
height="60"
style="object-fit: cover; border-radius: 4px;"
style="object-fit: cover; border-radius: 4px"
:preview="true"
/>
</template>
@@ -382,8 +414,8 @@ const getTagList = (tags: string | undefined) => {
<!-- 标签列 -->
<template #tags="{ row }: { row: any }">
<div v-if="row.tags" class="flex flex-wrap gap-1">
<Tag
v-for="tag in getTagList(row.tags)"
<Tag
v-for="tag in getTagList(row.tags)"
:key="tag"
size="small"
color="blue"
@@ -397,12 +429,8 @@ const getTagList = (tags: string | undefined) => {
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleDownload(row)">
下载
</Button>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" @click="handleDownload(row)"> 下载 </Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row.id)">
删除
</Button>
@@ -413,22 +441,22 @@ const getTagList = (tags: string | undefined) => {
<!-- 网格视图 -->
<ImageGridView
v-else
:search-form="searchForm"
v-model:search-form="searchForm"
:category-options="imageCategoryOptions"
:upload-loading="uploadLoading"
@edit="handleEdit"
@delete="handleDelete"
@download="handleDownload"
@preview="handlePreview"
/>
<!-- 编辑弹窗 -->
<ImageEditModal
v-model:open="editModalVisible"
:image-data="currentImageData"
@success="handleEditSuccess"
@cancel="editModalVisible = false"
/>
</Page>
<!-- 编辑弹窗 -->
<ImageEditModal
v-model:open="editModalVisible"
:image-data="currentImageData"
@success="handleEditSuccess"
@cancel="editModalVisible = false"
/>
</template>
<style scoped>
@@ -0,0 +1,191 @@
<script lang="ts" setup>
import type { ImageVO } from '#/api/media/image/types';
import { createIconifyIcon } from '@vben/icons';
import { Button, Card, Image, Popconfirm, Space, Tag } from 'ant-design-vue';
defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
const DownloadIcon = createIconifyIcon('lucide:download');
const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2');
interface Props {
image: ImageVO.Info;
}
interface Emits {
(e: 'download', image: ImageVO.Info): void;
(e: 'edit', image: ImageVO.Info): void;
(e: 'delete', id: number): void;
(e: 'preview', image: ImageVO.Info): void;
}
const handleDownload = (image: ImageVO.Info) => {
emit('download', image);
};
const handleEdit = (image: ImageVO.Info) => {
emit('edit', image);
};
const handleDelete = (id: number) => {
emit('delete', id);
};
const getCategoryColor = (category: string | undefined) => {
switch (category) {
case 'avatar': {
return 'green';
}
case 'image': {
return 'blue';
}
case 'logo': {
return 'purple';
}
default: {
return 'default';
}
}
};
const getCategoryText = (category: string | undefined) => {
switch (category) {
case 'avatar': {
return '头像';
}
case 'image': {
return '普通图片';
}
case 'logo': {
return 'Logo';
}
default: {
return '未分类';
}
}
};
// 获取标签列表
const getTagList = (tags: string | undefined) => {
if (!tags) return [];
return tags
.split(',')
.map((tag) => tag.trim())
.filter(Boolean);
};
</script>
<template>
<Card hoverable :body-style="{ padding: 0 }" class="image-card group">
<!-- 图片区域 -->
<div
class="relative aspect-square cursor-pointer overflow-hidden rounded-t-lg bg-gray-100 dark:bg-neutral-800"
>
<Image
:src="image.url"
:alt="image.filename"
class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
:preview="true"
/>
<!-- 分类标签 -->
<div class="absolute left-2 top-2">
<Tag :color="getCategoryColor(image.category)" size="small">
{{ getCategoryText(image.category) }}
</Tag>
</div>
<!-- 标签列表(如果有多个标签) -->
<div
v-if="getTagList(image.tags).length > 0"
class="absolute right-2 top-2 flex max-w-[calc(100%-80px)] flex-wrap gap-1"
>
<Tag
v-for="(tag, index) in getTagList(image.tags).slice(0, 2)"
:key="index"
size="small"
color="blue"
class="max-w-[80px] truncate"
>
{{ tag }}
</Tag>
<Tag v-if="getTagList(image.tags).length > 2" size="small" color="blue">
+{{ getTagList(image.tags).length - 2 }}
</Tag>
</div>
</div>
<!-- 信息区域 -->
<div class="p-3">
<div
class="mb-1 truncate text-sm font-medium text-gray-900 dark:text-gray-100"
:title="image.filename"
>
{{ image.filename || '未命名' }}
</div>
<div class="mb-3 text-xs text-gray-500 dark:text-gray-400">
{{ image.uploadTime }}
</div>
<!-- 操作按钮 -->
<Space size="small" class="w-full justify-between">
<Space size="small">
<Button
type="text"
size="small"
@click="handleDownload(image)"
title="下载"
>
<template #icon>
<DownloadIcon class="h-4 w-4" />
</template>
下载
</Button>
<Button
type="text"
size="small"
@click="handleEdit(image)"
title="编辑"
>
<template #icon>
<EditIcon class="h-4 w-4" />
</template>
编辑
</Button>
</Space>
<Popconfirm
title="确定要删除这张图片吗?"
@confirm="handleDelete(image.id)"
>
<Button type="text" size="small" danger title="删除">
<template #icon>
<TrashIcon class="h-4 w-4" />
</template>
删除
</Button>
</Popconfirm>
</Space>
</div>
</Card>
</template>
<style scoped>
.image-card {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid var(--border-color);
}
.image-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
border-color: var(--primary-color);
}
.image-card :deep(.ant-card-body) {
padding: 0 !important;
}
</style>
@@ -0,0 +1,247 @@
<script setup lang="ts">
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import { ref, watch } from 'vue';
import {
Button,
Card,
Col,
Form,
Input,
message,
Pagination,
Row,
Select,
Space,
Spin,
} from 'ant-design-vue';
import { getImagePageApi } from '#/api/media/image';
import ImageCard from './components/ImageCard.vue';
defineOptions({ name: 'ImageGridView' });
const props = defineProps<{
categoryOptions: Array<{ label: string; value: string }>;
searchForm: {
category?: string;
filename: string;
};
uploadLoading?: boolean;
}>();
const emit = defineEmits<{
(e: 'edit', image: ImageVO.Info): void;
(e: 'delete', id: number): void;
(e: 'download', image: ImageVO.Info): void;
(e: 'preview', image: ImageVO.Info): void;
(e: 'update:searchForm', value: typeof props.searchForm): void;
}>();
// 响应式数据
const loading = ref(false);
const imageList = ref<ImageVO.Info[]>([]);
const total = ref(0);
const current = ref(1);
const pageSize = ref(24); // 网格视图默认24个
// 本地搜索表单副本(用于 v-model)
const localSearchForm = ref({
filename: props.searchForm.filename,
category: props.searchForm.category,
});
// 监听 props 变化,同步到本地
watch(
() => props.searchForm,
(newForm) => {
if (
localSearchForm.value.filename !== newForm.filename ||
localSearchForm.value.category !== newForm.category
) {
localSearchForm.value.filename = newForm.filename;
localSearchForm.value.category = newForm.category;
current.value = 1;
loadImageList();
}
},
{ deep: true },
);
// 监听本地表单变化,同步到父组件
watch(
localSearchForm,
(newForm) => {
if (
props.searchForm.filename !== newForm.filename ||
props.searchForm.category !== newForm.category
) {
emit('update:searchForm', { ...newForm });
}
},
{ deep: true },
);
// 加载图片列表
const loadImageList = async () => {
loading.value = true;
try {
const params: PageQueryDTO<ImageDTO.Filters> = {
page: current.value,
pageSize: pageSize.value,
filters: {
filename: localSearchForm.value.filename || undefined,
category: localSearchForm.value.category || undefined,
},
};
const response = await getImagePageApi(params);
imageList.value = response.records;
total.value = response.total;
} catch {
message.error('加载图片列表失败');
} finally {
loading.value = false;
}
};
// 搜索
const handleSearch = () => {
current.value = 1;
loadImageList();
};
// 重置
const handleReset = () => {
localSearchForm.value.filename = '';
localSearchForm.value.category = undefined;
handleSearch();
};
// 分页变化
const handlePageChange = (page: number, size: number) => {
current.value = page;
pageSize.value = size;
loadImageList();
};
// 事件处理
const handleEdit = (image: ImageVO.Info) => {
emit('edit', image);
};
const handleDelete = (id: number) => {
emit('delete', id);
};
const handleDownload = (image: ImageVO.Info) => {
emit('download', image);
};
const handlePreview = (image: ImageVO.Info) => {
emit('preview', image);
};
// 初始化
loadImageList();
</script>
<template>
<div class="flex-col">
<!-- 搜索区域 -->
<Card class="mb-4" :body-style="{ padding: '16px' }">
<Form :model="localSearchForm" layout="inline" class="w-full">
<div class="flex flex-wrap items-center gap-4">
<Form.Item label="文件名" class="mb-0">
<Input
v-model:value="localSearchForm.filename"
placeholder="请输入文件名"
style="width: 200px"
allow-clear
@press-enter="handleSearch"
/>
</Form.Item>
<Form.Item label="图片分类" class="mb-0">
<Select
v-model:value="localSearchForm.category"
placeholder="请选择图片分类"
style="width: 150px"
allow-clear
>
<Select.Option
v-for="option in categoryOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item class="mb-0">
<Space>
<Button type="primary" @click="handleSearch">搜索</Button>
<Button @click="handleReset">重置</Button>
</Space>
</Form.Item>
<div class="ml-auto text-sm text-gray-500 dark:text-gray-400">
共 {{ total }} 张图片
</div>
</div>
</Form>
</Card>
<!-- 网格内容 -->
<Card class="flex-1" :body-style="{ padding: '16px' }">
<Spin :spinning="loading">
<Row :gutter="[16, 16]">
<Col
v-for="image in imageList"
:key="image.id"
:xs="12"
:sm="8"
:md="6"
:lg="4"
:xl="3"
>
<ImageCard
:image="image"
@download="handleDownload"
@edit="handleEdit"
@delete="handleDelete"
@preview="handlePreview"
/>
</Col>
</Row>
<!-- 空状态 -->
<div
v-if="!loading && imageList.length === 0"
class="py-16 text-center"
>
<div class="mb-4 text-6xl">📷</div>
<div class="mb-2 text-lg text-gray-400">暂无图片数据</div>
<div class="text-sm text-gray-400">请上传图片或调整搜索条件</div>
</div>
<!-- 分页 -->
<div v-if="total > 0" class="mt-6 flex justify-center">
<Pagination
v-model:current="current"
v-model:page-size="pageSize"
:total="total"
:page-size-options="['12', '24', '48', '96']"
show-size-changer
show-quick-jumper
:show-total="
(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`
"
@change="handlePageChange"
/>
</div>
</Spin>
</Card>
</div>
</template>
@@ -1,31 +1,37 @@
<script lang="ts" setup>
import { computed, ref, watch } from 'vue';
import { Form, Input, Modal, Select, message } from 'ant-design-vue';
import type {
SuperAccountDTO,
SuperAccountVO,
} from '#/api/organization/account-super';
import {
super_createAccountApi,
import { computed, ref, watch } from 'vue';
import { Form, Input, message, Modal, Select } from 'ant-design-vue';
import {
super_createAccountApi,
super_updateAccountApi,
type SuperAccountVO,
type SuperAccountDTO
} from '#/api/organization/account-super';
interface Emits {
(e: 'success'): void;
}
const emit = defineEmits<Emits>();
defineOptions({ name: 'SuperAccountFormModal' });
const emit = defineEmits<Emits>();
// 响应式数据
const formRef = ref();
const loading = ref(false);
const visible = ref(false);
const isEdit = ref(false);
const currentAccountData = ref<SuperAccountVO.AccountInfoVO | null>(null);
const currentAccountData = ref<null | SuperAccountVO.AccountInfoVO>(null);
// 表单数据
const formData = ref<SuperAccountDTO.SuperCreateAccountDTO & { status?: number }>({
const formData = ref<
SuperAccountDTO.SuperCreateAccountDTO & { status?: number }
>({
loginCode: '',
password: '',
realName: '',
@@ -40,7 +46,7 @@ const formData = ref<SuperAccountDTO.SuperCreateAccountDTO & { status?: number }
});
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑账户' : '添加账户');
const modalTitle = computed(() => (isEdit.value ? '编辑账户' : '添加账户'));
// 状态选项
const statusOptions = [
@@ -74,12 +80,12 @@ function handleCancel() {
}
// 暴露给父组件的方法
function open(accountData?: SuperAccountVO.AccountInfoVO | null) {
function open(accountData?: null | SuperAccountVO.AccountInfoVO) {
isEdit.value = !!accountData;
currentAccountData.value = accountData || null;
resetForm();
if (accountData) {
formData.value = {
loginCode: accountData.loginCode,
@@ -95,7 +101,7 @@ function open(accountData?: SuperAccountVO.AccountInfoVO | null) {
status: accountData.status,
};
}
visible.value = true;
}
@@ -104,21 +110,22 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
if (isEdit.value && currentAccountData.value) {
const { password, ...updateData } = formData.value;
const { password: _, ...updateData } = formData.value;
await super_updateAccountApi(currentAccountData.value.id, updateData);
message.success('更新成功');
} else {
await super_createAccountApi(formData.value);
message.success('创建成功');
}
visible.value = false;
emit('success');
} catch (error: any) {
console.error('保存账户失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '保存账户失败';
const errorMessage =
error?.response?.data?.message || error?.message || '保存账户失败';
message.error(errorMessage);
} finally {
loading.value = false;
@@ -153,63 +160,112 @@ defineExpose({
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="登录账号" name="loginCode" :rules="[
{ required: true, message: '请输入登录账号' },
{ min: 3, max: 20, message: '登录账号长度为3-20个字符' },
{ pattern: /^[a-zA-Z0-9_]+$/, message: '登录账号只能包含字母、数字和下划线' }
]">
<Input v-model:value="formData.loginCode" placeholder="请输入登录账号" />
<Form.Item
label="登录账号"
name="loginCode"
:rules="[
{ required: true, message: '请输入登录账号' },
{ min: 3, max: 20, message: '登录账号长度为3-20个字符' },
{
pattern: /^[a-zA-Z0-9_]+$/,
message: '登录账号只能包含字母、数字和下划线',
},
]"
>
<Input
v-model:value="formData.loginCode"
placeholder="请输入登录账号"
/>
</Form.Item>
<Form.Item v-if="!isEdit" label="密码" name="password" :rules="[
{ required: true, message: '请输入密码' },
{ min: 6, max: 20, message: '密码长度为6-20个字符' }
]">
<Input v-model:value="formData.password" type="password" placeholder="请输入密码" />
<Form.Item
v-if="!isEdit"
label="密码"
name="password"
:rules="[
{ required: true, message: '请输入密码' },
{ 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: '请输入真实姓名' }]">
<Form.Item
label="真实姓名"
name="realName"
:rules="[{ required: true, message: '请输入真实姓名' }]"
>
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
</Form.Item>
<Form.Item label="备注" name="remark">
<Input v-model:value="formData.remark" placeholder="请输入备注" />
</Form.Item>
<Form.Item label="手机号" name="phone" :rules="[
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
]">
<Form.Item
label="手机号"
name="phone"
:rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }]"
>
<Input v-model:value="formData.phone" placeholder="请输入手机号" />
</Form.Item>
<Form.Item label="公司ID" name="companyId" :rules="[{ required: true, message: '请输入公司ID' }]">
<Input v-model:value="formData.companyId" type="number" placeholder="请输入公司ID" />
<Form.Item
label="公司ID"
name="companyId"
:rules="[{ required: true, message: '请输入公司ID' }]"
>
<Input
v-model:value="formData.companyId"
type="number"
placeholder="请输入公司ID"
/>
</Form.Item>
<Form.Item label="部门ID" name="departmentId">
<Input v-model:value="formData.departmentId" type="number" placeholder="请输入部门ID" />
<Input
v-model:value="formData.departmentId"
type="number"
placeholder="请输入部门ID"
/>
</Form.Item>
<Form.Item label="岗位ID" name="positionId">
<Input v-model:value="formData.positionId" type="number" placeholder="请输入岗位ID" />
<Input
v-model:value="formData.positionId"
type="number"
placeholder="请输入岗位ID"
/>
</Form.Item>
<Form.Item label="角色" name="role" :rules="[{ required: true, message: '请输入角色' }]">
<Form.Item
label="角色"
name="role"
:rules="[{ required: true, message: '请输入角色' }]"
>
<Select
v-model:value="formData.role"
placeholder="请选择角色"
:options="[
{ label: '超级管理员', value: 'super' },
{ label: '管理员', value: 'admin' },
{ label: '普通用户', value: 'user' }
{ label: '普通用户', value: 'user' },
]"
/>
</Form.Item>
<Form.Item label="头像图片ID" name="avatarImageId">
<Input v-model:value="formData.avatarImageId" type="number" placeholder="请输入头像图片ID" />
<Input
v-model:value="formData.avatarImageId"
type="number"
placeholder="请输入头像图片ID"
/>
</Form.Item>
<Form.Item v-if="isEdit" label="状态" name="status">
<Select
v-model:value="formData.status"
@@ -217,7 +273,6 @@ defineExpose({
:options="statusOptions"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,40 +1,45 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
super_deleteAccountApi,
super_getAccountPageApi,
type SuperAccountVO,
type SuperAccountDTO
import type {
SuperAccountDTO,
SuperAccountVO,
} from '#/api/organization/account-super';
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, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
super_deleteAccountApi,
super_getAccountPageApi,
} from '#/api/organization/account-super';
import SuperAccountFormModal from './components/SuperAccountFormModal.vue';
defineOptions({ name: 'SuperAccountManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'SuperAccountManagement' });
// 响应式数据
const loading = ref(false);
const accountFormModalRef = ref();
// 搜索表单
const searchForm = ref({
loginCode: undefined as undefined | string,
realName: undefined as undefined | string,
phone: undefined as undefined | string,
companyId: undefined as undefined | number,
departmentId: undefined as undefined | number,
positionId: undefined as undefined | number,
role: undefined as undefined | string,
status: undefined as undefined | number,
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,
});
// 状态选项
@@ -150,7 +155,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -170,7 +193,8 @@ const gridOptions: VxeGridProps<any> = {
};
} catch (error: any) {
console.error('查询数据失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '查询数据失败';
const errorMessage =
error?.response?.data?.message || error?.message || '查询数据失败';
message.error(errorMessage);
return {
items: [],
@@ -220,7 +244,8 @@ const handleDelete = async (row: SuperAccountVO.AccountInfoVO) => {
refreshTable();
} catch (error: any) {
console.error('删除失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
const errorMessage =
error?.response?.data?.message || error?.message || '删除失败';
message.error(errorMessage);
}
};
@@ -234,15 +259,16 @@ const handleBatchDelete = async () => {
}
try {
const deletePromises = selectedRows.map((row: SuperAccountVO.AccountInfoVO) =>
super_deleteAccountApi(row.id)
const deletePromises = selectedRows.map(
(row: SuperAccountVO.AccountInfoVO) => super_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 || '批量删除失败';
const errorMessage =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(errorMessage);
}
};
@@ -284,9 +310,7 @@ const getStatusColor = (status: number) => {
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -294,11 +318,7 @@ const getStatusColor = (status: number) => {
<PlusIcon />
添加账户
</Button>
<Button
v-if="hasSelected"
danger
@click="handleBatchDelete"
>
<Button v-if="hasSelected" danger @click="handleBatchDelete">
批量删除
</Button>
</Space>
@@ -310,21 +330,20 @@ const getStatusColor = (status: number) => {
{{ getStatusText(row.status) }}
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 账户表单弹窗 -->
<SuperAccountFormModal ref="accountFormModalRef" @success="handleModalSuccess" />
<SuperAccountFormModal
ref="accountFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>
@@ -1,22 +1,23 @@
<script lang="ts" setup>
import { computed, ref, watch } from 'vue';
import { Form, Input, Modal, Select, message } from 'ant-design-vue';
import type { AccountDTO, AccountVO } from '#/api/organization/account';
import {
admin_createAccountApi,
import { computed, ref, watch } from 'vue';
import { Form, Input, message, Modal, Select } from 'ant-design-vue';
import {
admin_createAccountApi,
admin_updateAccountApi,
type AccountVO,
type AccountDTO
} from '#/api/organization/account';
interface Emits {
(e: 'success'): void;
}
const emit = defineEmits<Emits>();
defineOptions({ name: 'AccountFormModal' });
const emit = defineEmits<Emits>();
// 响应式数据
const formRef = ref();
const loading = ref(false);
@@ -38,7 +39,7 @@ const formData = ref<AccountDTO.CreateAccountDTO & { status?: number }>({
});
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑账户' : '添加账户');
const modalTitle = computed(() => (isEdit.value ? '编辑账户' : '添加账户'));
// 状态选项
const statusOptions = [
@@ -73,9 +74,9 @@ function handleCancel() {
function open(accountData?: AccountVO.AccountInfoVO | null) {
isEdit.value = !!accountData;
currentAccountData.value = accountData || null;
resetForm();
if (accountData) {
formData.value = {
loginCode: accountData.loginCode,
@@ -89,7 +90,7 @@ function open(accountData?: AccountVO.AccountInfoVO | null) {
status: accountData.status,
};
}
visible.value = true;
}
@@ -98,21 +99,22 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
if (isEdit.value && currentAccountData.value) {
const { password, ...updateData } = formData.value;
const { password: _, ...updateData } = formData.value;
await admin_updateAccountApi(currentAccountData.value.id, updateData);
message.success('更新成功');
} else {
await admin_createAccountApi(formData.value);
message.success('创建成功');
}
visible.value = false;
emit('success');
} catch (error: any) {
console.error('保存账户失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '保存账户失败';
const errorMessage =
error?.response?.data?.message || error?.message || '保存账户失败';
message.error(errorMessage);
} finally {
loading.value = false;
@@ -147,48 +149,96 @@ defineExpose({
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="登录账号" name="loginCode" :rules="[
{ required: true, message: '请输入登录账号' },
{ min: 4, max: 20, message: '登录账号长度为4-20个字符' },
{ pattern: /^[a-zA-Z0-9_]+$/, message: '登录账号只能包含字母、数字和下划线' }
]">
<Input v-model:value="formData.loginCode" placeholder="请输入登录账号" />
<Form.Item
label="登录账号"
name="loginCode"
:rules="[
{ required: true, message: '请输入登录账号' },
{ min: 4, max: 20, message: '登录账号长度为4-20个字符' },
{
pattern: /^[a-zA-Z0-9_]+$/,
message: '登录账号只能包含字母、数字和下划线',
},
]"
>
<Input
v-model:value="formData.loginCode"
placeholder="请输入登录账号"
/>
</Form.Item>
<Form.Item v-if="!isEdit" label="密码" name="password" :rules="[
{ required: true, message: '请输入密码' },
{ min: 8, max: 20, message: '密码长度为8-20个字符' },
{ pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/, message: '密码必须包含大小写字母、数字,长度至少8位' }
]">
<Input v-model:value="formData.password" type="password" placeholder="请输入密码" />
<Form.Item
v-if="!isEdit"
label="密码"
name="password"
:rules="[
{ required: true, message: '请输入密码' },
{ min: 8, max: 20, message: '密码长度为8-20个字符' },
{
pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/,
message: '密码必须包含大小写字母、数字,长度至少8位',
},
]"
>
<Input
v-model:value="formData.password"
type="password"
placeholder="请输入密码"
/>
</Form.Item>
<Form.Item label="真实姓名" name="realName" :rules="[{ required: true, message: '请输入真实姓名' }]">
<Form.Item
label="真实姓名"
name="realName"
:rules="[{ required: true, message: '请输入真实姓名' }]"
>
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
</Form.Item>
<Form.Item label="备注" name="remark">
<Input v-model:value="formData.remark" placeholder="请输入备注" />
</Form.Item>
<Form.Item label="手机号" name="phone" :rules="[
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
]">
<Form.Item
label="手机号"
name="phone"
:rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }]"
>
<Input v-model:value="formData.phone" placeholder="请输入手机号" />
</Form.Item>
<Form.Item label="部门ID" name="departmentId" :rules="[{ required: true, message: '请输入部门ID' }]">
<Input v-model:value="formData.departmentId" type="number" placeholder="请输入部门ID" />
<Form.Item
label="部门ID"
name="departmentId"
:rules="[{ required: true, message: '请输入部门ID' }]"
>
<Input
v-model:value="formData.departmentId"
type="number"
placeholder="请输入部门ID"
/>
</Form.Item>
<Form.Item label="岗位ID" name="positionId" :rules="[{ required: true, message: '请输入岗位ID' }]">
<Input v-model:value="formData.positionId" type="number" placeholder="请输入岗位ID" />
<Form.Item
label="岗位ID"
name="positionId"
:rules="[{ required: true, message: '请输入岗位ID' }]"
>
<Input
v-model:value="formData.positionId"
type="number"
placeholder="请输入岗位ID"
/>
</Form.Item>
<Form.Item label="头像图片ID" name="avatarImageId">
<Input v-model:value="formData.avatarImageId" type="number" placeholder="请输入头像图片ID" />
<Input
v-model:value="formData.avatarImageId"
type="number"
placeholder="请输入头像图片ID"
/>
</Form.Item>
<Form.Item v-if="isEdit" label="状态" name="status">
<Select
v-model:value="formData.status"
@@ -196,7 +246,6 @@ defineExpose({
:options="statusOptions"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,40 +1,42 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
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 { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
admin_deleteAccountApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
admin_deleteAccountApi,
admin_getAccountPageApi,
type AccountVO,
type AccountDTO
} from '#/api/organization/account';
import type { PageQueryDTO } from '#/types/common';
import AccountFormModal from './components/AccountFormModal.vue';
defineOptions({ name: 'CompanyAccountManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'CompanyAccountManagement' });
// 响应式数据
const loading = ref(false);
const accountFormModalRef = ref();
// 搜索表单
const searchForm = ref({
loginCode: undefined as undefined | string,
realName: undefined as undefined | string,
phone: undefined as undefined | string,
companyId: undefined as undefined | number,
departmentId: undefined as undefined | number,
positionId: undefined as undefined | number,
role: undefined as undefined | string,
status: undefined as undefined | number,
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,
});
// 状态选项
@@ -150,7 +152,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -170,7 +190,8 @@ const gridOptions: VxeGridProps<any> = {
};
} catch (error: any) {
console.error('查询数据失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '查询数据失败';
const errorMessage =
error?.response?.data?.message || error?.message || '查询数据失败';
message.error(errorMessage);
return {
items: [],
@@ -220,7 +241,8 @@ const handleDelete = async (row: AccountVO.AccountInfoVO) => {
refreshTable();
} catch (error: any) {
console.error('删除失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
const errorMessage =
error?.response?.data?.message || error?.message || '删除失败';
message.error(errorMessage);
}
};
@@ -234,15 +256,16 @@ const handleBatchDelete = async () => {
}
try {
const deletePromises = selectedRows.map((row: AccountVO.AccountInfoVO) =>
admin_deleteAccountApi(row.id)
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 || '批量删除失败';
const errorMessage =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(errorMessage);
}
};
@@ -273,7 +296,6 @@ const getStatusColor = (status: number) => {
function handleModalSuccess() {
refreshTable();
}
</script>
<template>
@@ -285,9 +307,7 @@ function handleModalSuccess() {
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -295,11 +315,7 @@ function handleModalSuccess() {
<PlusIcon />
添加账户
</Button>
<Button
v-if="hasSelected"
danger
@click="handleBatchDelete"
>
<Button v-if="hasSelected" danger @click="handleBatchDelete">
批量删除
</Button>
</Space>
@@ -311,16 +327,12 @@ function handleModalSuccess() {
{{ getStatusText(row.status) }}
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
@@ -1,113 +1,25 @@
<template>
<Modal
:open="visible"
:title="modalTitle"
width="600px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<Form
ref="formRef"
:model="formData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="公司Logo" name="logoImageId">
<div style="display: flex; align-items: center; gap: 16px;">
<!-- Logo预览区域 -->
<div style="position: relative; display: inline-block;">
<!-- 有图片时显示图片 -->
<img
v-if="currentLogoUrl && !imageLoadError"
:src="currentLogoUrl"
alt="公司Logo"
style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 1px solid #d9d9d9; background-color: #f5f5f5;"
@error="handleImageError"
/>
<!-- 无图片或加载失败时显示空状态 -->
<div
v-else
style="width: 80px; height: 80px; border: 1px dashed #d9d9d9; border-radius: 8px; background-color: #fafafa; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px; text-align: center; line-height: 1.2;">
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
<CameraIcon style="font-size: 16px; margin-bottom: 4px;" />
<div>上传Logo</div>
</div>
</div>
<!-- 点击更换遮罩 -->
<div
style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); border-radius: 8px; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; cursor: pointer;"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
@mouseleave="($event.target as HTMLElement).style.opacity = '0'"
@click="selectLogoFile">
<div style="color: white; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center;">
<CameraIcon style="font-size: 16px; margin-bottom: 4px;" />
<div style="font-size: 12px;">{{ currentLogoUrl && !imageLoadError ? '更换Logo' : '上传Logo' }}</div>
</div>
</div>
</div>
<!-- 重置按钮 -->
<div v-if="newLogoFile">
<Button size="small" @click="removeNewLogo">重置</Button>
</div>
</div>
</Form.Item>
<Form.Item label="公司名称" name="name" :rules="[{ required: true, message: '请输入公司名称' }]">
<Input v-model:value="formData.name" placeholder="请输入公司名称" />
</Form.Item>
<Form.Item label="公司地址" name="address">
<Input v-model:value="formData.address" placeholder="请输入公司地址" />
</Form.Item>
<Form.Item label="联系人" name="contactPerson">
<Input v-model:value="formData.contactPerson" placeholder="请输入联系人" />
</Form.Item>
<Form.Item label="联系电话" name="contactPhone" :rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }]">
<Input v-model:value="formData.contactPhone" placeholder="请输入联系电话" />
</Form.Item>
<Form.Item label="邮箱" name="email" :rules="[{ type: 'email', message: '请输入正确的邮箱地址' }]">
<Input v-model:value="formData.email" placeholder="请输入邮箱" />
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
checked-children="正常"
un-checked-children="禁用"
/>
</Form.Item>
<Form.Item label="订阅到期时间" name="expireTime">
<DatePicker
v-model:value="formData.expireTime"
placeholder="请选择订阅到期时间"
style="width: 100%;"
show-time
format="YYYY-MM-DD HH:mm:ss"
/>
</Form.Item>
</Form>
</Modal>
</template>
<script lang="ts" setup>
import { computed, ref, onUnmounted } from 'vue';
import { Form, Input, Modal, DatePicker, Button, message, Switch } from 'ant-design-vue';
import type { CompanyDTO, CompanyVO } from '#/api/organization/company';
import { computed, onUnmounted, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
DatePicker,
Form,
Input,
message,
Modal,
Switch,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
uploadCompanyLogoApi,
createCompanyApi,
import {
createCompanyApi,
updateCompanyApi,
type CompanyVO,
type CompanyDTO
uploadCompanyLogoApi,
} from '#/api/organization/company';
interface Emits {
@@ -158,7 +70,7 @@ const formData = ref<FormData>({
// 开关组件不需要选项数组
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑公司' : '添加公司');
const modalTitle = computed(() => (isEdit.value ? '编辑公司' : '添加公司'));
// 当前显示的logo URL(优先显示新选择的)
const currentLogoUrl = computed(() => {
@@ -180,9 +92,11 @@ function initFormData() {
email: currentCompanyData.value.email || '',
logoImageId: undefined,
status: currentCompanyData.value.status === 1, // 转换为boolean
expireTime: currentCompanyData.value.expireTime ? dayjs(currentCompanyData.value.expireTime) : undefined,
expireTime: currentCompanyData.value.expireTime
? dayjs(currentCompanyData.value.expireTime)
: undefined,
};
// 设置原始Logo URL
originalLogoUrl.value = currentCompanyData.value.logo || '';
} else {
@@ -199,7 +113,7 @@ function initFormData() {
};
originalLogoUrl.value = '';
}
// 重置新选择的logo和图片加载状态
newLogoFile.value = null;
imageLoadError.value = false;
@@ -218,18 +132,20 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
// 准备提交数据
const submitData = {
const submitData = {
...formData.value,
status: formData.value.status ? 1 : 0 // 转换boolean为number
status: formData.value.status ? 1 : 0, // 转换boolean为number
};
// 处理日期格式
if (submitData.expireTime) {
submitData.expireTime = submitData.expireTime.format('YYYY-MM-DD HH:mm:ss');
submitData.expireTime = submitData.expireTime.format(
'YYYY-MM-DD HH:mm:ss',
);
}
// 如果有新选择的logo,先上传获取ID
if (newLogoFile.value) {
const logoImageId = await uploadLogoAndGetId();
@@ -240,16 +156,19 @@ async function handleSubmit() {
// 创建模式且没有选择Logo,移除logoImageId字段
delete submitData.logoImageId;
}
// 调用API
if (isEdit.value && currentCompanyData.value) {
await updateCompanyApi(currentCompanyData.value.id, submitData as CompanyDTO.UpdateCompanyDTO);
await updateCompanyApi(
currentCompanyData.value.id,
submitData as CompanyDTO.UpdateCompanyDTO,
);
message.success('更新成功');
} else {
await createCompanyApi(submitData as CompanyDTO.CreateCompanyDTO);
message.success('创建成功');
}
visible.value = false;
emit('success');
} catch (error) {
@@ -266,13 +185,16 @@ function handleCancel() {
}
// 暴露给父组件的方法
function open(editMode: boolean = false, companyData?: CompanyVO.CompanyInfoVO | null) {
function open(
editMode: boolean = false,
companyData?: CompanyVO.CompanyInfoVO | null,
) {
isEdit.value = editMode;
currentCompanyData.value = companyData || null;
resetForm(); // 先重置表单
initFormData(); // 再初始化数据
visible.value = true;
}
@@ -287,35 +209,35 @@ function selectLogoFile() {
input.type = 'file';
input.accept = 'image/*';
input.style.display = 'none';
document.body.appendChild(input);
input.onchange = (e) => {
document.body.append(input);
input.addEventListener('change', (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
// 验证文件
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('只能上传图片文件');
document.body.removeChild(input);
input.remove();
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小不能超过 2MB');
document.body.removeChild(input);
input.remove();
return;
}
// 设置新选择的文件
newLogoFile.value = file;
imageLoadError.value = false; // 重置图片加载错误状态
message.success('Logo选择成功');
}
document.body.removeChild(input);
};
input.remove();
});
input.click();
}
@@ -331,10 +253,9 @@ async function uploadLogoAndGetId(): Promise<number | undefined> {
if (!newLogoFile.value) {
return undefined;
}
try {
const response = await uploadCompanyLogoApi(newLogoFile.value);
console.log('Logo上传成功:', response);
return response.id;
} catch (error) {
console.error('Logo上传失败:', error);
@@ -350,7 +271,6 @@ function handleImageError(event: Event) {
message.error('图片加载失败,请重新选择');
}
// 组件卸载时清理
onUnmounted(() => {
if (newLogoFile.value) {
@@ -359,3 +279,174 @@ onUnmounted(() => {
}
});
</script>
<template>
<Modal
:open="visible"
:title="modalTitle"
width="600px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<Form
ref="formRef"
:model="formData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="公司Logo" name="logoImageId">
<div style="display: flex; align-items: center; gap: 16px">
<!-- Logo预览区域 -->
<div style="position: relative; display: inline-block">
<!-- 有图片时显示图片 -->
<img
v-if="currentLogoUrl && !imageLoadError"
:src="currentLogoUrl"
alt="公司Logo"
style="
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 8px;
border: 1px solid #d9d9d9;
background-color: #f5f5f5;
"
@error="handleImageError"
/>
<!-- 无图片或加载失败时显示空状态 -->
<div
v-else
style="
width: 80px;
height: 80px;
border: 1px dashed #d9d9d9;
border-radius: 8px;
background-color: #fafafa;
display: flex;
align-items: center;
justify-content: center;
color: #999;
font-size: 12px;
text-align: center;
line-height: 1.2;
"
>
<div
style="
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div>上传Logo</div>
</div>
</div>
<!-- 点击更换遮罩 -->
<div
style="
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.3s;
cursor: pointer;
"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
@mouseleave="($event.target as HTMLElement).style.opacity = '0'"
@click="selectLogoFile"
>
<div
style="
color: white;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div style="font-size: 12px">
{{
currentLogoUrl && !imageLoadError ? '更换Logo' : '上传Logo'
}}
</div>
</div>
</div>
</div>
<!-- 重置按钮 -->
<div v-if="newLogoFile">
<Button size="small" @click="removeNewLogo">重置</Button>
</div>
</div>
</Form.Item>
<Form.Item
label="公司名称"
name="name"
:rules="[{ required: true, message: '请输入公司名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入公司名称" />
</Form.Item>
<Form.Item label="公司地址" name="address">
<Input v-model:value="formData.address" placeholder="请输入公司地址" />
</Form.Item>
<Form.Item label="联系人" name="contactPerson">
<Input
v-model:value="formData.contactPerson"
placeholder="请输入联系人"
/>
</Form.Item>
<Form.Item
label="联系电话"
name="contactPhone"
:rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }]"
>
<Input
v-model:value="formData.contactPhone"
placeholder="请输入联系电话"
/>
</Form.Item>
<Form.Item
label="邮箱"
name="email"
:rules="[{ type: 'email', message: '请输入正确的邮箱地址' }]"
>
<Input v-model:value="formData.email" placeholder="请输入邮箱" />
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
checked-children="正常"
un-checked-children="禁用"
/>
</Form.Item>
<Form.Item label="订阅到期时间" name="expireTime">
<DatePicker
v-model:value="formData.expireTime"
placeholder="请选择订阅到期时间"
style="width: 100%"
show-time
format="YYYY-MM-DD HH:mm:ss"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,27 +1,29 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CompanyDTO, CompanyVO } from '#/api/organization/company';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteCompanyApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteCompanyApi,
getCompanyPageApi,
type CompanyVO,
type CompanyDTO
} from '#/api/organization/company';
import type { PageQueryDTO } from '#/types/common';
import CompanyFormModal from './components/CompanyFormModal.vue';
import CompanyMenuDrawer from '#/components/CompanyMenuDrawer.vue';
import CompanyFormModal from './components/CompanyFormModal.vue';
defineOptions({ name: 'CompanyManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'CompanyManagement' });
// 响应式数据
const loading = ref(false);
const companyFormModalRef = ref();
@@ -125,7 +127,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -133,6 +153,15 @@ const gridOptions: VxeGridProps<any> = {
query: async ({ page }) => {
try {
loading.value = true;
// 处理 expired 字段的转换
let expiredValue: boolean | undefined;
if (searchForm.value.expired === 'true') {
expiredValue = true;
} else if (searchForm.value.expired === 'false') {
expiredValue = false;
} else {
expiredValue = undefined;
}
const params: PageQueryDTO<CompanyDTO.CompanyFiltersDTO> = {
page: page.currentPage,
pageSize: page.pageSize,
@@ -142,7 +171,7 @@ const gridOptions: VxeGridProps<any> = {
contactPhone: searchForm.value.contactPhone || undefined,
email: searchForm.value.email || undefined,
status: searchForm.value.status,
expired: searchForm.value.expired === 'true' ? true : searchForm.value.expired === 'false' ? false : undefined,
expired: expiredValue,
},
};
const data = await getCompanyPageApi(params);
@@ -216,7 +245,7 @@ const formOptions = computed(() => ({
placeholder: '请选择过期状态',
options: [
{ label: '已过期', value: 'true' },
{ label: '正常', value: 'false' }
{ label: '正常', value: 'false' },
],
allowClear: true,
},
@@ -286,9 +315,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -302,13 +329,18 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- Logo列 -->
<template #logo="{ row }: { row: any }">
<div v-if="row.logo">
<img
:src="row.logo"
<img
:src="row.logo"
:alt="row.name"
style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;"
style="
width: 40px;
height: 40px;
object-fit: cover;
border-radius: 4px;
"
/>
</div>
<span v-else style="color: #999;">暂无Logo</span>
<span v-else style="color: #999">暂无Logo</span>
</template>
<!-- 状态列 -->
@@ -322,12 +354,12 @@ const [Grid, gridApi] = useVbenVxeGrid({
<template #expired="{ row }: { row: any }">
<Tag v-if="row.expired === true" color="red">已过期</Tag>
<Tag v-else-if="row.expired === false" color="green">正常</Tag>
<span v-else style="color: #999;">未知</span>
<span v-else style="color: #999">未知</span>
</template>
<!-- 订阅到期时间列 -->
<template #expireTime="{ row }: { row: any }">
<span v-if="!row.expireTime" style="color: #999;">未设置</span>
<span v-if="!row.expireTime" style="color: #999">未设置</span>
<span v-else :style="{ color: row.expired ? '#ff4d4f' : '#52c41a' }">
{{ row.expireTime }}
</span>
@@ -336,25 +368,18 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" type="primary" @click="handleMenuManage(row)">
菜单
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 公司表单模态框 -->
<CompanyFormModal
ref="companyFormModalRef"
@success="handleModalSuccess"
/>
<CompanyFormModal ref="companyFormModalRef" @success="handleModalSuccess" />
<!-- 公司菜单管理抽屉 -->
<CompanyMenuDrawer ref="companyMenuDrawerRef" />
</Page>
@@ -1,11 +1,13 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { Form, Input, Modal, Select, message, Switch } from 'ant-design-vue';
import type { DepartmentVO } from '#/api/organization/department';
import {
createDepartmentApi,
import { computed, ref } from 'vue';
import { Form, Input, message, Modal, Select, Switch } from 'ant-design-vue';
import {
createDepartmentApi,
updateDepartmentApi,
type DepartmentVO
} from '#/api/organization/department';
interface Props {
@@ -47,16 +49,25 @@ const formData = ref<FormData>({
// 父部门选项
const parentDepartmentOptions = computed(() => {
const options: Array<{ label: string; value: number | undefined }> = [{ label: '根部门', value: undefined }];
const addDepartmentOptions = (departments: DepartmentVO.DepartmentInfoVO[], level = 0) => {
departments.forEach(dept => {
const options: Array<{ label: string; value: number | undefined }> = [
{ label: '根部门', value: undefined },
];
const addDepartmentOptions = (
departments: DepartmentVO.DepartmentInfoVO[],
level = 0,
) => {
departments.forEach((dept) => {
// 编辑时排除自己和自己的子部门
if (isEdit.value && currentDepartmentData.value &&
(dept.id === currentDepartmentData.value.id || isChildDepartment(dept, currentDepartmentData.value.id))) {
if (
isEdit.value &&
currentDepartmentData.value &&
(dept.id === currentDepartmentData.value.id ||
isChildDepartment(dept, currentDepartmentData.value.id))
) {
return;
}
const prefix = ' '.repeat(level);
options.push({
label: `${prefix}${dept.name}`,
@@ -67,13 +78,16 @@ const parentDepartmentOptions = computed(() => {
}
});
};
addDepartmentOptions(props.departmentList);
return options;
});
// 检查是否为子部门
function isChildDepartment(department: DepartmentVO.DepartmentInfoVO, parentId: number): boolean {
function isChildDepartment(
department: DepartmentVO.DepartmentInfoVO,
parentId: number,
): boolean {
if (department.children) {
for (const child of department.children) {
if (child.id === parentId || isChildDepartment(child, parentId)) {
@@ -85,7 +99,7 @@ function isChildDepartment(department: DepartmentVO.DepartmentInfoVO, parentId:
}
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑部门' : '添加部门');
const modalTitle = computed(() => (isEdit.value ? '编辑部门' : '添加部门'));
// 重置表单
function resetForm() {
@@ -108,13 +122,13 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
// 转换boolean值为number值
const submitData = {
...formData.value,
status: formData.value.status ? 1 : 0
status: formData.value.status ? 1 : 0,
};
if (isEdit.value && currentDepartmentData.value) {
await updateDepartmentApi(currentDepartmentData.value.id, submitData);
message.success('更新成功');
@@ -122,7 +136,7 @@ async function handleSubmit() {
await createDepartmentApi(submitData);
message.success('创建成功');
}
visible.value = false;
emit('success');
} catch (error) {
@@ -134,12 +148,15 @@ async function handleSubmit() {
}
// 暴露给父组件的方法
function open(editMode: boolean = false, departmentData?: DepartmentVO.DepartmentInfoVO | null) {
function open(
editMode: boolean = false,
departmentData?: DepartmentVO.DepartmentInfoVO | null,
) {
isEdit.value = editMode;
currentDepartmentData.value = departmentData || null;
resetForm();
if (editMode && departmentData) {
formData.value = {
name: departmentData.name,
@@ -148,7 +165,7 @@ function open(editMode: boolean = false, departmentData?: DepartmentVO.Departmen
status: departmentData.status === 1, // 转换为boolean
};
}
visible.value = true;
}
@@ -181,15 +198,23 @@ defineExpose({
allow-clear
/>
</Form.Item>
<Form.Item label="部门名称" name="name" :rules="[{ required: true, message: '请输入部门名称' }]">
<Form.Item
label="部门名称"
name="name"
:rules="[{ required: true, message: '请输入部门名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入部门名称" />
</Form.Item>
<Form.Item label="描述" name="remark">
<Input.TextArea v-model:value="formData.remark" placeholder="请输入部门描述" :rows="3" />
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入部门描述"
:rows="3"
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
@@ -1,26 +1,31 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteDepartmentApi,
getDepartmentPageApi,
type DepartmentVO,
type DepartmentDTO
import type {
DepartmentDTO,
DepartmentVO,
} from '#/api/organization/department';
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, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteDepartmentApi,
getDepartmentPageApi,
} from '#/api/organization/department';
import DepartmentModal from './components/DepartmentModal.vue';
defineOptions({ name: 'DepartmentManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'DepartmentManagement' });
// 响应式数据
const loading = ref(false);
const departmentModalRef = ref();
@@ -41,10 +46,15 @@ const statusOptions = [
// 父部门选项
const parentDepartmentOptions = computed(() => {
const options: Array<{ label: string; value: number | undefined }> = [{ label: '根部门', value: undefined }];
const addDepartmentOptions = (departments: DepartmentVO.DepartmentInfoVO[], level = 0) => {
departments.forEach(dept => {
const options: Array<{ label: string; value: number | undefined }> = [
{ label: '根部门', value: undefined },
];
const addDepartmentOptions = (
departments: DepartmentVO.DepartmentInfoVO[],
level = 0,
) => {
departments.forEach((dept) => {
const prefix = ' '.repeat(level);
options.push({
label: `${prefix}${dept.name}`,
@@ -55,7 +65,7 @@ const parentDepartmentOptions = computed(() => {
}
});
};
addDepartmentOptions(departmentList.value);
return options;
});
@@ -116,7 +126,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -156,7 +184,10 @@ const gridOptions: VxeGridProps<any> = {
};
// 查找父部门
function findParentDepartment(departments: DepartmentVO.DepartmentInfoVO[], parentId: number): DepartmentVO.DepartmentInfoVO | null {
function findParentDepartment(
departments: DepartmentVO.DepartmentInfoVO[],
parentId: number,
): DepartmentVO.DepartmentInfoVO | null {
for (const dept of departments) {
if (dept.id === parentId) {
return dept;
@@ -258,9 +289,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -275,7 +304,9 @@ const [Grid, gridApi] = useVbenVxeGrid({
<template #parentDepartment="{ row }: { row: any }">
<span v-if="!row.parentId">根部门</span>
<span v-else>
{{ findParentDepartment(departmentList, row.parentId)?.name || '未知' }}
{{
findParentDepartment(departmentList, row.parentId)?.name || '未知'
}}
</span>
</template>
@@ -289,12 +320,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
@@ -1,52 +1,69 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Button, Card, Input, message, Pagination, Select, Spin, Tree, Flex } from 'ant-design-vue'
import { Page } from '@vben/common-ui'
import { getPositionPageApi } from '#/api/organization/position'
import { getCompanyMenuTreeApi } from '#/api/organization/company-menu'
import { getPositionCompanyMenuIdsApi, batchUpdatePositionCompanyMenusApi } from '#/api/organization/position-permission'
import type { PositionVO } from '#/api/organization/position/types'
import type { CompanyMenuVO } from '#/api/organization/company-menu/types'
import type { CompanyMenuVO } from '#/api/organization/company-menu/types';
import type { PositionVO } from '#/api/organization/position/types';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import {
Button,
Card,
Flex,
Input,
message,
Pagination,
Select,
Spin,
Tree,
} from 'ant-design-vue';
import { getCompanyMenuTreeApi } from '#/api/organization/company-menu';
import { getPositionPageApi } from '#/api/organization/position';
import {
batchUpdatePositionCompanyMenusApi,
getPositionCompanyMenuIdsApi,
} from '#/api/organization/position-permission';
defineOptions({
name: 'PositionPermissionPage',
})
});
// 搜索表单
const searchForm = ref({
name: '',
status: undefined as number | undefined,
})
});
// 岗位列表
const positionList = ref<PositionVO.PositionInfoVO[]>([])
const positionLoading = ref(false)
const positionList = ref<PositionVO.PositionInfoVO[]>([]);
const positionLoading = ref(false);
const positionPagination = ref({
current: 1,
pageSize: 10,
total: 0,
})
});
// 当前选中的岗位
const currentPosition = ref<PositionVO.PositionInfoVO | null>(null)
const currentPosition = ref<null | PositionVO.PositionInfoVO>(null);
// 公司菜单树数据
const companyMenuTree = ref<CompanyMenuVO.CompanyMenuInfo[]>([])
const menuTreeLoading = ref(false)
const companyMenuTree = ref<CompanyMenuVO.CompanyMenuInfo[]>([]);
const menuTreeLoading = ref(false);
// 岗位权限菜单ID列表
const positionMenuIds = ref<number[]>([])
const permissionLoading = ref(false)
const positionMenuIds = ref<number[]>([]);
const permissionLoading = ref(false);
// 选中的菜单ID(用于树形控件)
const checkedKeys = ref<number[]>([])
const expandedKeys = ref<number[]>([])
const checkedKeys = ref<number[]>([]);
const expandedKeys = ref<number[]>([]);
// 不区分超管与普通菜单
// 搜索岗位列表
async function searchPositions() {
positionLoading.value = true
positionLoading.value = true;
try {
const params = {
page: positionPagination.value.current,
@@ -55,113 +72,118 @@ async function searchPositions() {
name: searchForm.value.name || undefined,
status: searchForm.value.status,
},
}
const result = await getPositionPageApi(params)
positionList.value = result.records
positionPagination.value.total = result.total
};
const result = await getPositionPageApi(params);
positionList.value = result.records;
positionPagination.value.total = result.total;
} catch (error: any) {
message.error(error?.message || '获取岗位列表失败')
message.error(error?.message || '获取岗位列表失败');
} finally {
positionLoading.value = false
positionLoading.value = false;
}
}
// 加载公司菜单树
async function loadCompanyMenuTree() {
menuTreeLoading.value = true
menuTreeLoading.value = true;
try {
const result = await getCompanyMenuTreeApi()
companyMenuTree.value = result
const result = await getCompanyMenuTreeApi();
companyMenuTree.value = result;
// 自动展开所有节点
expandedKeys.value = getAllMenuIds(result)
expandedKeys.value = getAllMenuIds(result);
} catch (error: any) {
message.error(error?.message || '获取菜单树失败')
message.error(error?.message || '获取菜单树失败');
} finally {
menuTreeLoading.value = false
menuTreeLoading.value = false;
}
}
// 获取所有菜单ID(递归)
function getAllMenuIds(menus: CompanyMenuVO.CompanyMenuInfo[]): number[] {
const ids: number[] = []
const ids: number[] = [];
function traverse(menuList: CompanyMenuVO.CompanyMenuInfo[]) {
menuList.forEach(menu => {
ids.push(menu.id)
menuList.forEach((menu) => {
ids.push(menu.id);
if (menu.children && menu.children.length > 0) {
traverse(menu.children)
traverse(menu.children);
}
})
});
}
traverse(menus)
return ids
traverse(menus);
return ids;
}
// 将菜单数据转换为Tree组件需要的格式
function convertToTreeData(menus: CompanyMenuVO.CompanyMenuInfo[]): any[] {
return menus.map(menu => ({
return menus.map((menu) => ({
key: menu.id,
title: menu.name,
type: menu.type,
superMenu: menu.superMenu,
status: menu.status,
disabled: menu.status === 0,
children: menu.children && menu.children.length > 0 ? convertToTreeData(menu.children) : undefined,
}))
children:
menu.children && menu.children.length > 0
? convertToTreeData(menu.children)
: undefined,
}));
}
// 选择岗位
async function selectPosition(position: PositionVO.PositionInfoVO) {
currentPosition.value = position
await loadPositionPermissions()
currentPosition.value = position;
await loadPositionPermissions();
}
// 加载岗位权限
async function loadPositionPermissions() {
if (!currentPosition.value?.id) return
permissionLoading.value = true
if (!currentPosition.value?.id) return;
permissionLoading.value = true;
try {
const result = await getPositionCompanyMenuIdsApi(currentPosition.value.id)
positionMenuIds.value = result
const result = await getPositionCompanyMenuIdsApi(currentPosition.value.id);
positionMenuIds.value = result;
// 清理根节点,只保留叶子节点
const leafMenuIds = cleanRootNodes(result)
checkedKeys.value = leafMenuIds
const leafMenuIds = cleanRootNodes(result);
checkedKeys.value = leafMenuIds;
} catch (error: any) {
message.error(error?.message || '获取岗位权限失败')
message.error(error?.message || '获取岗位权限失败');
} finally {
permissionLoading.value = false
permissionLoading.value = false;
}
}
// 清理根节点,只保留叶子节点
function cleanRootNodes(menuIds: number[]): number[] {
return menuIds.filter((menuId) => {
const menu = findMenuById(menuId)
if (!menu) return false
const menu = findMenuById(menuId);
if (!menu) return false;
// 检查是否有其他菜单将此菜单作为父菜单
const hasChildren = hasMenuChildren(menuId)
const hasChildren = hasMenuChildren(menuId);
// 只保留叶子节点(没有子节点的菜单)
return !hasChildren
})
return !hasChildren;
});
}
// 根据ID查找菜单
function findMenuById(menuId: number): CompanyMenuVO.CompanyMenuInfo | null {
function search(menus: CompanyMenuVO.CompanyMenuInfo[]): CompanyMenuVO.CompanyMenuInfo | null {
function search(
menus: CompanyMenuVO.CompanyMenuInfo[],
): CompanyMenuVO.CompanyMenuInfo | null {
for (const menu of menus) {
if (menu.id === menuId) return menu
if (menu.id === menuId) return menu;
if (menu.children && menu.children.length > 0) {
const found = search(menu.children)
if (found) return found
const found = search(menu.children);
if (found) return found;
}
}
return null
return null;
}
return search(companyMenuTree.value)
return search(companyMenuTree.value);
}
// 检查菜单是否有子菜单
@@ -169,208 +191,231 @@ function hasMenuChildren(menuId: number): boolean {
function search(menus: CompanyMenuVO.CompanyMenuInfo[]): boolean {
for (const menu of menus) {
if (menu.children && menu.children.length > 0) {
if (menu.children.some(child => child.id === menuId)) return true
if (search(menu.children)) return true
if (menu.children.some((child) => child.id === menuId)) return true;
if (search(menu.children)) return true;
}
}
return false
return false;
}
return search(companyMenuTree.value)
return search(companyMenuTree.value);
}
// 确保提交时包含必要的父菜单ID(递归添加所有层级的父菜单)
function ensureParentMenuIds(menuIds: number[]): number[] {
const result = new Set(menuIds)
const result = new Set(menuIds);
// 递归添加所有父菜单ID
function addAllParentIds(menuId: number) {
const menu = findMenuById(menuId)
const menu = findMenuById(menuId);
if (menu && menu.parentId) {
result.add(menu.parentId)
result.add(menu.parentId);
// 递归添加父菜单的父菜单
addAllParentIds(menu.parentId)
addAllParentIds(menu.parentId);
}
}
// 为每个选中的菜单添加其所有父菜单ID
menuIds.forEach((menuId) => {
addAllParentIds(menuId)
})
return [...result]
addAllParentIds(menuId);
});
return [...result];
}
// 保存岗位权限
async function savePositionPermissions() {
if (!currentPosition.value?.id) return
if (!currentPosition.value?.id) return;
try {
// 确保提交时包含必要的父菜单ID
const finalMenuIds = ensureParentMenuIds(checkedKeys.value)
await batchUpdatePositionCompanyMenusApi(currentPosition.value.id, finalMenuIds)
message.success('权限配置保存成功')
const finalMenuIds = ensureParentMenuIds(checkedKeys.value);
await batchUpdatePositionCompanyMenusApi(
currentPosition.value.id,
finalMenuIds,
);
message.success('权限配置保存成功');
// 重新加载权限数据
await loadPositionPermissions()
await loadPositionPermissions();
} catch (error: any) {
message.error(error?.message || '保存失败')
message.error(error?.message || '保存失败');
}
}
// 一键全选
function handleSelectAll() {
// 获取所有可选择的菜单ID(排除禁用的)
let selectableMenus = getAllSelectableMenus()
const selectableMenus = getAllSelectableMenus();
// 只选择叶子节点(没有子节点的菜单)
const leafMenus = selectableMenus.filter((menu) => {
return !hasMenuChildren(menu.id)
})
return !hasMenuChildren(menu.id);
});
// 全选所有叶子节点
checkedKeys.value = leafMenus.map((menu) => menu.id)
checkedKeys.value = leafMenus.map((menu) => menu.id);
}
// 取消全选
function handleSelectNone() {
// 取消所有叶子节点的选中状态
const allLeafMenuIds = getAllSelectableMenus()
.filter((menu) => !hasMenuChildren(menu.id))
.map((menu) => menu.id)
checkedKeys.value = checkedKeys.value.filter((id) => !allLeafMenuIds.includes(id))
const allLeafMenuIds = new Set(
getAllSelectableMenus()
.filter((menu) => !hasMenuChildren(menu.id))
.map((menu) => menu.id),
);
checkedKeys.value = checkedKeys.value.filter((id) => !allLeafMenuIds.has(id));
}
// 获取所有可选择的菜单
function getAllSelectableMenus(): CompanyMenuVO.CompanyMenuInfo[] {
const result: CompanyMenuVO.CompanyMenuInfo[] = []
const result: CompanyMenuVO.CompanyMenuInfo[] = [];
function traverse(menus: CompanyMenuVO.CompanyMenuInfo[]) {
menus.forEach(menu => {
if (menu.status === 1) { // 只包含启用的菜单
result.push(menu)
menus.forEach((menu) => {
if (menu.status === 1) {
// 只包含启用的菜单
result.push(menu);
}
if (menu.children && menu.children.length > 0) {
traverse(menu.children)
traverse(menu.children);
}
})
});
}
traverse(companyMenuTree.value)
return result
traverse(companyMenuTree.value);
return result;
}
// 处理树形控件的选中变化
function handleTreeCheckChange(checkedKeysValue: any) {
checkedKeys.value = checkedKeysValue
checkedKeys.value = checkedKeysValue;
}
// 计算统计信息
const stats = computed(() => {
const totalMenus = getAllSelectableMenus().length
const positionMenus = positionMenuIds.value.length
const selectedMenus = ensureParentMenuIds(checkedKeys.value).length
const totalMenus = getAllSelectableMenus().length;
const positionMenus = positionMenuIds.value.length;
const selectedMenus = ensureParentMenuIds(checkedKeys.value).length;
return {
total: totalMenus,
position: positionMenus,
selected: selectedMenus,
}
})
};
});
// 重置搜索
function resetSearch() {
searchForm.value = {
name: '',
status: undefined,
}
positionPagination.value.current = 1
searchPositions()
};
positionPagination.value.current = 1;
searchPositions();
}
// 分页变化
function handlePageChange(page: number, pageSize: number) {
positionPagination.value.current = page
positionPagination.value.pageSize = pageSize
searchPositions()
positionPagination.value.current = page;
positionPagination.value.pageSize = pageSize;
searchPositions();
}
// 初始化
onMounted(() => {
searchPositions()
loadCompanyMenuTree()
})
searchPositions();
loadCompanyMenuTree();
});
</script>
<template>
<Page
:auto-content-height="true"
>
<Page :auto-content-height="true">
<Flex gap="middle" class="h-full">
<!-- 左栏:岗位列表 -->
<Card title="岗位列表" class="h-full flex flex-col max-w-[400px]" :bodyStyle="{ height: '100%', display: 'flex', flexDirection: 'column',gap: '10px' }">
<Card
title="岗位列表"
class="flex h-full max-w-[400px] flex-col"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}"
>
<!-- 搜索区域 -->
<Flex class="flex-wrap gap-2">
<Input
v-model:value="searchForm.name"
placeholder="请输入岗位名称"
allow-clear
style="width: 200px; margin-right: 8px"
/>
<Select
v-model:value="searchForm.status"
placeholder="请选择状态"
allow-clear
style="width: 120px; margin-right: 8px"
>
<Select.Option :value="1">启用</Select.Option>
<Select.Option :value="0">禁用</Select.Option>
</Select>
<Button type="primary" @click="searchPositions">
搜索
</Button>
<Button @click="resetSearch">
重置
</Button>
v-model:value="searchForm.name"
placeholder="请输入岗位名称"
allow-clear
style="width: 200px; margin-right: 8px"
/>
<Select
v-model:value="searchForm.status"
placeholder="请选择状态"
allow-clear
style="width: 120px; margin-right: 8px"
>
<Select.Option :value="1">启用</Select.Option>
<Select.Option :value="0">禁用</Select.Option>
</Select>
<Button type="primary" @click="searchPositions"> 搜索 </Button>
<Button @click="resetSearch"> 重置 </Button>
</Flex>
<!-- 岗位列表区域 -->
<Flex vertical class="flex-1">
<Flex vertical class="flex-1">
<!-- 岗位列表 -->
<Flex vertical class="flex-1">
<Spin :spinning="positionLoading">
<Card
v-for="position in positionList"
:key="position.id"
hoverable
size="small"
:bodyStyle="{ padding: '10px 12px' }"
:class="[
'group mb-2 cursor-pointer transition-all duration-200',
(currentPosition?.id === position.id) && 'ring-1 ring-primary shadow'
]"
@click="selectPosition(position)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="flex items-center gap-2 mb-1">
<span
class="inline-block h-2 w-2 rounded-full"
:class="position.status === 1 ? 'bg-green-500' : 'bg-red-500'"
/>
<span class="text-sm font-semibold text-[var(--text-primary)] truncate">{{ position.name }}</span>
v-for="position in positionList"
:key="position.id"
hoverable
size="small"
:body-style="{ padding: '10px 12px' }"
class="group mb-2 cursor-pointer transition-all duration-200"
:class="[
currentPosition?.id === position.id &&
'ring-primary shadow ring-1',
]"
@click="selectPosition(position)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="mb-1 flex items-center gap-2">
<span
class="inline-block h-2 w-2 rounded-full"
:class="
position.status === 1 ? 'bg-green-500' : 'bg-red-500'
"
></span>
<span
class="truncate text-sm font-semibold text-[var(--text-primary)]"
>
{{ position.name }}
</span>
</div>
<div class="mb-1 text-xs text-[var(--text-secondary)]">
编码:{{ position.code }}
</div>
<div
v-if="position.remark"
class="truncate text-xs text-[var(--text-secondary)]"
>
{{ position.remark }}
</div>
</div>
<div class="text-xs text-[var(--text-secondary)] mb-1">编码:{{ position.code }}</div>
<div v-if="position.remark" class="text-xs text-[var(--text-secondary)] truncate">{{ position.remark }}</div>
<Tag :color="position.status === 1 ? 'green' : 'red'">
{{ position.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
<Tag :color="position.status === 1 ? 'green' : 'red'">
{{ position.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
</Card>
</Spin>
</Flex>
<!-- 分页器 -->
<Flex justify="center">
<Flex justify="center">
<Pagination
v-model:current="positionPagination.current"
v-model:page-size="positionPagination.pageSize"
@@ -380,78 +425,97 @@ onMounted(() => {
:show-total="(total) => `共 ${total} 条`"
@change="handlePageChange"
/>
</Flex>
</Flex>
</Flex>
</Card>
<!-- 右栏:权限管理 -->
<Card title="权限管理" class="h-full flex flex-col flex-1" :bodyStyle="{ height: '100%' }">
<template v-if="currentPosition">
<!-- 岗位信息 + 统计与操作 -->
<div class="p-4 rounded mb-4 bg-gray-50 dark:bg-neutral-800">
<div class="flex items-center justify-between gap-2 mb-3">
<div class="flex items-center gap-2">
<span class="text-base font-semibold">{{ currentPosition.name }}</span>
</div>
<div class="flex items-center gap-2">
<Button @click="handleSelectNone">取消全选</Button>
<Button type="primary" @click="handleSelectAll">一键全选</Button>
<Button type="primary" @click="savePositionPermissions">保存权限</Button>
</div>
<Card
title="权限管理"
class="flex h-full flex-1 flex-col"
:body-style="{ height: '100%' }"
>
<template v-if="currentPosition">
<!-- 岗位信息 + 统计与操作 -->
<div class="mb-4 rounded bg-gray-50 p-4 dark:bg-neutral-800">
<div class="mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<span class="text-base font-semibold">{{
currentPosition.name
}}</span>
</div>
<div class="flex items-center gap-6 text-xs text-gray-500">
<span>编码:{{ currentPosition.code }}</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">系统菜单:</span>
<span class="font-semibold text-sm">{{ stats.total }}</span>
</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">已配置:</span>
<span class="font-semibold text-sm text-[var(--success)]">{{ stats.position }}</span>
</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">当前选择:</span>
<span class="font-semibold text-sm text-[var(--primary)]">{{ stats.selected }}</span>
</span>
<div class="flex items-center gap-2">
<Button @click="handleSelectNone">取消全选</Button>
<Button type="primary" @click="handleSelectAll">
一键全选
</Button>
<Button type="primary" @click="savePositionPermissions">
保存权限
</Button>
</div>
</div>
<!-- 菜单树 -->
<div class="flex-1 overflow-y-auto min-h-0">
<Spin :spinning="permissionLoading">
<Tree
v-model:checked-keys="checkedKeys"
v-model:expanded-keys="expandedKeys"
:tree-data="convertToTreeData(companyMenuTree)"
checkable
block-node
class="border rounded"
@check="handleTreeCheckChange"
>
<template #title="{ title, status, disabled }">
<div class="flex items-center gap-2">
<span class="font-medium">{{ title }}</span>
<span v-if="status === 0" class="text-red-600 bg-red-50 dark:bg-red-900/30 text-xs px-1.5 py-0.5 rounded">
已禁用
</span>
<span v-if="disabled" class="text-red-600 bg-red-50 dark:bg-red-900/30 text-xs px-1.5 py-0.5 rounded">
不可选择
</span>
</div>
</template>
</Tree>
</Spin>
</div>
</template>
<div v-else class="flex-1 flex items-center justify-center h-full">
<div class="text-center text-gray-500">
<div class="text-5xl mb-4">👈</div>
<div class="text-base">请先选择一个岗位</div>
<div class="flex items-center gap-6 text-xs text-gray-500">
<span>编码:{{ currentPosition.code }}</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">系统菜单:</span>
<span class="text-sm font-semibold">{{ stats.total }}</span>
</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">已配置:</span>
<span class="text-sm font-semibold text-[var(--success)]">{{
stats.position
}}</span>
</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">当前选择:</span>
<span class="text-sm font-semibold text-[var(--primary)]">{{
stats.selected
}}</span>
</span>
</div>
</div>
</Card>
<!-- 菜单树 -->
<div class="min-h-0 flex-1 overflow-y-auto">
<Spin :spinning="permissionLoading">
<Tree
v-model:checked-keys="checkedKeys"
v-model:expanded-keys="expandedKeys"
:tree-data="convertToTreeData(companyMenuTree)"
checkable
block-node
class="rounded border"
@check="handleTreeCheckChange"
>
<template #title="{ title, status, disabled }">
<div class="flex items-center gap-2">
<span class="font-medium">{{ title }}</span>
<span
v-if="status === 0"
class="rounded bg-red-50 px-1.5 py-0.5 text-xs text-red-600 dark:bg-red-900/30"
>
已禁用
</span>
<span
v-if="disabled"
class="rounded bg-red-50 px-1.5 py-0.5 text-xs text-red-600 dark:bg-red-900/30"
>
不可选择
</span>
</div>
</template>
</Tree>
</Spin>
</div>
</template>
<div v-else class="flex h-full flex-1 items-center justify-center">
<div class="text-center text-gray-500">
<div class="mb-4 text-5xl">👈</div>
<div class="text-base">请先选择一个岗位</div>
</div>
</div>
</Card>
</Flex>
<!-- <div class="flex h-full gap-4 max-lg:flex-col">
@@ -1,11 +1,13 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { Form, Input, Modal, Select, message, Switch } from 'ant-design-vue';
import type { PositionVO } from '#/api/organization/position';
import {
createPositionApi,
import { computed, ref } from 'vue';
import { Form, Input, message, Modal, Select, Switch } from 'ant-design-vue';
import {
createPositionApi,
updatePositionApi,
type PositionVO
} from '#/api/organization/position';
interface Props {
@@ -25,7 +27,7 @@ const formRef = ref();
const loading = ref(false);
const visible = ref(false);
const isEdit = ref(false);
const currentPositionData = ref<PositionVO.PositionInfoVO | null>(null);
const currentPositionData = ref<null | PositionVO.PositionInfoVO>(null);
// 内部表单数据类型
interface FormData {
@@ -48,7 +50,7 @@ const formData = ref<FormData>({
// 开关组件不需要选项数组
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑岗位' : '添加岗位');
const modalTitle = computed(() => (isEdit.value ? '编辑岗位' : '添加岗位'));
// 重置表单
function resetForm() {
@@ -72,13 +74,13 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
// 转换boolean值为number值
const submitData = {
...formData.value,
status: formData.value.status ? 1 : 0
status: formData.value.status ? 1 : 0,
};
if (isEdit.value && currentPositionData.value) {
await updatePositionApi(currentPositionData.value.id, submitData);
message.success('更新成功');
@@ -86,7 +88,7 @@ async function handleSubmit() {
await createPositionApi(submitData);
message.success('创建成功');
}
visible.value = false;
emit('success');
} catch (error) {
@@ -98,12 +100,15 @@ async function handleSubmit() {
}
// 暴露给父组件的方法
function open(editMode: boolean = false, positionData?: PositionVO.PositionInfoVO | null) {
function open(
editMode: boolean = false,
positionData?: null | PositionVO.PositionInfoVO,
) {
isEdit.value = editMode;
currentPositionData.value = positionData || null;
resetForm();
if (editMode && positionData) {
formData.value = {
name: positionData.name,
@@ -113,7 +118,7 @@ function open(editMode: boolean = false, positionData?: PositionVO.PositionInfoV
status: positionData.status === 1, // 转换为boolean
};
}
visible.value = true;
}
@@ -138,14 +143,18 @@ defineExpose({
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="岗位名称" name="name" :rules="[{ required: true, message: '请输入岗位名称' }]">
<Form.Item
label="岗位名称"
name="name"
:rules="[{ required: true, message: '请输入岗位名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入岗位名称" />
</Form.Item>
<Form.Item label="岗位编码" name="code">
<Input v-model:value="formData.code" placeholder="请输入岗位编码" />
</Form.Item>
<Form.Item label="所属部门" name="departmentId">
<Select
v-model:value="formData.departmentId"
@@ -154,11 +163,15 @@ defineExpose({
allow-clear
/>
</Form.Item>
<Form.Item label="描述" name="remark">
<Input.TextArea v-model:value="formData.remark" placeholder="请输入岗位描述" :rows="3" />
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入岗位描述"
:rows="3"
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
@@ -1,26 +1,28 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PositionDTO, PositionVO } from '#/api/organization/position';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deletePositionApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePositionApi,
getPositionPageApi,
type PositionVO,
type PositionDTO
} from '#/api/organization/position';
import type { PageQueryDTO } from '#/types/common';
import PositionModal from './components/PositionModal.vue';
defineOptions({ name: 'PositionManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'PositionManagement' });
// 响应式数据
const loading = ref(false);
const positionModalRef = ref();
@@ -106,7 +108,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -221,9 +241,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -238,7 +256,10 @@ const [Grid, gridApi] = useVbenVxeGrid({
<template #department="{ row }: { row: any }">
<span v-if="!row.departmentId">-</span>
<span v-else>
{{ departmentOptions.find(d => d.value === row.departmentId)?.label || '未知部门' }}
{{
departmentOptions.find((d) => d.value === row.departmentId)
?.label || '未知部门'
}}
</span>
</template>
@@ -252,12 +273,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
@@ -1,29 +1,29 @@
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Modal, Form, Input, InputNumber, Switch, message } from 'ant-design-vue';
import {
createOrderStatusApi,
updateOrderStatusApi,
} from '#/api/ecommerce';
import type { OrderStatusDTO, OrderStatusVO } from '#/api/ecommerce/types';
defineProps<{
visible?: boolean;
}>();
import { ref, watch } from 'vue';
import {
Form,
Input,
InputNumber,
message,
Modal,
Switch,
} from 'ant-design-vue';
import { createOrderStatusApi, updateOrderStatusApi } from '#/api/ecommerce';
const emit = defineEmits<{
success: [];
cancel: [];
success: [];
}>();
// 响应式数据
const visible = ref(false);
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<OrderStatusVO.Info | null>(null);
const currentRecord = ref<null | OrderStatusVO.Info>(null);
// 表单数据
const formData = ref<Partial<OrderStatusDTO.Create>>({
@@ -47,24 +47,22 @@ function open(edit: boolean, record?: OrderStatusVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
visible.value = true;
if (edit && record) {
// 编辑模式,填充表单数据
formData.value = {
statusName: record.statusName,
description: record.description || '',
isActive: record.isActive,
sortOrder: record.sortOrder || 0,
};
} else {
// 新增模式,重置表单
formData.value = {
statusName: '',
description: '',
isActive: 1,
sortOrder: 0,
};
}
// 根据模式填充表单数据
formData.value =
edit && record
? {
statusName: record.statusName,
description: record.description || '',
isActive: record.isActive,
sortOrder: record.sortOrder || 0,
}
: {
statusName: '',
description: '',
isActive: 1,
sortOrder: 0,
};
}
// 关闭模态框
@@ -106,7 +104,7 @@ async function handleSubmit() {
close();
emit('success');
} catch (error) {
console.error('提交订单状态失败:', ( error as any).message );
console.error('提交订单状态失败:', (error as any).message);
} finally {
loading.value = false;
}
@@ -143,33 +141,33 @@ defineExpose({
>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="状态名称" name="statusName">
<Input
v-model:value="formData.statusName"
<Input
v-model:value="formData.statusName"
placeholder="请输入状态名称"
/>
</Form.Item>
</div>
<Form.Item label="状态描述" name="description">
<Input.TextArea
v-model:value="formData.description"
<Input.TextArea
v-model:value="formData.description"
placeholder="请输入状态描述(可选)"
:rows="3"
/>
</Form.Item>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="排序" name="sortOrder">
<InputNumber
v-model:value="formData.sortOrder"
<InputNumber
v-model:value="formData.sortOrder"
placeholder="请输入排序"
style="width: 100%"
:min="0"
/>
</Form.Item>
<Form.Item label="启用状态" name="isActive">
<Switch
<Switch
v-model:checked="formData.isActive"
:checked-value="1"
:un-checked-value="0"
@@ -1,24 +1,27 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { OrderStatusVO } from '#/api/ecommerce/types';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteOrderStatusApi,
getAllOrderStatusListApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteOrderStatusApi,
getAllOrderStatusListApi,
} from '#/api/ecommerce';
import type { OrderStatusVO } from '#/api/ecommerce/types';
import OrderStatusFormModal from './components/OrderStatusFormModal.vue';
defineOptions({ name: 'OrderStatusConfig' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'OrderStatusConfig' });
// 响应式数据
const loading = ref(false);
const orderStatusFormModalRef = ref();
@@ -47,7 +50,7 @@ const gridOptions: VxeGridProps<any> = {
field: 'sortOrder',
title: '排序',
minWidth: 'auto',
},
},
{
title: '状态',
minWidth: 'auto',
@@ -213,12 +216,8 @@ function handleModalSuccess() {
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
@@ -1,29 +1,36 @@
<script lang="ts" setup>
import type {
PromotionFeeTypeDTO,
PromotionFeeTypeVO,
} from '#/api/ecommerce/types';
import { ref, watch } from 'vue';
import { Modal, Form, Input, InputNumber, Select, Switch, message } from 'ant-design-vue';
import {
Form,
Input,
InputNumber,
message,
Modal,
Select,
Switch,
} from 'ant-design-vue';
import {
createPromotionFeeTypeApi,
updatePromotionFeeTypeApi,
import {
createPromotionFeeTypeApi,
updatePromotionFeeTypeApi,
} from '#/api/ecommerce';
import type { PromotionFeeTypeDTO, PromotionFeeTypeVO } from '#/api/ecommerce/types';
defineProps<{
visible?: boolean;
}>();
const emit = defineEmits<{
success: [];
cancel: [];
success: [];
}>();
// 响应式数据
const visible = ref(false);
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<PromotionFeeTypeVO.Info | null>(null);
const currentRecord = ref<null | PromotionFeeTypeVO.Info>(null);
// 表单数据
const formData = ref<Partial<PromotionFeeTypeDTO.Create>>({
@@ -57,26 +64,24 @@ function open(edit: boolean, record?: PromotionFeeTypeVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
visible.value = true;
if (edit && record) {
// 编辑模式,填充表单数据
formData.value = {
typeName: record.typeName,
description: record.description || '',
calculationMethod: record.calculationMethod || 1,
sortOrder: record.sortOrder || 0,
isActive: record.isActive || 1,
};
} else {
// 新增模式,重置表单
formData.value = {
typeName: '',
description: '',
calculationMethod: 1,
sortOrder: 0,
isActive: 1,
};
}
// 根据模式填充表单数据
formData.value =
edit && record
? {
typeName: record.typeName,
description: record.description || '',
calculationMethod: record.calculationMethod || 1,
sortOrder: record.sortOrder || 0,
isActive: record.isActive || 1,
}
: {
typeName: '',
description: '',
calculationMethod: 1,
sortOrder: 0,
isActive: 1,
};
}
// 关闭模态框
@@ -120,7 +125,7 @@ async function handleSubmit() {
close();
emit('success');
} catch (error) {
console.error('提交推广费类型失败:', ( error as any).message );
console.error('提交推广费类型失败:', (error as any).message);
} finally {
loading.value = false;
}
@@ -156,43 +161,42 @@ defineExpose({
layout="vertical"
>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="类型名称" name="typeName">
<Input
v-model:value="formData.typeName"
<Input
v-model:value="formData.typeName"
placeholder="请输入类型名称"
/>
</Form.Item>
</div>
<Form.Item label="类型描述" name="description">
<Input.TextArea
v-model:value="formData.description"
<Input.TextArea
v-model:value="formData.description"
placeholder="请输入类型描述(可选)"
:rows="3"
/>
</Form.Item>
<div class="grid grid-cols-3 gap-4">
<Form.Item label="计算方式" name="calculationMethod">
<Select
v-model:value="formData.calculationMethod"
<Select
v-model:value="formData.calculationMethod"
placeholder="请选择计算方式"
:options="calculationMethodOptions"
/>
</Form.Item>
<Form.Item label="排序" name="sortOrder">
<InputNumber
v-model:value="formData.sortOrder"
<InputNumber
v-model:value="formData.sortOrder"
placeholder="请输入排序"
style="width: 100%"
:min="0"
/>
</Form.Item>
<Form.Item label="启用状态" name="isActive">
<Switch
<Switch
v-model:checked="formData.isActive"
:checked-value="1"
:un-checked-value="0"
@@ -1,24 +1,27 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PromotionFeeTypeVO } from '#/api/ecommerce/types';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deletePromotionFeeTypeApi,
getAllPromotionFeeTypeListApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePromotionFeeTypeApi,
getAllPromotionFeeTypeListApi,
} from '#/api/ecommerce';
import type { PromotionFeeTypeVO } from '#/api/ecommerce/types';
import PromotionFeeTypeFormModal from './components/PromotionFeeTypeFormModal.vue';
defineOptions({ name: 'PromotionFeeTypeConfig' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'PromotionFeeTypeConfig' });
// 响应式数据
const loading = ref(false);
const promotionFeeTypeFormModalRef = ref();
@@ -219,7 +222,11 @@ function handleModalSuccess() {
<!-- 计算方式列 -->
<template #calculationMethod="{ row }: { row: any }">
<Tag color="blue">
{{ calculationMethodOptions.find(opt => opt.value === row.calculationMethod)?.label || '未设置' }}
{{
calculationMethodOptions.find(
(opt) => opt.value === row.calculationMethod,
)?.label || '未设置'
}}
</Tag>
</template>
@@ -233,12 +240,8 @@ function handleModalSuccess() {
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
@@ -1,32 +1,37 @@
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Modal, Form, Input, Select, InputNumber, DatePicker, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import {
createOrderApi,
updateOrderApi,
getActiveOrderStatusListApi,
} from '#/api/ecommerce';
import type { OrderDTO, OrderVO, OrderStatusVO } from '#/api/ecommerce/types';
import { getShopPageApi } from '#/api/shop/shop';
import type { OrderDTO, OrderStatusVO, OrderVO } from '#/api/ecommerce/types';
import type { ShopVO } from '#/api/shop/shop/types';
defineProps<{
visible?: boolean;
}>();
import { ref, watch } from 'vue';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Modal,
Select,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
createOrderApi,
getActiveOrderStatusListApi,
updateOrderApi,
} from '#/api/ecommerce';
import { getShopPageApi } from '#/api/shop/shop';
const emit = defineEmits<{
success: [];
cancel: [];
success: [];
}>();
// 响应式数据
const visible = ref(false);
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<OrderVO.Info | null>(null);
const currentRecord = ref<null | OrderVO.Info>(null);
// 表单数据
const formData = ref<Partial<OrderDTO.Create>>({
@@ -54,7 +59,9 @@ const orderStatusOptions = ref<{ label: string; value: number }[]>([]);
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
statusId: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
receivedAmount: [{ required: true, message: '请输入实收金额', trigger: 'blur' }],
receivedAmount: [
{ required: true, message: '请输入实收金额', trigger: 'blur' },
],
orderDate: [{ required: true, message: '请选择下单时间', trigger: 'change' }],
productId: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
@@ -103,44 +110,44 @@ function open(edit: boolean, record?: OrderVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
visible.value = true;
if (edit && record) {
// 编辑模式,填充表单数据
formData.value = {
shopId: record.shopId,
platformOrderNo: record.platformOrderNo || '',
statusId: record.statusId,
receivedAmount: record.receivedAmount,
shippingFee: record.shippingFee || 0,
orderDate: record.orderDate ? dayjs(record.orderDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
productId: record.productId,
productSpecId: record.productSpecId,
productName: record.productName,
specName: record.specName,
quantity: record.quantity,
unitPrice: record.unitPrice,
costPrice: record.costPrice,
costTotal: record.costTotal,
};
} else {
// 新增模式,重置表单
formData.value = {
shopId: undefined,
platformOrderNo: '',
statusId: undefined,
receivedAmount: 0,
shippingFee: 0,
orderDate: dayjs().format('YYYY-MM-DD'),
productId: undefined,
productSpecId: undefined,
productName: '',
specName: '',
quantity: 1,
unitPrice: 0,
costPrice: 0,
costTotal: 0,
};
}
// 根据模式填充表单数据
formData.value =
edit && record
? {
shopId: record.shopId,
platformOrderNo: record.platformOrderNo || '',
statusId: record.statusId,
receivedAmount: record.receivedAmount,
shippingFee: record.shippingFee || 0,
orderDate: record.orderDate
? dayjs(record.orderDate).format('YYYY-MM-DD')
: dayjs().format('YYYY-MM-DD'),
productId: record.productId,
productSpecId: record.productSpecId,
productName: record.productName,
specName: record.specName,
quantity: record.quantity,
unitPrice: record.unitPrice,
costPrice: record.costPrice,
costTotal: record.costTotal,
}
: {
shopId: undefined,
platformOrderNo: '',
statusId: undefined,
receivedAmount: 0,
shippingFee: 0,
orderDate: dayjs().format('YYYY-MM-DD'),
productId: undefined,
productSpecId: undefined,
productName: '',
specName: '',
quantity: 1,
unitPrice: 0,
costPrice: 0,
costTotal: 0,
};
}
// 关闭模态框
@@ -240,16 +247,16 @@ defineExpose({
>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="店铺" name="shopId">
<Select
v-model:value="formData.shopId"
<Select
v-model:value="formData.shopId"
placeholder="请选择店铺"
:options="shopOptions"
/>
</Form.Item>
<Form.Item label="订单状态" name="statusId">
<Select
v-model:value="formData.statusId"
<Select
v-model:value="formData.statusId"
placeholder="请选择订单状态"
:options="orderStatusOptions"
/>
@@ -258,15 +265,15 @@ defineExpose({
<div class="grid grid-cols-2 gap-4">
<Form.Item label="平台订单号" name="platformOrderNo">
<Input
v-model:value="formData.platformOrderNo"
<Input
v-model:value="formData.platformOrderNo"
placeholder="请输入平台订单号(可选)"
/>
</Form.Item>
<Form.Item label="下单时间" name="orderDate">
<DatePicker
v-model:value="formData.orderDate"
<DatePicker
v-model:value="formData.orderDate"
placeholder="请选择下单时间"
style="width: 100%"
format="YYYY-MM-DD"
@@ -277,17 +284,17 @@ defineExpose({
<div class="grid grid-cols-2 gap-4">
<Form.Item label="商品ID" name="productId">
<InputNumber
v-model:value="formData.productId"
<InputNumber
v-model:value="formData.productId"
placeholder="请输入商品ID"
style="width: 100%"
:min="1"
/>
</Form.Item>
<Form.Item label="商品规格ID" name="productSpecId">
<InputNumber
v-model:value="formData.productSpecId"
<InputNumber
v-model:value="formData.productSpecId"
placeholder="请输入商品规格ID(可选)"
style="width: 100%"
:min="1"
@@ -297,15 +304,15 @@ defineExpose({
<div class="grid grid-cols-2 gap-4">
<Form.Item label="商品名称" name="productName">
<Input
v-model:value="formData.productName"
<Input
v-model:value="formData.productName"
placeholder="请输入商品名称"
/>
</Form.Item>
<Form.Item label="规格名称" name="specName">
<Input
v-model:value="formData.specName"
<Input
v-model:value="formData.specName"
placeholder="请输入规格名称(可选)"
/>
</Form.Item>
@@ -313,27 +320,27 @@ defineExpose({
<div class="grid grid-cols-3 gap-4">
<Form.Item label="数量" name="quantity">
<InputNumber
v-model:value="formData.quantity"
<InputNumber
v-model:value="formData.quantity"
placeholder="请输入数量"
style="width: 100%"
:min="1"
/>
</Form.Item>
<Form.Item label="销售单价" name="unitPrice">
<InputNumber
v-model:value="formData.unitPrice"
<InputNumber
v-model:value="formData.unitPrice"
placeholder="请输入销售单价"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="成本价" name="costPrice">
<InputNumber
v-model:value="formData.costPrice"
<InputNumber
v-model:value="formData.costPrice"
placeholder="请输入成本价"
style="width: 100%"
:min="0"
@@ -344,28 +351,28 @@ defineExpose({
<div class="grid grid-cols-3 gap-4">
<Form.Item label="成本小计" name="costTotal">
<InputNumber
v-model:value="formData.costTotal"
<InputNumber
v-model:value="formData.costTotal"
placeholder="请输入成本小计"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="实收金额" name="receivedAmount">
<InputNumber
v-model:value="formData.receivedAmount"
<InputNumber
v-model:value="formData.receivedAmount"
placeholder="请输入实收金额"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="运费" name="shippingFee">
<InputNumber
v-model:value="formData.shippingFee"
<InputNumber
v-model:value="formData.shippingFee"
placeholder="请输入运费"
style="width: 100%"
:min="0"
@@ -1,29 +1,31 @@
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteOrderApi,
getOrderPageApi,
getActiveOrderStatusListApi
} from '#/api/ecommerce';
import type { OrderVO, OrderDTO, OrderStatusVO } from '#/api/ecommerce/types';
import { getShopPageApi } from '#/api/shop/shop';
import type { OrderDTO, OrderStatusVO, OrderVO } from '#/api/ecommerce/types';
import type { ShopVO } from '#/api/shop/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteOrderApi,
getActiveOrderStatusListApi,
getOrderPageApi,
} from '#/api/ecommerce';
import { getShopPageApi } from '#/api/shop/shop';
import OrderFormModal from './components/OrderFormModal.vue';
defineOptions({ name: 'OrderManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
const UploadIcon = createIconifyIcon('lucide:upload');
defineOptions({ name: 'OrderManagement' });
// 响应式数据
const loading = ref(false);
const orderFormModalRef = ref();
@@ -116,7 +118,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -237,7 +257,6 @@ async function fetchOrderStatusOptions() {
}
}
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
@@ -246,10 +265,6 @@ const [Grid, gridApi] = useVbenVxeGrid({
tableTitle: '订单管理',
});
// 处理添加订单
function handleAdd() {
orderFormModalRef.value?.open(false);
@@ -283,13 +298,9 @@ function handleModalSuccess() {
refreshTable();
}
// 初始化
onMounted(async () => {
await Promise.all([
fetchShopOptions(),
fetchOrderStatusOptions(),
]);
await Promise.all([fetchShopOptions(), fetchOrderStatusOptions()]);
});
</script>
@@ -301,11 +312,8 @@ onMounted(async () => {
</div>
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -314,20 +322,21 @@ onMounted(async () => {
批量导入
</Button>
<Button type="primary" @click="handleAdd">
<PlusIcon />
<PlusIcon />
添加订单
</Button>
</Space>
</template>
<!-- 商品信息列 -->
<template #productInfo="{ row }: { row: any }">
<div v-if="row.productName">
<div style="font-weight: bold;">{{ row.productName }}</div>
<div v-if="row.specName" style="color: #666; font-size: 12px;">{{ row.specName }}</div>
<div style="font-weight: bold">{{ row.productName }}</div>
<div v-if="row.specName" style="color: #666; font-size: 12px">
{{ row.specName }}
</div>
</div>
<span v-else style="color: #999;">暂无商品信息</span>
<span v-else style="color: #999">暂无商品信息</span>
</template>
<!-- 数量列 -->
@@ -337,14 +346,14 @@ onMounted(async () => {
<!-- 实收金额列 -->
<template #receivedAmount="{ row }: { row: any }">
<span style="color: #52c41a; font-weight: bold;">
<span style="color: #52c41a; font-weight: bold">
¥{{ (row.receivedAmount || 0).toFixed(2) }}
</span>
</template>
<!-- 运费列 -->
<template #shippingFee="{ row }: { row: any }">
<span style="color: #666;">
<span style="color: #666">
¥{{ (row.shippingFee || 0).toFixed(2) }}
</span>
</template>
@@ -352,27 +361,24 @@ onMounted(async () => {
<!-- 订单状态列 -->
<template #orderStatus="{ row }: { row: any }">
<Tag color="blue">
{{ orderStatusOptions.find(s => s.value === row.statusId)?.label || row.statusName || '未知状态' }}
{{
orderStatusOptions.find((s) => s.value === row.statusId)?.label ||
row.statusName ||
'未知状态'
}}
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 订单表单模态框 -->
<OrderFormModal
ref="orderFormModalRef"
@success="handleModalSuccess"
/>
<OrderFormModal ref="orderFormModalRef" @success="handleModalSuccess" />
</Page>
</template>
@@ -1,8 +1,20 @@
<script lang="ts" setup>
import { Card, Image, Tag, Button, Space, Popconfirm, Tooltip } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import type { ProductVO } from '#/api/shop/product/types';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
Image,
Popconfirm,
Space,
Tag,
Tooltip,
} from 'ant-design-vue';
defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2');
@@ -16,13 +28,10 @@ interface Props {
interface Emits {
(e: 'edit', product: ProductVO.Info): void;
(e: 'delete', product: ProductVO.Info): void;
(e: 'manage-specs', product: ProductVO.Info): void;
(e: 'view-details', product: ProductVO.Info): void;
(e: 'manageSpecs', product: ProductVO.Info): void;
(e: 'viewDetails', product: ProductVO.Info): void;
}
defineProps<Props>();
const emit = defineEmits<Emits>();
const handleEdit = (product: ProductVO.Info) => {
emit('edit', product);
};
@@ -32,17 +41,19 @@ const handleDelete = (product: ProductVO.Info) => {
};
const handleManageSpecs = (product: ProductVO.Info) => {
emit('manage-specs', product);
emit('manageSpecs', product);
};
const handleViewDetails = (product: ProductVO.Info) => {
emit('view-details', product);
emit('viewDetails', product);
};
const handleImageError = (event: Event | string) => {
if (typeof event === 'string') {
// 如果是字符串,说明是错误信息,直接隐藏图片
const img = document.querySelector(`img[src="${event}"]`) as HTMLImageElement;
const img = document.querySelector(
`img[src="${event}"]`,
) as HTMLImageElement;
if (img) {
img.style.display = 'none';
}
@@ -57,95 +68,96 @@ const handleImageError = (event: Event | string) => {
</script>
<template>
<Card
hoverable
:body-style="{ padding: '12px' }"
class="product-card"
>
<Card hoverable :body-style="{ padding: '12px' }" class="product-card">
<div class="relative">
<!-- 商品图片 -->
<div class="aspect-square bg-gray-100 rounded-lg overflow-hidden">
<div class="aspect-square overflow-hidden rounded-lg bg-gray-100">
<Image
v-if="product.mainImage"
:src="product.mainImage"
:alt="product.name"
class="w-full h-full object-cover"
class="h-full w-full object-cover"
:preview="true"
@error="handleImageError"
/>
<div v-else class="w-full h-full flex items-center justify-center text-gray-400">
<div
v-else
class="flex h-full w-full items-center justify-center text-gray-400"
>
<div class="text-center">
<div class="text-4xl mb-2">📦</div>
<div class="mb-2 text-4xl">📦</div>
<div class="text-sm">暂无图片</div>
</div>
</div>
</div>
<!-- 规格数量标签 -->
<div v-if="product.specs && product.specs.length > 0" class="absolute top-2 left-2">
<Tag color="blue">
{{ product.specs.length }} 个规格
</Tag>
<div
v-if="product.specs && product.specs.length > 0"
class="absolute left-2 top-2"
>
<Tag color="blue"> {{ product.specs.length }} 个规格 </Tag>
</div>
</div>
<!-- 商品信息 -->
<div class="mt-3">
<div class="text-sm font-medium text-gray-900 mb-2 line-clamp-2" :title="product.name">
<div
class="mb-2 line-clamp-2 text-sm font-medium text-gray-900"
:title="product.name"
>
{{ product.name }}
</div>
<!-- 规格信息 -->
<div v-if="product.specs && product.specs.length > 0" class="mb-2">
<div class="text-xs text-gray-500 mb-1">规格信息:</div>
<div class="mb-1 text-xs text-gray-500">规格信息:</div>
<div class="space-y-1">
<div
v-for="spec in product.specs.slice(0, 2)"
<div
v-for="spec in product.specs.slice(0, 2)"
:key="spec.id"
class="text-xs bg-gray-50 px-2 py-1 rounded"
class="rounded bg-gray-50 px-2 py-1 text-xs"
>
<span class="font-medium">{{ spec.name }}</span>
<span class="text-red-500 ml-1">¥{{ spec.costPrice.toFixed(2) }}</span>
<span class="ml-1 text-red-500">
¥{{ spec.costPrice.toFixed(2) }}
</span>
</div>
<div v-if="product.specs.length > 2" class="text-xs text-gray-400">
还有 {{ product.specs.length - 2 }} 个规格...
</div>
</div>
</div>
<!-- 创建时间 -->
<div class="text-xs text-gray-500 mb-3">
<div class="mb-3 text-xs text-gray-500">
{{ product.createTime }}
</div>
<!-- 操作按钮 -->
<div class="flex justify-between items-center">
<div class="flex items-center justify-between">
<Space size="small">
<Tooltip title="编辑">
<Button
type="text"
size="small"
@click="handleEdit(product)"
>
<EditIcon class="w-4 h-4" />
<Button type="text" size="small" @click="handleEdit(product)">
<EditIcon class="h-4 w-4" />
</Button>
</Tooltip>
<Tooltip title="管理规格">
<Button
type="text"
size="small"
<Button
type="text"
size="small"
@click="handleManageSpecs(product)"
>
<SettingsIcon class="w-4 h-4" />
<SettingsIcon class="h-4 w-4" />
</Button>
</Tooltip>
<Tooltip title="查看详情">
<Button
type="text"
size="small"
<Button
type="text"
size="small"
@click="handleViewDetails(product)"
>
<EyeIcon class="w-4 h-4" />
<EyeIcon class="h-4 w-4" />
</Button>
</Tooltip>
</Space>
@@ -153,12 +165,8 @@ const handleImageError = (event: Event | string) => {
title="确定要删除这个商品吗?"
@confirm="handleDelete(product)"
>
<Button
type="text"
size="small"
danger
>
<TrashIcon class="w-4 h-4" />
<Button type="text" size="small" danger>
<TrashIcon class="h-4 w-4" />
</Button>
</Popconfirm>
</div>
@@ -1,158 +1,25 @@
<template>
<Modal
:open="visible"
:title="modalTitle"
width="600px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<Form
ref="formRef"
:model="formData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="商品主图" name="mainImageId">
<div style="display: flex; align-items: center; gap: 16px;">
<!-- 主图预览区域 -->
<div style="position: relative; display: inline-block;">
<!-- 有图片时显示图片 -->
<img
v-if="currentImageUrl && !imageLoadError"
:src="currentImageUrl"
alt="商品主图"
style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 1px solid #d9d9d9; background-color: #f5f5f5;"
@error="handleImageError"
/>
<!-- 无图片或加载失败时显示空状态 -->
<div
v-else
style="width: 80px; height: 80px; border: 1px dashed #d9d9d9; border-radius: 8px; background-color: #fafafa; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px; text-align: center; line-height: 1.2;">
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
<CameraIcon style="font-size: 16px; margin-bottom: 4px;" />
<div>上传主图</div>
</div>
</div>
<!-- 点击更换遮罩 -->
<div
style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); border-radius: 8px; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; cursor: pointer;"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
@mouseleave="($event.target as HTMLElement).style.opacity = '0'"
@click="selectImageFile">
<div style="color: white; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center;">
<CameraIcon style="font-size: 16px; margin-bottom: 4px;" />
<div style="font-size: 12px;">{{ currentImageUrl && !imageLoadError ? '更换主图' : '上传主图' }}</div>
</div>
</div>
</div>
<!-- 重置按钮 -->
<div v-if="newImageFile">
<Button size="small" @click="removeNewImage">重置</Button>
</div>
</div>
</Form.Item>
<Form.Item label="商品名称" name="name" :rules="[{ required: true, message: '请输入商品名称' }]">
<Input v-model:value="formData.name" placeholder="请输入商品名称" />
</Form.Item>
<Form.Item v-if="isEdit" label="商品编码" name="specCode">
<Input v-model:value="formData.specCode" placeholder="请输入商品编码" />
</Form.Item>
<Form.Item v-if="isEdit" label="商品SKU" name="skuCode">
<Input v-model:value="formData.skuCode" placeholder="请输入商品SKU" />
</Form.Item>
<Form.Item v-if="isEdit" label="成本价" name="costPrice" :rules="[{ required: true, message: '请输入成本价' }]">
<InputNumber
v-model:value="formData.costPrice"
placeholder="请输入成本价"
style="width: 100%;"
:min="0"
:precision="2"
/>
</Form.Item>
<!-- 规格管理 -->
<Form.Item v-if="!isEdit" label="商品规格">
<div class="space-y-4">
<div class="flex items-center gap-2">
<Button
type="dashed"
@click="showSpecs = !showSpecs"
:icon="showSpecs ? 'up' : 'down'"
>
{{ showSpecs ? '收起规格' : '添加规格' }}
</Button>
<span class="text-sm text-gray-500">
可以添加多个规格,每个规格包含名称、编码和成本价
</span>
</div>
<div v-if="showSpecs" class="border border-gray-200 rounded-lg p-4 bg-gray-50">
<div class="space-y-3">
<div
v-for="(spec, index) in specs"
:key="index"
class="flex items-center gap-2 p-3 bg-white rounded border"
>
<Input
v-model:value="spec.name"
placeholder="规格名称"
style="flex: 1;"
/>
<Input
v-model:value="spec.specCode"
placeholder="规格编码"
style="flex: 1;"
/>
<InputNumber
v-model:value="spec.costPrice"
placeholder="成本价"
style="width: 120px;"
:min="0"
:precision="2"
/>
<Button
type="text"
danger
@click="removeSpec(index)"
>
删除
</Button>
</div>
<Button
type="dashed"
@click="addSpec"
style="width: 100%;"
>
+ 添加规格
</Button>
</div>
</div>
</div>
</Form.Item>
</Form>
</Modal>
</template>
<script lang="ts" setup>
import { computed, ref, onUnmounted } from 'vue';
import { Form, Input, Modal, InputNumber, Button, message } from 'ant-design-vue';
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import { computed, onUnmounted, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
createProductApi,
updateProductApi,
createProductWithSpecsApi
} from '#/api/shop/product';
import type { ProductVO, ProductDTO } from '#/api/shop/product/types';
import {
Button,
Form,
Input,
InputNumber,
message,
Modal,
} from 'ant-design-vue';
import { uploadImageApi } from '#/api/media/image';
import {
createProductApi,
createProductWithSpecsApi,
updateProductApi,
} from '#/api/shop/product';
interface Emits {
(e: 'success'): void;
@@ -166,7 +33,9 @@ const CameraIcon = createIconifyIcon('mdi:camera');
// 内部状态管理
const visible = ref(false);
const isEdit = ref(false);
const currentProductData = ref<ProductVO.Info | Partial<ProductVO.Info> | null>(null);
const currentProductData = ref<null | Partial<ProductVO.Info> | ProductVO.Info>(
null,
);
// 响应式数据
const formRef = ref();
@@ -189,7 +58,7 @@ const specs = ref<ProductDTO.Spec[]>([]);
const showSpecs = ref(false);
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑商品' : '添加商品');
const modalTitle = computed(() => (isEdit.value ? '编辑商品' : '添加商品'));
// 当前显示的图片 URL(优先显示新选择的)
const currentImageUrl = computed(() => {
@@ -210,7 +79,7 @@ function initFormData() {
mainImageId: undefined,
costPrice: 0,
};
// 设置原始图片 URL
originalImageUrl.value = currentProductData.value.mainImage || '';
} else {
@@ -224,21 +93,26 @@ function initFormData() {
};
originalImageUrl.value = currentProductData.value?.mainImage || '';
}
// 重置新选择的图片和图片加载状态
newImageFile.value = null;
imageLoadError.value = false;
// 重置规格数据
specs.value = [];
showSpecs.value = false;
// 如果有传入的规格信息,则自动填入
if (!isEdit.value && currentProductData.value && 'specs' in currentProductData.value && currentProductData.value.specs) {
specs.value = currentProductData.value.specs.map(spec => ({
if (
!isEdit.value &&
currentProductData.value &&
'specs' in currentProductData.value &&
currentProductData.value.specs
) {
specs.value = currentProductData.value.specs.map((spec) => ({
name: (spec as ProductVO.SpecInfo).name || spec.specCode || '',
specCode: spec.specCode || '',
costPrice: spec.costPrice || 0
costPrice: spec.costPrice || 0,
}));
showSpecs.value = specs.value.length > 0;
}
@@ -259,10 +133,10 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
// 准备提交数据
const submitData = { ...formData.value };
// 如果有新选择的图片,先上传获取ID
if (newImageFile.value) {
const mainImageId = await uploadImageAndGetId();
@@ -273,10 +147,18 @@ async function handleSubmit() {
// 创建模式且没有选择图片,移除mainImageId字段
delete submitData.mainImageId;
}
// 调用API
if (isEdit.value && currentProductData.value && 'id' in currentProductData.value && currentProductData.value.id) {
await updateProductApi(currentProductData.value.id, submitData as ProductDTO.Update);
if (
isEdit.value &&
currentProductData.value &&
'id' in currentProductData.value &&
currentProductData.value.id
) {
await updateProductApi(
currentProductData.value.id,
submitData as ProductDTO.Update,
);
message.success('更新成功');
} else {
// 创建模式:如果有规格,使用一键创建接口
@@ -293,7 +175,7 @@ async function handleSubmit() {
message.success('创建成功');
}
}
visible.value = false;
emit('success');
} catch (error) {
@@ -310,13 +192,16 @@ function handleCancel() {
}
// 暴露给父组件的方法
function open(editMode: boolean = false, productData?: ProductVO.Info | Partial<ProductVO.Info> | null) {
function open(
editMode: boolean = false,
productData?: null | Partial<ProductVO.Info> | ProductVO.Info,
) {
isEdit.value = editMode;
currentProductData.value = productData || null;
resetForm(); // 先重置表单
initFormData(); // 再初始化数据
visible.value = true;
}
@@ -331,35 +216,35 @@ function selectImageFile() {
input.type = 'file';
input.accept = 'image/*';
input.style.display = 'none';
document.body.appendChild(input);
input.onchange = (e) => {
document.body.append(input);
input.addEventListener('change', (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
// 验证文件
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('只能上传图片文件');
document.body.removeChild(input);
input.remove();
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小不能超过 2MB');
document.body.removeChild(input);
input.remove();
return;
}
// 设置新选择的文件
newImageFile.value = file;
imageLoadError.value = false; // 重置图片加载错误状态
message.success('图片选择成功');
}
document.body.removeChild(input);
};
input.remove();
});
input.click();
}
@@ -389,10 +274,9 @@ async function uploadImageAndGetId(): Promise<number | undefined> {
if (!newImageFile.value) {
return undefined;
}
try {
const response = await uploadImageApi(newImageFile.value);
console.log('图片上传成功:', response);
return response.id;
} catch (error) {
console.error('图片上传失败:', error);
@@ -416,3 +300,205 @@ onUnmounted(() => {
}
});
</script>
<template>
<Modal
:open="visible"
:title="modalTitle"
width="600px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<Form
ref="formRef"
:model="formData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="商品主图" name="mainImageId">
<div style="display: flex; align-items: center; gap: 16px">
<!-- 主图预览区域 -->
<div style="position: relative; display: inline-block">
<!-- 有图片时显示图片 -->
<img
v-if="currentImageUrl && !imageLoadError"
:src="currentImageUrl"
alt="商品主图"
style="
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 8px;
border: 1px solid #d9d9d9;
background-color: #f5f5f5;
"
@error="handleImageError"
/>
<!-- 无图片或加载失败时显示空状态 -->
<div
v-else
style="
width: 80px;
height: 80px;
border: 1px dashed #d9d9d9;
border-radius: 8px;
background-color: #fafafa;
display: flex;
align-items: center;
justify-content: center;
color: #999;
font-size: 12px;
text-align: center;
line-height: 1.2;
"
>
<div
style="
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div>上传主图</div>
</div>
</div>
<!-- 点击更换遮罩 -->
<div
style="
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.3s;
cursor: pointer;
"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
@mouseleave="($event.target as HTMLElement).style.opacity = '0'"
@click="selectImageFile"
>
<div
style="
color: white;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div style="font-size: 12px">
{{
currentImageUrl && !imageLoadError ? '更换主图' : '上传主图'
}}
</div>
</div>
</div>
</div>
<!-- 重置按钮 -->
<div v-if="newImageFile">
<Button size="small" @click="removeNewImage">重置</Button>
</div>
</div>
</Form.Item>
<Form.Item
label="商品名称"
name="name"
:rules="[{ required: true, message: '请输入商品名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入商品名称" />
</Form.Item>
<Form.Item v-if="isEdit" label="商品编码" name="specCode">
<Input v-model:value="formData.specCode" placeholder="请输入商品编码" />
</Form.Item>
<Form.Item v-if="isEdit" label="商品SKU" name="skuCode">
<Input v-model:value="formData.skuCode" placeholder="请输入商品SKU" />
</Form.Item>
<Form.Item
v-if="isEdit"
label="成本价"
name="costPrice"
:rules="[{ required: true, message: '请输入成本价' }]"
>
<InputNumber
v-model:value="formData.costPrice"
placeholder="请输入成本价"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<!-- 规格管理 -->
<Form.Item v-if="!isEdit" label="商品规格">
<div class="space-y-4">
<div class="flex items-center gap-2">
<Button
type="dashed"
@click="showSpecs = !showSpecs"
:icon="showSpecs ? 'up' : 'down'"
>
{{ showSpecs ? '收起规格' : '添加规格' }}
</Button>
<span class="text-sm text-gray-500">
可以添加多个规格,每个规格包含名称、编码和成本价
</span>
</div>
<div
v-if="showSpecs"
class="rounded-lg border border-gray-200 bg-gray-50 p-4"
>
<div class="space-y-3">
<div
v-for="(spec, index) in specs"
:key="index"
class="flex items-center gap-2 rounded border bg-white p-3"
>
<Input
v-model:value="spec.name"
placeholder="规格名称"
style="flex: 1"
/>
<Input
v-model:value="spec.specCode"
placeholder="规格编码"
style="flex: 1"
/>
<InputNumber
v-model:value="spec.costPrice"
placeholder="成本价"
style="width: 120px"
:min="0"
:precision="2"
/>
<Button type="text" danger @click="removeSpec(index)">
删除
</Button>
</div>
<Button type="dashed" @click="addSpec" style="width: 100%">
+ 添加规格
</Button>
</div>
</div>
</div>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,104 +1,26 @@
<template>
<Modal
:open="visible"
:title="modalTitle"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<div class="space-y-4">
<!-- 商品信息 -->
<div class="bg-gray-50 p-4 rounded-lg">
<h3 class="font-medium text-gray-900 mb-2">商品信息</h3>
<div class="grid grid-cols-2 gap-4 text-sm">
<div>
<span class="text-gray-500">商品名称:</span>
<span class="ml-2 font-medium">{{ currentProduct?.name }}</span>
</div>
<div>
<span class="text-gray-500">商品ID:</span>
<span class="ml-2 font-medium">{{ currentProduct?.id }}</span>
</div>
</div>
</div>
<!-- 规格列表 -->
<div>
<div class="flex items-center justify-between mb-4">
<h3 class="font-medium text-gray-900">商品规格</h3>
<Button type="primary" @click="handleAddSpec">
添加规格
</Button>
</div>
<Table
:columns="columns"
:data-source="specList"
:loading="specLoading"
:pagination="{
current: specCurrent,
pageSize: specPageSize,
total: specTotal,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
}"
row-key="id"
@change="handleSpecTableChange"
/>
</div>
</div>
</Modal>
<!-- 规格表单模态框 -->
<Modal
:open="specFormVisible"
:title="specFormTitle"
width="500px"
:confirm-loading="specFormLoading"
@ok="handleSpecSubmit"
@cancel="handleSpecCancel"
>
<Form
ref="specFormRef"
:model="specFormData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="规格名称" name="name" :rules="[{ required: true, message: '请输入规格名称' }]">
<Input v-model:value="specFormData.name" placeholder="请输入规格名称" />
</Form.Item>
<Form.Item label="规格编码" name="specCode">
<Input v-model:value="specFormData.specCode" placeholder="请输入规格编码" />
</Form.Item>
<Form.Item label="成本价" name="costPrice" :rules="[{ required: true, message: '请输入成本价' }]">
<InputNumber
v-model:value="specFormData.costPrice"
placeholder="请输入成本价"
style="width: 100%;"
:min="0"
:precision="2"
/>
</Form.Item>
</Form>
</Modal>
</template>
<script lang="ts" setup>
import { computed, ref, h } from 'vue';
import { Form, Input, Modal, InputNumber, Button, Table, message } from 'ant-design-vue';
import {
getProductSpecPageApi,
createProductSpecApi,
updateProductSpecApi,
deleteProductSpecApi
} from '#/api/shop/product';
import type { ProductVO, ProductDTO } from '#/api/shop/product/types';
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, h, ref } from 'vue';
import {
Button,
Form,
Input,
InputNumber,
message,
Modal,
Table,
} from 'ant-design-vue';
import {
createProductSpecApi,
deleteProductSpecApi,
getProductSpecPageApi,
updateProductSpecApi,
} from '#/api/shop/product';
interface Emits {
(e: 'success'): void;
}
@@ -107,7 +29,7 @@ const emit = defineEmits<Emits>();
// 内部状态管理
const visible = ref(false);
const currentProduct = ref<ProductVO.Info | null>(null);
const currentProduct = ref<null | ProductVO.Info>(null);
// 响应式数据
const loading = ref(false);
@@ -122,7 +44,7 @@ const specFormVisible = ref(false);
const specFormLoading = ref(false);
const specFormRef = ref();
const isEditSpec = ref(false);
const currentSpecId = ref<number | null>(null);
const currentSpecId = ref<null | number>(null);
const specFormData = ref({
name: '',
@@ -131,12 +53,14 @@ const specFormData = ref({
});
// 模态框标题
const modalTitle = computed(() =>
currentProduct.value ? `管理规格 - ${currentProduct.value.name}` : '管理规格'
const modalTitle = computed(() =>
currentProduct.value ? `管理规格 - ${currentProduct.value.name}` : '管理规格',
);
// 规格表单标题
const specFormTitle = computed(() => isEditSpec.value ? '编辑规格' : '添加规格');
const specFormTitle = computed(() =>
isEditSpec.value ? '编辑规格' : '添加规格',
);
// 表格列配置
const columns = [
@@ -174,15 +98,23 @@ const columns = [
fixed: 'right' as const,
customRender: ({ record }: { record: ProductVO.SpecInfo }) => {
return h('div', { style: 'display: flex; gap: 8px;' }, [
h(Button, {
size: 'small',
onClick: () => handleEditSpec(record),
}, { default: () => '编辑' }),
h(Button, {
size: 'small',
danger: true,
onClick: () => handleDeleteSpec(record),
}, { default: () => '删除' }),
h(
Button,
{
size: 'small',
onClick: () => handleEditSpec(record),
},
{ default: () => '编辑' },
),
h(
Button,
{
size: 'small',
danger: true,
onClick: () => handleDeleteSpec(record),
},
{ default: () => '删除' },
),
]);
},
},
@@ -191,7 +123,7 @@ const columns = [
// 获取规格列表
async function fetchSpecList() {
if (!currentProduct.value) return;
try {
specLoading.value = true;
const params: PageQueryDTO<ProductDTO.SpecFilters> = {
@@ -260,16 +192,19 @@ async function handleSpecSubmit() {
try {
await specFormRef.value?.validate();
specFormLoading.value = true;
if (isEditSpec.value && currentSpecId.value) {
await updateProductSpecApi(currentSpecId.value, specFormData.value as ProductDTO.UpdateSpec);
await updateProductSpecApi(
currentSpecId.value,
specFormData.value as ProductDTO.UpdateSpec,
);
message.success('更新成功');
} else {
if (!currentProduct.value) {
message.error('商品信息不存在');
return;
}
const createData: ProductDTO.CreateSpec = {
productId: currentProduct.value.id,
...specFormData.value,
@@ -277,7 +212,7 @@ async function handleSpecSubmit() {
await createProductSpecApi(createData);
message.success('创建成功');
}
specFormVisible.value = false;
await fetchSpecList();
} catch (error) {
@@ -319,3 +254,102 @@ defineExpose({
open,
});
</script>
<template>
<Modal
:open="visible"
:title="modalTitle"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<div class="space-y-4">
<!-- 商品信息 -->
<div class="rounded-lg bg-gray-50 p-4">
<h3 class="mb-2 font-medium text-gray-900">商品信息</h3>
<div class="grid grid-cols-2 gap-4 text-sm">
<div>
<span class="text-gray-500">商品名称:</span>
<span class="ml-2 font-medium">{{ currentProduct?.name }}</span>
</div>
<div>
<span class="text-gray-500">商品ID:</span>
<span class="ml-2 font-medium">{{ currentProduct?.id }}</span>
</div>
</div>
</div>
<!-- 规格列表 -->
<div>
<div class="mb-4 flex items-center justify-between">
<h3 class="font-medium text-gray-900">商品规格</h3>
<Button type="primary" @click="handleAddSpec"> 添加规格 </Button>
</div>
<Table
:columns="columns"
:data-source="specList"
:loading="specLoading"
:pagination="{
current: specCurrent,
pageSize: specPageSize,
total: specTotal,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total, range) =>
`第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
}"
row-key="id"
@change="handleSpecTableChange"
/>
</div>
</div>
</Modal>
<!-- 规格表单模态框 -->
<Modal
:open="specFormVisible"
:title="specFormTitle"
width="500px"
:confirm-loading="specFormLoading"
@ok="handleSpecSubmit"
@cancel="handleSpecCancel"
>
<Form
ref="specFormRef"
:model="specFormData"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item
label="规格名称"
name="name"
:rules="[{ required: true, message: '请输入规格名称' }]"
>
<Input v-model:value="specFormData.name" placeholder="请输入规格名称" />
</Form.Item>
<Form.Item label="规格编码" name="specCode">
<Input
v-model:value="specFormData.specCode"
placeholder="请输入规格编码"
/>
</Form.Item>
<Form.Item
label="成本价"
name="costPrice"
:rules="[{ required: true, message: '请输入成本价' }]"
>
<InputNumber
v-model:value="specFormData.costPrice"
placeholder="请输入成本价"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,233 +1,47 @@
<template>
<Page title="商品管理" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理商品信息,支持商品和规格的一键创建,提供网格和列表两种视图模式
</div>
</template>
<template #extra>
<div class="flex items-center gap-2">
<Button
:type="viewMode === 'grid' ? 'primary' : 'default'"
@click="viewMode = 'grid'"
>
<GridIcon class="w-4 h-4 mr-2" />
网格视图
</Button>
<Button
:type="viewMode === 'table' ? 'primary' : 'default'"
@click="viewMode = 'table'"
>
<ListIcon class="w-4 h-4 mr-2" />
列表视图
</Button>
</div>
</template>
<!-- 列表视图 -->
<Grid v-if="viewMode === 'table'" :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加商品
</Button>
</Space>
</template>
<!-- 主图列 -->
<template #mainImage="{ row }: { row: any }">
<div v-if="row.mainImage">
<img
:src="row.mainImage"
:alt="row.name"
style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;"
/>
</div>
<span v-else style="color: #999;">暂无图片</span>
</template>
<!-- 规格数量列 -->
<template #specs="{ row }: { row: any }">
<Tag :color="(row.specs?.length || 0) > 0 ? 'blue' : 'default'">
{{ row.specs?.length || 0 }} 个规格
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" @click="handleManageSpecs(row)">
规格
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
</Space>
</template>
</Grid>
<!-- 网格视图 -->
<div v-if="viewMode === 'grid'">
<!-- 搜索表单 -->
<div class="mb-4 p-4 bg-white rounded-lg shadow-sm">
<Form :model="searchForm" layout="inline">
<Form.Item label="商品名称">
<Input
v-model:value="searchForm.name"
placeholder="请输入商品名称"
style="width: 200px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="商品编码">
<Input
v-model:value="searchForm.specCode"
placeholder="请输入商品编码"
style="width: 150px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="商品SKU">
<Input
v-model:value="searchForm.skuCode"
placeholder="请输入商品SKU"
style="width: 150px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="成本价范围">
<div class="flex items-center gap-2">
<InputNumber
v-model:value="searchForm.minCostPrice"
placeholder="最小值"
style="width: 100px"
:min="0"
:precision="2"
/>
<span class="text-gray-500">-</span>
<InputNumber
v-model:value="searchForm.maxCostPrice"
placeholder="最大值"
style="width: 100px"
:min="0"
:precision="2"
/>
</div>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" @click="refreshTable">搜索</Button>
<Button @click="handleReset">重置</Button>
</Space>
</Form.Item>
</Form>
</div>
<!-- 工具栏 -->
<div class="mb-4 flex justify-between items-center">
<div class="flex items-center gap-4">
<Button type="primary" @click="handleAdd">
<PlusIcon class="w-4 h-4 mr-2" />
添加商品
</Button>
<span class="text-gray-500">支持商品和规格的一键创建</span>
</div>
<div class="flex items-center gap-2">
<span class="text-gray-500">共 {{ total }} 个商品</span>
</div>
</div>
<!-- 网格内容 -->
<div class="bg-white rounded-lg shadow-sm p-4">
<Row :gutter="[16, 16]">
<Col
v-for="product in productList"
:key="product.id"
:xs="12"
:sm="8"
:md="6"
:lg="4"
:xl="3"
>
<ProductCard
:product="product"
@edit="handleEdit"
@delete="handleDelete"
@manage-specs="handleManageSpecs"
@view-details="handleViewDetails"
/>
</Col>
</Row>
<!-- 分页 -->
<div class="mt-4 flex justify-center">
<Pagination
v-model:current="current"
v-model:page-size="pageSize"
:total="total"
:show-size-changer="true"
:show-quick-jumper="true"
:show-total="(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`"
@change="handleTableChange"
/>
</div>
</div>
</div>
<!-- 商品表单模态框 -->
<ProductFormModal
ref="productFormModalRef"
@success="handleModalSuccess"
/>
<!-- 商品规格管理模态框 -->
<ProductSpecModal
ref="productSpecModalRef"
@success="handleSpecModalSuccess"
/>
</Page>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag, Row, Col, Pagination, Form, Input, InputNumber } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteProductApi,
getProductPageApi
} from '#/api/shop/product';
import type { ProductVO, ProductDTO } from '#/api/shop/product/types';
import type { PageQueryDTO } from '#/types/common';
import {
Button,
Col,
Form,
Input,
InputNumber,
message,
Pagination,
Row,
Space,
Tag,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteProductApi, getProductPageApi } from '#/api/shop/product';
import ProductCard from './components/ProductCard.vue';
import ProductFormModal from './components/ProductFormModal.vue';
// @ts-ignore
import ProductSpecModal from './components/ProductSpecModal.vue';
import ProductCard from './components/ProductCard.vue';
defineOptions({ name: 'ProductManagement' });
// 创建图标组件
const GridIcon = createIconifyIcon('lucide:grid-3x3');
const ListIcon = createIconifyIcon('lucide:list');
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'ProductManagement' });
// 响应式数据
const loading = ref(false);
const productList = ref<ProductVO.Info[]>([]);
const total = ref(0);
const current = ref(1);
const pageSize = ref(10);
const viewMode = ref<'table' | 'grid'>('grid');
const viewMode = ref<'grid' | 'table'>('grid');
const productFormModalRef = ref();
const productSpecModalRef = ref();
@@ -295,7 +109,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -418,7 +250,6 @@ function handleTableChange(pagination: any) {
refreshTable();
}
// 处理添加商品
function handleAdd() {
productFormModalRef.value?.open(false);
@@ -472,6 +303,200 @@ const [Grid, gridApi] = useVbenVxeGrid({
});
</script>
<template>
<Page title="商品管理" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理商品信息,支持商品和规格的一键创建,提供网格和列表两种视图模式
</div>
</template>
<template #extra>
<div class="flex items-center gap-2">
<Button
:type="viewMode === 'grid' ? 'primary' : 'default'"
@click="viewMode = 'grid'"
>
<GridIcon class="mr-2 h-4 w-4" />
网格视图
</Button>
<Button
:type="viewMode === 'table' ? 'primary' : 'default'"
@click="viewMode = 'table'"
>
<ListIcon class="mr-2 h-4 w-4" />
列表视图
</Button>
</div>
</template>
<!-- 列表视图 -->
<Grid v-if="viewMode === 'table'" :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加商品
</Button>
</Space>
</template>
<!-- 主图列 -->
<template #mainImage="{ row }: { row: any }">
<div v-if="row.mainImage">
<img
:src="row.mainImage"
:alt="row.name"
style="
width: 40px;
height: 40px;
object-fit: cover;
border-radius: 4px;
"
/>
</div>
<span v-else style="color: #999">暂无图片</span>
</template>
<!-- 规格数量列 -->
<template #specs="{ row }: { row: any }">
<Tag :color="(row.specs?.length || 0) > 0 ? 'blue' : 'default'">
{{ row.specs?.length || 0 }} 个规格
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" @click="handleManageSpecs(row)"> 规格 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 网格视图 -->
<div v-if="viewMode === 'grid'">
<!-- 搜索表单 -->
<div class="mb-4 rounded-lg bg-white p-4 shadow-sm">
<Form :model="searchForm" layout="inline">
<Form.Item label="商品名称">
<Input
v-model:value="searchForm.name"
placeholder="请输入商品名称"
style="width: 200px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="商品编码">
<Input
v-model:value="searchForm.specCode"
placeholder="请输入商品编码"
style="width: 150px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="商品SKU">
<Input
v-model:value="searchForm.skuCode"
placeholder="请输入商品SKU"
style="width: 150px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="成本价范围">
<div class="flex items-center gap-2">
<InputNumber
v-model:value="searchForm.minCostPrice"
placeholder="最小值"
style="width: 100px"
:min="0"
:precision="2"
/>
<span class="text-gray-500">-</span>
<InputNumber
v-model:value="searchForm.maxCostPrice"
placeholder="最大值"
style="width: 100px"
:min="0"
:precision="2"
/>
</div>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" @click="refreshTable">搜索</Button>
<Button @click="handleReset">重置</Button>
</Space>
</Form.Item>
</Form>
</div>
<!-- 工具栏 -->
<div class="mb-4 flex items-center justify-between">
<div class="flex items-center gap-4">
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
添加商品
</Button>
<span class="text-gray-500">支持商品和规格的一键创建</span>
</div>
<div class="flex items-center gap-2">
<span class="text-gray-500">共 {{ total }} 个商品</span>
</div>
</div>
<!-- 网格内容 -->
<div class="rounded-lg bg-white p-4 shadow-sm">
<Row :gutter="[16, 16]">
<Col
v-for="product in productList"
:key="product.id"
:xs="12"
:sm="8"
:md="6"
:lg="4"
:xl="3"
>
<ProductCard
:product="product"
@edit="handleEdit"
@delete="handleDelete"
@manage-specs="handleManageSpecs"
@view-details="handleViewDetails"
/>
</Col>
</Row>
<!-- 分页 -->
<div class="mt-4 flex justify-center">
<Pagination
v-model:current="current"
v-model:page-size="pageSize"
:total="total"
:show-size-changer="true"
:show-quick-jumper="true"
:show-total="
(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
"
@change="handleTableChange"
/>
</div>
</div>
</div>
<!-- 商品表单模态框 -->
<ProductFormModal ref="productFormModalRef" @success="handleModalSuccess" />
<!-- 商品规格管理模态框 -->
<ProductSpecModal
ref="productSpecModalRef"
@success="handleSpecModalSuccess"
/>
</Page>
</template>
<style scoped>
.line-clamp-2 {
display: -webkit-box;
@@ -1,3 +1,228 @@
<script setup lang="ts">
import type { PromotionFeeTypeVO } from '#/api/ecommerce/types';
import type {
PromotionFeeDTO,
PromotionFeeVO,
} from '#/api/shop/promotion-fee/types';
import type { ShopVO } from '#/api/shop/shop/types';
import { onMounted, ref, watch } from 'vue';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Modal,
Select,
} from 'ant-design-vue';
import { getActivePromotionFeeTypeListApi } from '#/api/ecommerce';
import {
createPromotionFeeApi,
updatePromotionFeeApi,
} from '#/api/shop/promotion-fee';
import { getShopPageApi } from '#/api/shop/shop';
defineOptions({ name: 'PromotionFeeFormModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// Props
interface Props {
open: boolean;
promotionFeeData?: null | PromotionFeeVO.Info;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
// 响应式数据
const visible = ref(false);
const formRef = ref();
const isEdit = ref(false);
// 表单数据
const formData = ref<PromotionFeeDTO.Create>({
shopId: undefined as any,
feeTypeId: undefined as any,
feeName: '',
platform: undefined,
campaignName: '',
feeAmount: undefined as any,
baseAmount: undefined,
feeRate: undefined,
clickCount: undefined,
impressionCount: undefined,
conversionCount: undefined,
feeDate: undefined as any,
remark: '',
});
// 表单验证规则
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
feeTypeId: [
{ required: true, message: '请选择推广费类型', trigger: 'change' },
],
feeName: [{ required: true, message: '请输入推广费名称', trigger: 'blur' }],
feeAmount: [{ required: true, message: '请输入推广费金额', trigger: 'blur' }],
feeDate: [{ required: true, message: '请选择发生日期', trigger: 'change' }],
} as any;
// 平台选项
const platformOptions = [
{ label: '淘宝', value: '淘宝' },
{ label: '京东', value: '京东' },
{ label: '拼多多', value: '拼多多' },
{ label: '天猫', value: '天猫' },
{ label: '抖音', value: '抖音' },
{ label: '快手', value: '快手' },
{ label: '其他', value: '其他' },
];
// 店铺列表
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 推广费类型列表
const feeTypeList = ref<PromotionFeeTypeVO.Info[]>([]);
const feeTypeListLoading = ref(false);
// 监听props变化
watch(
() => props.open,
(newVal) => {
visible.value = newVal;
if (newVal) {
isEdit.value = !!props.promotionFeeData;
if (props.promotionFeeData) {
// 编辑模式,填充表单数据
formData.value = {
shopId: props.promotionFeeData.shopId,
feeTypeId: props.promotionFeeData.feeTypeId,
feeName: props.promotionFeeData.feeName,
platform: props.promotionFeeData.platform,
campaignName: props.promotionFeeData.campaignName || '',
feeAmount: props.promotionFeeData.feeAmount,
baseAmount: props.promotionFeeData.baseAmount,
feeRate: props.promotionFeeData.feeRate,
clickCount: props.promotionFeeData.clickCount,
impressionCount: props.promotionFeeData.impressionCount,
conversionCount: props.promotionFeeData.conversionCount,
feeDate: props.promotionFeeData.feeDate,
remark: props.promotionFeeData.remark || '',
};
} else {
// 新增模式,重置表单数据
resetFormData();
}
}
},
);
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal);
});
// 加载店铺列表
const loadShopList = async () => {
shopListLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopList.value = response.records;
} catch (error) {
console.error('加载店铺列表失败:', error);
} finally {
shopListLoading.value = false;
}
};
// 加载推广费类型列表
const loadFeeTypeList = async () => {
feeTypeListLoading.value = true;
try {
const response = await getActivePromotionFeeTypeListApi();
feeTypeList.value = response;
} catch (error) {
console.error('加载推广费类型列表失败:', error);
} finally {
feeTypeListLoading.value = false;
}
};
// 重置表单数据
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
feeTypeId: undefined as any,
feeName: '',
platform: undefined,
campaignName: '',
feeAmount: undefined as any,
baseAmount: undefined,
feeRate: undefined,
clickCount: undefined,
impressionCount: undefined,
conversionCount: undefined,
feeDate: undefined as any,
remark: '',
};
};
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (isEdit.value && props.promotionFeeData) {
// 更新推广费记录
const updateData: PromotionFeeDTO.Update = {
id: props.promotionFeeData.id,
...formData.value,
};
await updatePromotionFeeApi(updateData);
message.success('更新成功');
} else {
// 创建推广费记录
await createPromotionFeeApi(formData.value);
message.success('创建成功');
}
emit('success');
visible.value = false;
} catch (error) {
console.error('操作失败:', error);
message.error(isEdit.value ? '更新失败' : '创建失败');
}
};
// 取消操作
const handleCancel = () => {
emit('cancel');
visible.value = false;
resetFormData();
};
// 组件挂载时加载数据
onMounted(() => {
loadShopList();
loadFeeTypeList();
});
</script>
<template>
<Modal
v-model:open="visible"
@@ -151,205 +376,3 @@
</Form>
</Modal>
</template>
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { Modal, Form, Input, Select, InputNumber, DatePicker, message } from 'ant-design-vue';
import { createPromotionFeeApi, updatePromotionFeeApi } from '#/api/shop/promotion-fee';
import { getShopPageApi } from '#/api/shop/shop';
import { getActivePromotionFeeTypeListApi } from '#/api/ecommerce';
import type { PromotionFeeDTO, PromotionFeeVO } from '#/api/shop/promotion-fee/types';
import type { ShopVO } from '#/api/shop/shop/types';
import type { PromotionFeeTypeVO } from '#/api/ecommerce/types';
defineOptions({ name: 'PromotionFeeFormModal' });
// Props
interface Props {
open: boolean;
promotionFeeData?: PromotionFeeVO.Info | null;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 响应式数据
const visible = ref(false);
const formRef = ref();
const isEdit = ref(false);
// 表单数据
const formData = ref<PromotionFeeDTO.Create>({
shopId: undefined as any,
feeTypeId: undefined as any,
feeName: '',
platform: undefined,
campaignName: '',
feeAmount: undefined as any,
baseAmount: undefined,
feeRate: undefined,
clickCount: undefined,
impressionCount: undefined,
conversionCount: undefined,
feeDate: undefined as any,
remark: '',
});
// 表单验证规则
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
feeTypeId: [{ required: true, message: '请选择推广费类型', trigger: 'change' }],
feeName: [{ required: true, message: '请输入推广费名称', trigger: 'blur' }],
feeAmount: [{ required: true, message: '请输入推广费金额', trigger: 'blur' }],
feeDate: [{ required: true, message: '请选择发生日期', trigger: 'change' }],
} as any;
// 平台选项
const platformOptions = [
{ label: '淘宝', value: '淘宝' },
{ label: '京东', value: '京东' },
{ label: '拼多多', value: '拼多多' },
{ label: '天猫', value: '天猫' },
{ label: '抖音', value: '抖音' },
{ label: '快手', value: '快手' },
{ label: '其他', value: '其他' },
];
// 店铺列表
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 推广费类型列表
const feeTypeList = ref<PromotionFeeTypeVO.Info[]>([]);
const feeTypeListLoading = ref(false);
// 监听props变化
watch(() => props.open, (newVal) => {
visible.value = newVal;
if (newVal) {
isEdit.value = !!props.promotionFeeData;
if (props.promotionFeeData) {
// 编辑模式,填充表单数据
formData.value = {
shopId: props.promotionFeeData.shopId,
feeTypeId: props.promotionFeeData.feeTypeId,
feeName: props.promotionFeeData.feeName,
platform: props.promotionFeeData.platform,
campaignName: props.promotionFeeData.campaignName || '',
feeAmount: props.promotionFeeData.feeAmount,
baseAmount: props.promotionFeeData.baseAmount,
feeRate: props.promotionFeeData.feeRate,
clickCount: props.promotionFeeData.clickCount,
impressionCount: props.promotionFeeData.impressionCount,
conversionCount: props.promotionFeeData.conversionCount,
feeDate: props.promotionFeeData.feeDate,
remark: props.promotionFeeData.remark || '',
};
} else {
// 新增模式,重置表单数据
resetFormData();
}
}
});
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal);
});
// 加载店铺列表
const loadShopList = async () => {
shopListLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopList.value = response.records;
} catch (error) {
console.error('加载店铺列表失败:', error);
} finally {
shopListLoading.value = false;
}
};
// 加载推广费类型列表
const loadFeeTypeList = async () => {
feeTypeListLoading.value = true;
try {
const response = await getActivePromotionFeeTypeListApi();
feeTypeList.value = response;
} catch (error) {
console.error('加载推广费类型列表失败:', error);
} finally {
feeTypeListLoading.value = false;
}
};
// 重置表单数据
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
feeTypeId: undefined as any,
feeName: '',
platform: undefined,
campaignName: '',
feeAmount: undefined as any,
baseAmount: undefined,
feeRate: undefined,
clickCount: undefined,
impressionCount: undefined,
conversionCount: undefined,
feeDate: undefined as any,
remark: '',
};
};
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (isEdit.value && props.promotionFeeData) {
// 更新推广费记录
const updateData: PromotionFeeDTO.Update = {
id: props.promotionFeeData.id,
...formData.value,
};
await updatePromotionFeeApi(updateData);
message.success('更新成功');
} else {
// 创建推广费记录
await createPromotionFeeApi(formData.value);
message.success('创建成功');
}
emit('success');
visible.value = false;
} catch (error) {
console.error('操作失败:', error);
message.error(isEdit.value ? '更新失败' : '创建失败');
}
};
// 取消操作
const handleCancel = () => {
emit('cancel');
visible.value = false;
resetFormData();
};
// 组件挂载时加载数据
onMounted(() => {
loadShopList();
loadFeeTypeList();
});
</script>
@@ -1,29 +1,35 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type {
PromotionFeeDTO,
PromotionFeeVO,
} from '#/api/shop/promotion-fee/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
getPromotionFeePageApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePromotionFeeApi,
getPromotionFeePageApi,
} from '#/api/shop/promotion-fee';
import type { PromotionFeeVO, PromotionFeeDTO } from '#/api/shop/promotion-fee/types';
import type { PageQueryDTO } from '#/types/common';
import PromotionFeeFormModal from './components/PromotionFeeFormModal.vue';
defineOptions({ name: 'PromotionFeeManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'PromotionFeeManagement' });
// 响应式数据
const loading = ref(false);
const formModalVisible = ref(false);
const currentPromotionFeeData = ref<PromotionFeeVO.Info | null>(null);
const currentPromotionFeeData = ref<null | PromotionFeeVO.Info>(null);
// 搜索表单
const searchForm = ref({
@@ -113,7 +119,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -244,7 +268,7 @@ const handleDelete = async (id: number) => {
await deletePromotionFeeApi(id);
message.success('删除成功');
refreshTable();
} catch (error) {
} catch {
message.error('删除失败');
}
};
@@ -262,20 +286,27 @@ const formatAmount = (amount: number) => {
// 获取平台标签颜色
const getPlatformColor = (platform: string | undefined) => {
switch (platform) {
case '淘宝':
return 'orange';
case '京东':
case '京东': {
return 'red';
case '拼多多':
return 'green';
case '天猫':
}
case '天猫': {
return 'purple';
case '抖音':
return 'blue';
case '快手':
}
case '快手': {
return 'cyan';
default:
}
case '抖音': {
return 'blue';
}
case '拼多多': {
return 'green';
}
case '淘宝': {
return 'orange';
}
default: {
return 'default';
}
}
};
</script>
@@ -291,7 +322,7 @@ const getPlatformColor = (platform: string | undefined) => {
<template #extra>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon class="w-4 h-4 mr-2" />
<PlusIcon class="mr-2 h-4 w-4" />
新增推广费记录
</Button>
</Space>
@@ -302,7 +333,9 @@ const getPlatformColor = (platform: string | undefined) => {
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<span class="text-gray-500">支持按店铺、类型、平台等维度查询推广费记录</span>
<span class="text-gray-500">
支持按店铺、类型、平台等维度查询推广费记录
</span>
</Space>
</template>
@@ -324,9 +357,7 @@ const getPlatformColor = (platform: string | undefined) => {
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row.id)">
删除
</Button>
@@ -1,13 +1,17 @@
<script lang="ts" setup>
import { computed, ref, onUnmounted } from 'vue';
import { Form, Input, Modal, Select, Button, message } from 'ant-design-vue';
import type { ShopDTO, ShopVO } from '#/api/shop/shop/types';
import { computed, onUnmounted, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
uploadShopLogoApi,
createShopApi,
import { Button, Form, Input, message, Modal, Select } from 'ant-design-vue';
import {
createShopApi,
updateShopApi,
uploadShopLogoApi,
} from '#/api/shop/shop';
import type { ShopVO, ShopDTO } from '#/api/shop/shop/types';
interface Emits {
(e: 'success'): void;
@@ -21,7 +25,7 @@ const CameraIcon = createIconifyIcon('mdi:camera');
// 内部状态管理
const visible = ref(false);
const isEdit = ref(false);
const currentShopData = ref<ShopVO.Info | Partial<ShopVO.Info> | null>(null);
const currentShopData = ref<null | Partial<ShopVO.Info> | ShopVO.Info>(null);
// 响应式数据
const formRef = ref();
@@ -46,7 +50,7 @@ const platformOptions = [
];
// 模态框标题
const modalTitle = computed(() => isEdit.value ? '编辑店铺' : '添加店铺');
const modalTitle = computed(() => (isEdit.value ? '编辑店铺' : '添加店铺'));
// 当前显示的logo URL(优先显示新选择的)
const currentLogoUrl = computed(() => {
@@ -65,7 +69,7 @@ function initFormData() {
platform: currentShopData.value.platform || '',
logoImageId: undefined,
};
// 设置原始Logo URL
originalLogoUrl.value = currentShopData.value.logo || '';
} else {
@@ -77,7 +81,7 @@ function initFormData() {
};
originalLogoUrl.value = currentShopData.value?.logo || '';
}
// 重置新选择的logo和图片加载状态
newLogoFile.value = null;
imageLoadError.value = false;
@@ -96,10 +100,10 @@ async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
// 准备提交数据
const submitData = { ...formData.value };
// 如果有新选择的logo,先上传获取ID
if (newLogoFile.value) {
const logoImageId = await uploadLogoAndGetId();
@@ -110,16 +114,24 @@ async function handleSubmit() {
// 创建模式且没有选择Logo,移除logoImageId字段
delete submitData.logoImageId;
}
// 调用API
if (isEdit.value && currentShopData.value && 'id' in currentShopData.value && currentShopData.value.id) {
await updateShopApi(currentShopData.value.id, submitData as ShopDTO.Update);
if (
isEdit.value &&
currentShopData.value &&
'id' in currentShopData.value &&
currentShopData.value.id
) {
await updateShopApi(
currentShopData.value.id,
submitData as ShopDTO.Update,
);
message.success('更新成功');
} else {
await createShopApi(submitData as ShopDTO.Create);
message.success('创建成功');
}
visible.value = false;
emit('success');
} catch (error) {
@@ -136,13 +148,16 @@ function handleCancel() {
}
// 暴露给父组件的方法
function open(editMode: boolean = false, shopData?: ShopVO.Info | Partial<ShopVO.Info> | null) {
function open(
editMode: boolean = false,
shopData?: null | Partial<ShopVO.Info> | ShopVO.Info,
) {
isEdit.value = editMode;
currentShopData.value = shopData || null;
resetForm(); // 先重置表单
initFormData(); // 再初始化数据
visible.value = true;
}
@@ -157,35 +172,35 @@ function selectLogoFile() {
input.type = 'file';
input.accept = 'image/*';
input.style.display = 'none';
document.body.appendChild(input);
input.onchange = (e) => {
document.body.append(input);
input.addEventListener('change', (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
// 验证文件
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('只能上传图片文件');
document.body.removeChild(input);
input.remove();
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小不能超过 2MB');
document.body.removeChild(input);
input.remove();
return;
}
// 设置新选择的文件
newLogoFile.value = file;
imageLoadError.value = false; // 重置图片加载错误状态
message.success('Logo选择成功');
}
document.body.removeChild(input);
};
input.remove();
});
input.click();
}
@@ -201,10 +216,9 @@ async function uploadLogoAndGetId(): Promise<number | undefined> {
if (!newLogoFile.value) {
return undefined;
}
try {
const response = await uploadShopLogoApi(newLogoFile.value);
console.log('Logo上传成功:', response);
return response.id;
} catch (error) {
console.error('Logo上传失败:', error);
@@ -245,52 +259,110 @@ onUnmounted(() => {
:wrapper-col="{ span: 18 }"
>
<Form.Item label="店铺Logo" name="logoImageId">
<div style="display: flex; align-items: center; gap: 16px;">
<div style="display: flex; align-items: center; gap: 16px">
<!-- Logo预览区域 -->
<div style="position: relative; display: inline-block;">
<div style="position: relative; display: inline-block">
<!-- 有图片时显示图片 -->
<img
<img
v-if="currentLogoUrl && !imageLoadError"
:src="currentLogoUrl"
alt="店铺Logo"
style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 1px solid #d9d9d9; background-color: #f5f5f5;"
:src="currentLogoUrl"
alt="店铺Logo"
style="
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 8px;
border: 1px solid #d9d9d9;
background-color: #f5f5f5;
"
@error="handleImageError"
/>
<!-- 无图片或加载失败时显示空状态 -->
<div
<div
v-else
style="width: 80px; height: 80px; border: 1px dashed #d9d9d9; border-radius: 8px; background-color: #fafafa; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px; text-align: center; line-height: 1.2;">
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
<CameraIcon style="font-size: 16px; margin-bottom: 4px;" />
style="
width: 80px;
height: 80px;
border: 1px dashed #d9d9d9;
border-radius: 8px;
background-color: #fafafa;
display: flex;
align-items: center;
justify-content: center;
color: #999;
font-size: 12px;
text-align: center;
line-height: 1.2;
"
>
<div
style="
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div>上传Logo</div>
</div>
</div>
<!-- 点击更换遮罩 -->
<div
style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); border-radius: 8px; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; cursor: pointer;"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
<div
style="
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.3s;
cursor: pointer;
"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
@mouseleave="($event.target as HTMLElement).style.opacity = '0'"
@click="selectLogoFile">
<div style="color: white; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center;">
<CameraIcon style="font-size: 16px; margin-bottom: 4px;" />
<div style="font-size: 12px;">{{ currentLogoUrl && !imageLoadError ? '更换Logo' : '上传Logo' }}</div>
@click="selectLogoFile"
>
<div
style="
color: white;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div style="font-size: 12px">
{{
currentLogoUrl && !imageLoadError ? '更换Logo' : '上传Logo'
}}
</div>
</div>
</div>
</div>
<!-- 重置按钮 -->
<div v-if="newLogoFile">
<Button size="small" @click="removeNewLogo">重置</Button>
</div>
</div>
</Form.Item>
<Form.Item label="店铺名称" name="name" :rules="[{ required: true, message: '请输入店铺名称' }]">
<Form.Item
label="店铺名称"
name="name"
:rules="[{ required: true, message: '请输入店铺名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入店铺名称" />
</Form.Item>
<Form.Item label="平台" name="platform">
<Select
v-model:value="formData.platform"
@@ -302,5 +374,3 @@ onUnmounted(() => {
</Form>
</Modal>
</template>
@@ -1,25 +1,25 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ShopDTO, ShopVO } from '#/api/shop/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteShopApi,
getShopPageApi,
} from '#/api/shop/shop';
import type { ShopVO, ShopDTO } from '#/api/shop/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { Button, message, Space } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteShopApi, getShopPageApi } from '#/api/shop/shop';
import ShopFormModal from './components/ShopFormModal.vue';
defineOptions({ name: 'ShopManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'ShopManagement' });
// 响应式数据
const loading = ref(false);
const shopFormModalRef = ref();
@@ -96,7 +96,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -174,7 +192,6 @@ function refreshTable() {
}
}
// 处理添加店铺
function handleAdd() {
shopFormModalRef.value?.open(false);
@@ -212,9 +229,7 @@ function handleModalSuccess() {
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -228,32 +243,30 @@ function handleModalSuccess() {
<!-- Logo列 -->
<template #logo="{ row }: { row: any }">
<div v-if="row.logo">
<img
:src="row.logo"
<img
:src="row.logo"
:alt="row.name"
style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;"
style="
width: 40px;
height: 40px;
object-fit: cover;
border-radius: 4px;
"
/>
</div>
<span v-else style="color: #999;">暂无Logo</span>
<span v-else style="color: #999">暂无Logo</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 店铺表单模态框 -->
<ShopFormModal
ref="shopFormModalRef"
@success="handleModalSuccess"
/>
<ShopFormModal ref="shopFormModalRef" @success="handleModalSuccess" />
</Page>
</template>
@@ -1,118 +1,25 @@
<template>
<div class="icon-selector">
<!-- 搜索框 -->
<div class="mb-2 flex w-full">
<Input
v-model:value="searchKeyword"
placeholder="搜索图标..."
class="mx-2"
@input="handleSearch"
/>
</div>
<!-- 图标网格 -->
<div class="grid max-h-[360px] w-full grid-cols-6 justify-items-center overflow-y-auto">
<button
v-for="icon in filteredIcons"
:key="icon.name"
class="inline-flex items-center justify-center whitespace-nowrap font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 h-8 w-8 px-1 text-lg hover:bg-accent hover:text-accent-foreground text-foreground/80 rounded-full"
:class="{ 'bg-primary text-primary-foreground': selectedIcon === icon.name }"
@click="selectIcon(icon.name)"
:title="icon.name"
>
<component :is="icon.component" />
</button>
</div>
<!-- 分页 -->
<div class="flex-center flex justify-end overflow-hidden border-t py-2 pr-3">
<nav size="small">
<div class="flex w-full items-center gap-1">
<button
class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground p-0 size-5"
:disabled="currentPage === 1"
@click="goToPage(1)"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-left size-4">
<path d="m11 17-5-5 5-5"></path>
<path d="m18 17-5-5 5-5"></path>
</svg>
</button>
<button
class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground p-0 size-5"
:disabled="currentPage === 1"
@click="goToPage(currentPage - 1)"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-left size-4">
<path d="m15 18-6-6 6-6"></path>
</svg>
</button>
<button
v-for="page in visiblePages"
:key="page"
class="inline-flex items-center justify-center whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground size-5 p-0 text-sm"
:class="{ 'bg-primary text-primary-foreground shadow': page === currentPage }"
@click="goToPage(page)"
>
{{ page }}
</button>
<div v-if="showEllipsis" class="flex items-center justify-center size-5">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-ellipsis size-4">
<circle cx="12" cy="12" r="1"></circle>
<circle cx="19" cy="12" r="1"></circle>
<circle cx="5" cy="12" r="1"></circle>
</svg>
</div>
<button
class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground p-0 size-5"
:disabled="currentPage === totalPages"
@click="goToPage(currentPage + 1)"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-right size-4">
<path d="m9 18 6-6-6-6"></path>
</svg>
</button>
<button
class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground p-0 size-5"
:disabled="currentPage === totalPages"
@click="goToPage(totalPages)"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-right size-4">
<path d="m6 17 5-5-5-5"></path>
<path d="m13 17 5-5-5-5"></path>
</svg>
</button>
</div>
</nav>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Input } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import { computed, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Input } from 'ant-design-vue';
interface Props {
modelValue?: string
modelValue?: string;
}
interface Emits {
(e: 'update:modelValue', value: string): void
(e: 'update:modelValue', value: string): void;
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const searchKeyword = ref('')
const selectedIcon = ref(props.modelValue || '')
const currentPage = ref(1)
const pageSize = 36 // 6列 x 6行
const searchKeyword = ref('');
const selectedIcon = ref(props.modelValue || '');
const currentPage = ref(1);
const pageSize = 36; // 6列 x 6行
// 常用图标列表
const iconList = [
@@ -138,8 +45,14 @@ const iconList = [
{ name: 'lucide:clock', component: createIconifyIcon('lucide:clock') },
{ name: 'lucide:star', component: createIconifyIcon('lucide:star') },
{ name: 'lucide:heart', component: createIconifyIcon('lucide:heart') },
{ name: 'lucide:thumbs-up', component: createIconifyIcon('lucide:thumbs-up') },
{ name: 'lucide:thumbs-down', component: createIconifyIcon('lucide:thumbs-down') },
{
name: 'lucide:thumbs-up',
component: createIconifyIcon('lucide:thumbs-up'),
},
{
name: 'lucide:thumbs-down',
component: createIconifyIcon('lucide:thumbs-down'),
},
{ name: 'lucide:eye', component: createIconifyIcon('lucide:eye') },
{ name: 'lucide:eye-off', component: createIconifyIcon('lucide:eye-off') },
{ name: 'lucide:lock', component: createIconifyIcon('lucide:lock') },
@@ -147,29 +60,77 @@ const iconList = [
{ name: 'lucide:shield', component: createIconifyIcon('lucide:shield') },
{ name: 'lucide:key', component: createIconifyIcon('lucide:key') },
{ name: 'lucide:bell', component: createIconifyIcon('lucide:bell') },
{ name: 'lucide:message-circle', component: createIconifyIcon('lucide:message-circle') },
{
name: 'lucide:message-circle',
component: createIconifyIcon('lucide:message-circle'),
},
{ name: 'lucide:users', component: createIconifyIcon('lucide:users') },
{ name: 'lucide:user-plus', component: createIconifyIcon('lucide:user-plus') },
{ name: 'lucide:user-minus', component: createIconifyIcon('lucide:user-minus') },
{ name: 'lucide:user-check', component: createIconifyIcon('lucide:user-check') },
{
name: 'lucide:user-plus',
component: createIconifyIcon('lucide:user-plus'),
},
{
name: 'lucide:user-minus',
component: createIconifyIcon('lucide:user-minus'),
},
{
name: 'lucide:user-check',
component: createIconifyIcon('lucide:user-check'),
},
{ name: 'lucide:user-x', component: createIconifyIcon('lucide:user-x') },
{ name: 'lucide:grid', component: createIconifyIcon('lucide:grid') },
{ name: 'lucide:list', component: createIconifyIcon('lucide:list') },
{ name: 'lucide:layout', component: createIconifyIcon('lucide:layout') },
{ name: 'lucide:sidebar', component: createIconifyIcon('lucide:sidebar') },
{ name: 'lucide:panel-left', component: createIconifyIcon('lucide:panel-left') },
{ name: 'lucide:panel-right', component: createIconifyIcon('lucide:panel-right') },
{ name: 'lucide:panel-top', component: createIconifyIcon('lucide:panel-top') },
{ name: 'lucide:panel-bottom', component: createIconifyIcon('lucide:panel-bottom') },
{ name: 'lucide:chevron-up', component: createIconifyIcon('lucide:chevron-up') },
{ name: 'lucide:chevron-down', component: createIconifyIcon('lucide:chevron-down') },
{ name: 'lucide:chevron-left', component: createIconifyIcon('lucide:chevron-left') },
{ name: 'lucide:chevron-right', component: createIconifyIcon('lucide:chevron-right') },
{
name: 'lucide:panel-left',
component: createIconifyIcon('lucide:panel-left'),
},
{
name: 'lucide:panel-right',
component: createIconifyIcon('lucide:panel-right'),
},
{
name: 'lucide:panel-top',
component: createIconifyIcon('lucide:panel-top'),
},
{
name: 'lucide:panel-bottom',
component: createIconifyIcon('lucide:panel-bottom'),
},
{
name: 'lucide:chevron-up',
component: createIconifyIcon('lucide:chevron-up'),
},
{
name: 'lucide:chevron-down',
component: createIconifyIcon('lucide:chevron-down'),
},
{
name: 'lucide:chevron-left',
component: createIconifyIcon('lucide:chevron-left'),
},
{
name: 'lucide:chevron-right',
component: createIconifyIcon('lucide:chevron-right'),
},
{ name: 'lucide:arrow-up', component: createIconifyIcon('lucide:arrow-up') },
{ name: 'lucide:arrow-down', component: createIconifyIcon('lucide:arrow-down') },
{ name: 'lucide:arrow-left', component: createIconifyIcon('lucide:arrow-left') },
{ name: 'lucide:arrow-right', component: createIconifyIcon('lucide:arrow-right') },
{ name: 'lucide:external-link', component: createIconifyIcon('lucide:external-link') },
{
name: 'lucide:arrow-down',
component: createIconifyIcon('lucide:arrow-down'),
},
{
name: 'lucide:arrow-left',
component: createIconifyIcon('lucide:arrow-left'),
},
{
name: 'lucide:arrow-right',
component: createIconifyIcon('lucide:arrow-right'),
},
{
name: 'lucide:external-link',
component: createIconifyIcon('lucide:external-link'),
},
{ name: 'lucide:link', component: createIconifyIcon('lucide:link') },
{ name: 'lucide:unlink', component: createIconifyIcon('lucide:unlink') },
{ name: 'lucide:copy', component: createIconifyIcon('lucide:copy') },
@@ -177,83 +138,170 @@ const iconList = [
{ name: 'lucide:paste', component: createIconifyIcon('lucide:paste') },
{ name: 'lucide:undo', component: createIconifyIcon('lucide:undo') },
{ name: 'lucide:redo', component: createIconifyIcon('lucide:redo') },
{ name: 'lucide:refresh-cw', component: createIconifyIcon('lucide:refresh-cw') },
{ name: 'lucide:rotate-cw', component: createIconifyIcon('lucide:rotate-cw') },
{ name: 'lucide:rotate-ccw', component: createIconifyIcon('lucide:rotate-ccw') },
{
name: 'lucide:refresh-cw',
component: createIconifyIcon('lucide:refresh-cw'),
},
{
name: 'lucide:rotate-cw',
component: createIconifyIcon('lucide:rotate-cw'),
},
{
name: 'lucide:rotate-ccw',
component: createIconifyIcon('lucide:rotate-ccw'),
},
{ name: 'lucide:zoom-in', component: createIconifyIcon('lucide:zoom-in') },
{ name: 'lucide:zoom-out', component: createIconifyIcon('lucide:zoom-out') },
{ name: 'lucide:maximize', component: createIconifyIcon('lucide:maximize') },
{ name: 'lucide:minimize', component: createIconifyIcon('lucide:minimize') },
{ name: 'lucide:monitor', component: createIconifyIcon('lucide:monitor') },
{ name: 'lucide:smartphone', component: createIconifyIcon('lucide:smartphone') },
{
name: 'lucide:smartphone',
component: createIconifyIcon('lucide:smartphone'),
},
{ name: 'lucide:tablet', component: createIconifyIcon('lucide:tablet') },
{ name: 'lucide:laptop', component: createIconifyIcon('lucide:laptop') },
{ name: 'lucide:desktop', component: createIconifyIcon('lucide:desktop') },
{ name: 'lucide:server', component: createIconifyIcon('lucide:server') },
{ name: 'lucide:database', component: createIconifyIcon('lucide:database') },
{ name: 'lucide:hard-drive', component: createIconifyIcon('lucide:hard-drive') },
{
name: 'lucide:hard-drive',
component: createIconifyIcon('lucide:hard-drive'),
},
{ name: 'lucide:wifi', component: createIconifyIcon('lucide:wifi') },
{ name: 'lucide:bluetooth', component: createIconifyIcon('lucide:bluetooth') },
{
name: 'lucide:bluetooth',
component: createIconifyIcon('lucide:bluetooth'),
},
{ name: 'lucide:usb', component: createIconifyIcon('lucide:usb') },
{ name: 'lucide:plug', component: createIconifyIcon('lucide:plug') },
{ name: 'lucide:battery', component: createIconifyIcon('lucide:battery') },
{ name: 'lucide:battery-charging', component: createIconifyIcon('lucide:battery-charging') },
{
name: 'lucide:battery-charging',
component: createIconifyIcon('lucide:battery-charging'),
},
{ name: 'lucide:power', component: createIconifyIcon('lucide:power') },
{ name: 'lucide:volume-2', component: createIconifyIcon('lucide:volume-2') },
{ name: 'lucide:volume-x', component: createIconifyIcon('lucide:volume-x') },
{ name: 'lucide:play', component: createIconifyIcon('lucide:play') },
{ name: 'lucide:pause', component: createIconifyIcon('lucide:pause') },
{ name: 'lucide:stop', component: createIconifyIcon('lucide:stop') },
{ name: 'lucide:skip-back', component: createIconifyIcon('lucide:skip-back') },
{ name: 'lucide:skip-forward', component: createIconifyIcon('lucide:skip-forward') },
{
name: 'lucide:skip-back',
component: createIconifyIcon('lucide:skip-back'),
},
{
name: 'lucide:skip-forward',
component: createIconifyIcon('lucide:skip-forward'),
},
{ name: 'lucide:repeat', component: createIconifyIcon('lucide:repeat') },
{ name: 'lucide:shuffle', component: createIconifyIcon('lucide:shuffle') },
{ name: 'lucide:mic', component: createIconifyIcon('lucide:mic') },
{ name: 'lucide:mic-off', component: createIconifyIcon('lucide:mic-off') },
{ name: 'lucide:camera', component: createIconifyIcon('lucide:camera') },
{ name: 'lucide:camera-off', component: createIconifyIcon('lucide:camera-off') },
{ name: 'lucide:video-off', component: createIconifyIcon('lucide:video-off') },
{
name: 'lucide:camera-off',
component: createIconifyIcon('lucide:camera-off'),
},
{
name: 'lucide:video-off',
component: createIconifyIcon('lucide:video-off'),
},
{ name: 'lucide:cast', component: createIconifyIcon('lucide:cast') },
{ name: 'lucide:airplay', component: createIconifyIcon('lucide:airplay') },
{ name: 'lucide:headphones', component: createIconifyIcon('lucide:headphones') },
{
name: 'lucide:headphones',
component: createIconifyIcon('lucide:headphones'),
},
{ name: 'lucide:speaker', component: createIconifyIcon('lucide:speaker') },
{ name: 'lucide:radio', component: createIconifyIcon('lucide:radio') },
{ name: 'lucide:tv', component: createIconifyIcon('lucide:tv') },
{ name: 'lucide:gamepad-2', component: createIconifyIcon('lucide:gamepad-2') },
{
name: 'lucide:gamepad-2',
component: createIconifyIcon('lucide:gamepad-2'),
},
{ name: 'lucide:joystick', component: createIconifyIcon('lucide:joystick') },
{ name: 'lucide:controller', component: createIconifyIcon('lucide:controller') },
{
name: 'lucide:controller',
component: createIconifyIcon('lucide:controller'),
},
{ name: 'lucide:mouse', component: createIconifyIcon('lucide:mouse') },
{ name: 'lucide:keyboard', component: createIconifyIcon('lucide:keyboard') },
{ name: 'lucide:printer', component: createIconifyIcon('lucide:printer') },
{ name: 'lucide:scanner', component: createIconifyIcon('lucide:scanner') },
{ name: 'lucide:fax', component: createIconifyIcon('lucide:fax') },
{ name: 'lucide:calculator', component: createIconifyIcon('lucide:calculator') },
{
name: 'lucide:calculator',
component: createIconifyIcon('lucide:calculator'),
},
{ name: 'lucide:watch', component: createIconifyIcon('lucide:watch') },
{ name: 'lucide:alarm-clock', component: createIconifyIcon('lucide:alarm-clock') },
{
name: 'lucide:alarm-clock',
component: createIconifyIcon('lucide:alarm-clock'),
},
{ name: 'lucide:timer', component: createIconifyIcon('lucide:timer') },
{ name: 'lucide:stopwatch', component: createIconifyIcon('lucide:stopwatch') },
{ name: 'lucide:hourglass', component: createIconifyIcon('lucide:hourglass') },
{ name: 'lucide:thermometer', component: createIconifyIcon('lucide:thermometer') },
{
name: 'lucide:stopwatch',
component: createIconifyIcon('lucide:stopwatch'),
},
{
name: 'lucide:hourglass',
component: createIconifyIcon('lucide:hourglass'),
},
{
name: 'lucide:thermometer',
component: createIconifyIcon('lucide:thermometer'),
},
{ name: 'lucide:gauge', component: createIconifyIcon('lucide:gauge') },
{ name: 'lucide:activity', component: createIconifyIcon('lucide:activity') },
{ name: 'lucide:trending-up', component: createIconifyIcon('lucide:trending-up') },
{ name: 'lucide:trending-down', component: createIconifyIcon('lucide:trending-down') },
{ name: 'lucide:bar-chart', component: createIconifyIcon('lucide:bar-chart') },
{ name: 'lucide:line-chart', component: createIconifyIcon('lucide:line-chart') },
{ name: 'lucide:pie-chart', component: createIconifyIcon('lucide:pie-chart') },
{ name: 'lucide:credit-card', component: createIconifyIcon('lucide:credit-card') },
{
name: 'lucide:trending-up',
component: createIconifyIcon('lucide:trending-up'),
},
{
name: 'lucide:trending-down',
component: createIconifyIcon('lucide:trending-down'),
},
{
name: 'lucide:bar-chart',
component: createIconifyIcon('lucide:bar-chart'),
},
{
name: 'lucide:line-chart',
component: createIconifyIcon('lucide:line-chart'),
},
{
name: 'lucide:pie-chart',
component: createIconifyIcon('lucide:pie-chart'),
},
{
name: 'lucide:credit-card',
component: createIconifyIcon('lucide:credit-card'),
},
{ name: 'lucide:wallet', component: createIconifyIcon('lucide:wallet') },
{ name: 'lucide:banknote', component: createIconifyIcon('lucide:banknote') },
{ name: 'lucide:coins', component: createIconifyIcon('lucide:coins') },
{ name: 'lucide:receipt', component: createIconifyIcon('lucide:receipt') },
{ name: 'lucide:shopping-cart', component: createIconifyIcon('lucide:shopping-cart') },
{ name: 'lucide:shopping-bag', component: createIconifyIcon('lucide:shopping-bag') },
{
name: 'lucide:shopping-cart',
component: createIconifyIcon('lucide:shopping-cart'),
},
{
name: 'lucide:shopping-bag',
component: createIconifyIcon('lucide:shopping-bag'),
},
{ name: 'lucide:store', component: createIconifyIcon('lucide:store') },
{ name: 'lucide:building', component: createIconifyIcon('lucide:building') },
{ name: 'lucide:building-2', component: createIconifyIcon('lucide:building-2') },
{
name: 'lucide:building-2',
component: createIconifyIcon('lucide:building-2'),
},
{ name: 'lucide:map', component: createIconifyIcon('lucide:map') },
{ name: 'lucide:map-pin', component: createIconifyIcon('lucide:map-pin') },
{ name: 'lucide:navigation', component: createIconifyIcon('lucide:navigation') },
{
name: 'lucide:navigation',
component: createIconifyIcon('lucide:navigation'),
},
{ name: 'lucide:compass', component: createIconifyIcon('lucide:compass') },
{ name: 'lucide:globe', component: createIconifyIcon('lucide:globe') },
{ name: 'lucide:earth', component: createIconifyIcon('lucide:earth') },
@@ -269,13 +317,28 @@ const iconList = [
{ name: 'lucide:forward', component: createIconifyIcon('lucide:forward') },
{ name: 'lucide:share', component: createIconifyIcon('lucide:share') },
{ name: 'lucide:share-2', component: createIconifyIcon('lucide:share-2') },
{ name: 'lucide:git-branch', component: createIconifyIcon('lucide:git-branch') },
{ name: 'lucide:git-commit', component: createIconifyIcon('lucide:git-commit') },
{ name: 'lucide:git-merge', component: createIconifyIcon('lucide:git-merge') },
{ name: 'lucide:git-pull-request', component: createIconifyIcon('lucide:git-pull-request') },
{
name: 'lucide:git-branch',
component: createIconifyIcon('lucide:git-branch'),
},
{
name: 'lucide:git-commit',
component: createIconifyIcon('lucide:git-commit'),
},
{
name: 'lucide:git-merge',
component: createIconifyIcon('lucide:git-merge'),
},
{
name: 'lucide:git-pull-request',
component: createIconifyIcon('lucide:git-pull-request'),
},
{ name: 'lucide:github', component: createIconifyIcon('lucide:github') },
{ name: 'lucide:gitlab', component: createIconifyIcon('lucide:gitlab') },
{ name: 'lucide:bitbucket', component: createIconifyIcon('lucide:bitbucket') },
{
name: 'lucide:bitbucket',
component: createIconifyIcon('lucide:bitbucket'),
},
{ name: 'lucide:code', component: createIconifyIcon('lucide:code') },
{ name: 'lucide:code-2', component: createIconifyIcon('lucide:code-2') },
{ name: 'lucide:terminal', component: createIconifyIcon('lucide:terminal') },
@@ -283,19 +346,43 @@ const iconList = [
{ name: 'lucide:hash', component: createIconifyIcon('lucide:hash') },
{ name: 'lucide:brackets', component: createIconifyIcon('lucide:brackets') },
{ name: 'lucide:braces', component: createIconifyIcon('lucide:braces') },
{ name: 'lucide:parentheses', component: createIconifyIcon('lucide:parentheses') },
{
name: 'lucide:parentheses',
component: createIconifyIcon('lucide:parentheses'),
},
{ name: 'lucide:slash', component: createIconifyIcon('lucide:slash') },
{ name: 'lucide:backslash', component: createIconifyIcon('lucide:backslash') },
{
name: 'lucide:backslash',
component: createIconifyIcon('lucide:backslash'),
},
{ name: 'lucide:at-sign', component: createIconifyIcon('lucide:at-sign') },
{ name: 'lucide:percent', component: createIconifyIcon('lucide:percent') },
{ name: 'lucide:asterisk', component: createIconifyIcon('lucide:asterisk') },
{ name: 'lucide:ampersand', component: createIconifyIcon('lucide:ampersand') },
{
name: 'lucide:ampersand',
component: createIconifyIcon('lucide:ampersand'),
},
{ name: 'lucide:equal', component: createIconifyIcon('lucide:equal') },
{ name: 'lucide:not-equal', component: createIconifyIcon('lucide:not-equal') },
{ name: 'lucide:greater-than', component: createIconifyIcon('lucide:greater-than') },
{ name: 'lucide:less-than', component: createIconifyIcon('lucide:less-than') },
{ name: 'lucide:greater-than-equal', component: createIconifyIcon('lucide:greater-than-equal') },
{ name: 'lucide:less-than-equal', component: createIconifyIcon('lucide:less-than-equal') },
{
name: 'lucide:not-equal',
component: createIconifyIcon('lucide:not-equal'),
},
{
name: 'lucide:greater-than',
component: createIconifyIcon('lucide:greater-than'),
},
{
name: 'lucide:less-than',
component: createIconifyIcon('lucide:less-than'),
},
{
name: 'lucide:greater-than-equal',
component: createIconifyIcon('lucide:greater-than-equal'),
},
{
name: 'lucide:less-than-equal',
component: createIconifyIcon('lucide:less-than-equal'),
},
{ name: 'lucide:minus', component: createIconifyIcon('lucide:minus') },
{ name: 'lucide:divide', component: createIconifyIcon('lucide:divide') },
{ name: 'lucide:multiply', component: createIconifyIcon('lucide:multiply') },
@@ -324,95 +411,263 @@ const iconList = [
{ name: 'lucide:chi', component: createIconifyIcon('lucide:chi') },
{ name: 'lucide:psi', component: createIconifyIcon('lucide:psi') },
{ name: 'lucide:omega', component: createIconifyIcon('lucide:omega') },
]
];
// 过滤后的图标
const filteredIcons = computed(() => {
let icons = iconList
let icons = iconList;
if (searchKeyword.value) {
icons = icons.filter(icon =>
icon.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
)
icons = icons.filter((icon) =>
icon.name.toLowerCase().includes(searchKeyword.value.toLowerCase()),
);
}
const start = (currentPage.value - 1) * pageSize
const end = start + pageSize
return icons.slice(start, end)
})
const start = (currentPage.value - 1) * pageSize;
const end = start + pageSize;
return icons.slice(start, end);
});
// 总页数
const totalPages = computed(() => {
let total = iconList.length
let total = iconList.length;
if (searchKeyword.value) {
total = iconList.filter(icon =>
icon.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
).length
total = iconList.filter((icon) =>
icon.name.toLowerCase().includes(searchKeyword.value.toLowerCase()),
).length;
}
return Math.ceil(total / pageSize)
})
return Math.ceil(total / pageSize);
});
// 可见页码
const visiblePages = computed(() => {
const pages = []
const total = totalPages.value
const current = currentPage.value
const pages = [];
const total = totalPages.value;
const current = currentPage.value;
if (total <= 7) {
for (let i = 1; i <= total; i++) {
pages.push(i)
pages.push(i);
}
} else {
if (current <= 4) {
for (let i = 1; i <= 5; i++) {
pages.push(i)
pages.push(i);
}
} else if (current >= total - 3) {
for (let i = total - 4; i <= total; i++) {
pages.push(i)
pages.push(i);
}
} else {
for (let i = current - 2; i <= current + 2; i++) {
pages.push(i)
pages.push(i);
}
}
}
return pages
})
return pages;
});
// 是否显示省略号
const showEllipsis = computed(() => {
return totalPages.value > 7 && currentPage.value > 4 && currentPage.value < totalPages.value - 3
})
return (
totalPages.value > 7 &&
currentPage.value > 4 &&
currentPage.value < totalPages.value - 3
);
});
// 选择图标
const selectIcon = (iconName: string) => {
selectedIcon.value = iconName
emit('update:modelValue', iconName)
}
selectedIcon.value = iconName;
emit('update:modelValue', iconName);
};
// 搜索处理
const handleSearch = () => {
currentPage.value = 1
}
currentPage.value = 1;
};
// 跳转页面
const goToPage = (page: number) => {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page
currentPage.value = page;
}
}
};
// 监听props变化
watch(() => props.modelValue, (newVal) => {
selectedIcon.value = newVal || ''
})
watch(
() => props.modelValue,
(newVal) => {
selectedIcon.value = newVal || '';
},
);
</script>
<template>
<div class="icon-selector">
<!-- 搜索框 -->
<div class="mb-2 flex w-full">
<Input
v-model:value="searchKeyword"
placeholder="搜索图标..."
class="mx-2"
@input="handleSearch"
/>
</div>
<!-- 图标网格 -->
<div
class="grid max-h-[360px] w-full grid-cols-6 justify-items-center overflow-y-auto"
>
<button
v-for="icon in filteredIcons"
:key="icon.name"
class="focus-visible:ring-ring hover:bg-accent hover:text-accent-foreground text-foreground/80 inline-flex h-8 w-8 items-center justify-center whitespace-nowrap rounded-full px-1 text-lg font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:class="{
'bg-primary text-primary-foreground': selectedIcon === icon.name,
}"
@click="selectIcon(icon.name)"
:title="icon.name"
>
<component :is="icon.component" />
</button>
</div>
<!-- 分页 -->
<div
class="flex-center flex justify-end overflow-hidden border-t py-2 pr-3"
>
<nav size="small">
<div class="flex w-full items-center gap-1">
<button
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === 1"
@click="goToPage(1)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevrons-left size-4"
>
<path d="m11 17-5-5 5-5" />
<path d="m18 17-5-5 5-5" />
</svg>
</button>
<button
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === 1"
@click="goToPage(currentPage - 1)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevron-left size-4"
>
<path d="m15 18-6-6 6-6" />
</svg>
</button>
<button
v-for="page in visiblePages"
:key="page"
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:class="{
'bg-primary text-primary-foreground shadow': page === currentPage,
}"
@click="goToPage(page)"
>
{{ page }}
</button>
<div
v-if="showEllipsis"
class="flex size-5 items-center justify-center"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-ellipsis size-4"
>
<circle cx="12" cy="12" r="1" />
<circle cx="19" cy="12" r="1" />
<circle cx="5" cy="12" r="1" />
</svg>
</div>
<button
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === totalPages"
@click="goToPage(currentPage + 1)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevron-right size-4"
>
<path d="m9 18 6-6-6-6" />
</svg>
</button>
<button
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="currentPage === totalPages"
@click="goToPage(totalPages)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide lucide-chevrons-right size-4"
>
<path d="m6 17 5-5-5-5" />
<path d="m13 17 5-5-5-5" />
</svg>
</button>
</div>
</nav>
</div>
</div>
</template>
<style scoped>
.icon-selector {
width: 100%;
@@ -1,26 +1,38 @@
<script setup lang="ts">
import { ref, h } from 'vue'
import { Form, Input, InputNumber, Select, Popover, message, Radio, Switch } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import { useVbenModal } from '@vben/common-ui'
import IconSelector from './IconSelector.vue'
import {
createMenuApi,
updateMenuApi,
import type { MenuVO } from '#/api/system/menu/types';
import { h, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Form,
Input,
InputNumber,
message,
Popover,
Radio,
Select,
Switch,
} from 'ant-design-vue';
import {
createMenuApi,
getAllMenusApi,
} from '#/api/system/menu'
import type { MenuVO } from '#/api/system/menu/types'
import {
addMenuPermissionApi,
removeMenuPermissionApi
} from '#/api/system/menu-permission'
import {
getAllPermissionsApi
} from '#/api/system/permission'
updateMenuApi,
} from '#/api/system/menu';
import {
addMenuPermissionApi,
removeMenuPermissionApi,
} from '#/api/system/menu-permission';
import { getAllPermissionsApi } from '#/api/system/permission';
import IconSelector from './IconSelector.vue';
const emit = defineEmits<{
success: [];
cancel: [];
success: [];
}>();
// 创建Vben Modal实例
@@ -75,7 +87,7 @@ const formData = ref<FormData>({
visible: true,
status: true,
keepAlive: false,
})
});
// 下拉选项数据
const parentMenuOptions = ref<{ label: string; value: number }[]>([]);
@@ -91,7 +103,7 @@ const iconSelectorContent = h(IconSelector, {
modelValue: formData.value.icon,
'onUpdate:modelValue': (value: string) => {
formData.value.icon = value;
}
},
});
// 获取父菜单选项
@@ -99,9 +111,9 @@ async function fetchParentMenuOptions() {
try {
const data = await getAllMenusApi();
const options: Array<{ label: string; value: number }> = [];
const addMenuOptions = (menus: MenuVO.MenuInfo[], level = 0) => {
menus.forEach(menu => {
menus.forEach((menu) => {
const prefix = ' '.repeat(level);
options.push({
label: `${prefix}${menu.title || menu.name}`,
@@ -112,7 +124,7 @@ async function fetchParentMenuOptions() {
}
});
};
addMenuOptions(data);
parentMenuOptions.value = options;
} catch (error) {
@@ -124,7 +136,7 @@ async function fetchParentMenuOptions() {
async function fetchPermissionOptions() {
try {
const data = await getAllPermissionsApi();
const options = data.map(permission => ({
const options = data.map((permission) => ({
label: permission.name,
value: permission.id,
}));
@@ -138,14 +150,14 @@ async function fetchPermissionOptions() {
function open(edit: boolean, record?: MenuVO.MenuInfo) {
isEdit.value = edit;
currentRecord.value = record || null;
// 更新模态框标题
modalApi.setState({
title: edit ? '编辑菜单' : '添加菜单'
title: edit ? '编辑菜单' : '添加菜单',
});
modalApi.open();
if (edit && record) {
// 编辑模式,填充表单数据
formData.value = {
@@ -163,10 +175,12 @@ function open(edit: boolean, record?: MenuVO.MenuInfo) {
status: record.status === 1, // 转换为boolean
keepAlive: record.keepAlive === 1, // 转换为boolean
};
// 设置权限数据
if ((record as any).permissions && (record as any).permissions.length > 0) {
selectedPermissions.value = (record as any).permissions.map((p: any) => p.id);
selectedPermissions.value = (record as any).permissions.map(
(p: any) => p.id,
);
originalPermissions.value = [...selectedPermissions.value];
} else {
selectedPermissions.value = [];
@@ -206,7 +220,7 @@ function open(edit: boolean, record?: MenuVO.MenuInfo) {
status: true,
keepAlive: false,
};
// 重置权限数据
selectedPermissions.value = [];
originalPermissions.value = [];
@@ -225,37 +239,41 @@ function close() {
// 处理权限变更
async function handlePermissionChange() {
if (!currentRecord.value) return;
const menuId = currentRecord.value.id;
const currentPermissions = selectedPermissions.value;
const originalPermissionsList = originalPermissions.value;
// 找出新增的权限
const addedPermissions = currentPermissions.filter(id => !originalPermissionsList.includes(id));
const addedPermissions = currentPermissions.filter(
(id) => !originalPermissionsList.includes(id),
);
// 找出移除的权限
const removedPermissions = originalPermissionsList.filter(id => !currentPermissions.includes(id));
const removedPermissions = originalPermissionsList.filter(
(id) => !currentPermissions.includes(id),
);
try {
// 添加新权限
for (const permissionId of addedPermissions) {
await addMenuPermissionApi({
menuId,
permissionId
permissionId,
});
}
// 移除权限
for (const permissionId of removedPermissions) {
await removeMenuPermissionApi({
menuId,
permissionId
permissionId,
});
}
// 更新原始权限列表
originalPermissions.value = [...currentPermissions];
if (addedPermissions.length > 0 || removedPermissions.length > 0) {
message.success('权限更新成功');
}
@@ -269,7 +287,7 @@ async function handlePermissionChange() {
async function handleSubmit() {
try {
await formRef.value?.validate();
// 设置模态框为loading状态
modalApi.setState({ confirmLoading: true });
@@ -286,20 +304,20 @@ async function handleSubmit() {
// 更新菜单
await updateMenuApi(currentRecord.value.id, submitData);
message.success('更新菜单成功');
// 处理权限变更
await handlePermissionChange();
} else {
// 创建菜单
const newMenu = await createMenuApi(submitData);
message.success('创建菜单成功');
// 如果有选择的权限,为新菜单添加权限
if (selectedPermissions.value.length > 0 && newMenu?.id) {
for (const permissionId of selectedPermissions.value) {
await addMenuPermissionApi({
menuId: newMenu.id,
permissionId
permissionId,
});
}
message.success('权限分配成功');
@@ -316,8 +334,6 @@ async function handleSubmit() {
}
}
// 暴露方法
defineExpose({
open,
@@ -334,8 +350,16 @@ defineExpose({
:wrapper-col="{ span: 18 }"
class="space-y-5"
>
<Form.Item label="菜单类型" name="type" :rules="[{ required: true, message: '请选择菜单类型' }]">
<Radio.Group v-model:value="formData.type" button-style="solid" class="w-full">
<Form.Item
label="菜单类型"
name="type"
:rules="[{ required: true, message: '请选择菜单类型' }]"
>
<Radio.Group
v-model:value="formData.type"
button-style="solid"
class="w-full"
>
<Radio.Button value="catalog" class="flex-1">目录</Radio.Button>
<Radio.Button value="menu" class="flex-1">菜单</Radio.Button>
<Radio.Button value="button" class="flex-1">按钮</Radio.Button>
@@ -343,7 +367,7 @@ defineExpose({
<Radio.Button value="link" class="flex-1">外链</Radio.Button>
</Radio.Group>
</Form.Item>
<Form.Item label="父菜单" name="parentId">
<Select
v-model:value="formData.parentId"
@@ -352,7 +376,7 @@ defineExpose({
allow-clear
/>
</Form.Item>
<Form.Item label="权限列表" name="permissions">
<Select
v-model:value="selectedPermissions"
@@ -364,27 +388,37 @@ defineExpose({
:max-tag-text-length="10"
/>
</Form.Item>
<Form.Item label="菜单名称" name="name" :rules="[{ required: true, message: '请输入菜单名称' }]">
<Form.Item
label="菜单名称"
name="name"
:rules="[{ required: true, message: '请输入菜单名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入菜单名称" />
</Form.Item>
<Form.Item label="菜单标题" name="title">
<Input v-model:value="formData.title" placeholder="请输入菜单标题" />
</Form.Item>
<Form.Item label="路由路径" name="path">
<Input v-model:value="formData.path" placeholder="请输入路由路径" />
</Form.Item>
<Form.Item label="页面组件" name="component">
<Input v-model:value="formData.component" placeholder="请输入页面组件" />
<Input
v-model:value="formData.component"
placeholder="请输入页面组件"
/>
</Form.Item>
<Form.Item label="重定向地址" name="redirect">
<Input v-model:value="formData.redirect" placeholder="请输入重定向地址" />
<Input
v-model:value="formData.redirect"
placeholder="请输入重定向地址"
/>
</Form.Item>
<Form.Item label="路由图标" name="icon">
<Popover
placement="bottomRight"
@@ -392,25 +426,27 @@ defineExpose({
:content="iconSelectorContent"
overlay-class-name="icon-selector-popover"
>
<Input
v-model:value="formData.icon"
placeholder="请输入路由图标"
<Input
v-model:value="formData.icon"
placeholder="请输入路由图标"
readonly
style="cursor: pointer;"
style="cursor: pointer"
>
<template #suffix>
<GridIcon
class="w-4 h-4 cursor-pointer"
/>
<GridIcon class="h-4 w-4 cursor-pointer" />
</template>
</Input>
</Popover>
</Form.Item>
<Form.Item label="排序" name="order">
<InputNumber v-model:value="formData.order" placeholder="请输入排序" :min="0" />
<InputNumber
v-model:value="formData.order"
placeholder="请输入排序"
:min="0"
/>
</Form.Item>
<Form.Item label="是否显示" name="visible">
<Switch
v-model:checked="formData.visible"
@@ -419,7 +455,7 @@ defineExpose({
class="w-12"
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
@@ -428,7 +464,7 @@ defineExpose({
class="w-12"
/>
</Form.Item>
<Form.Item label="是否缓存" name="keepAlive">
<Switch
v-model:checked="formData.keepAlive"
@@ -437,7 +473,7 @@ defineExpose({
class="w-12"
/>
</Form.Item>
<Form.Item label="超级菜单" name="superMenu">
<Switch
v-model:checked="formData.superMenu"
@@ -449,5 +485,3 @@ defineExpose({
</Form>
</Modal>
</template>
@@ -1,20 +1,24 @@
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MenuVO } from '#/api/system/menu/types';
import { onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deleteMenuApi,
getAllMenusApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
batchSortMenuApi,
deleteMenuApi,
getAllMenusApi,
} from '#/api/system/menu';
import type { MenuVO } from '#/api/system/menu/types';
import MenuFormModal from './components/MenuFormModal.vue';
defineOptions({ name: 'MenuManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
const EditIcon = createIconifyIcon('lucide:edit');
@@ -25,8 +29,6 @@ const PlusCircleIcon = createIconifyIcon('lucide:plus-circle');
const ExpandIcon = createIconifyIcon('lucide:chevrons-down');
const CollapseIcon = createIconifyIcon('lucide:chevrons-up');
defineOptions({ name: 'MenuManagement' });
// 响应式数据
const loading = ref(false);
const menuFormModalRef = ref();
@@ -147,7 +149,6 @@ const gridOptions: VxeGridProps<any> = {
},
};
// 刷新表格数据
function refreshTable() {
if (gridApi) {
@@ -199,11 +200,11 @@ const handleDragSort = async (_params: any) => {
try {
isUpdating = true;
// 获取当前表格数据
const tableDataResult = gridApi.grid.getTableData();
const tableData = tableDataResult?.tableData || [];
// 构建排序数据
const sortItems = tableData.map((item: MenuVO.MenuInfo, index: number) => ({
menuId: item.id,
@@ -212,7 +213,7 @@ const handleDragSort = async (_params: any) => {
// 调用排序接口
await batchSortMenuApi({ sortItems });
// 排序成功后不需要重新加载数据,因为表格数据已经更新
} catch (error: any) {
console.error('拖拽排序失败:', error);
@@ -272,7 +273,6 @@ function getMenuTypeColor(type: string) {
return colorMap[type] || 'default';
}
// 获取菜单图标
function getMenuIcon(menu: MenuVO.MenuInfo) {
if (menu.icon) {
@@ -280,13 +280,16 @@ function getMenuIcon(menu: MenuVO.MenuInfo) {
}
// 根据菜单类型返回默认图标
switch (menu.type) {
case 'catalog':
case 'catalog': {
return FolderIcon;
case 'menu':
}
case 'embedded':
case 'menu': {
return FileIcon;
default:
}
default: {
return FileIcon;
}
}
}
@@ -326,10 +329,7 @@ onMounted(() => {
<template>
<Page title="菜单管理" auto-content-height>
<!-- VbenVxeGrid 表格 -->
<Grid
ref="gridRef"
:loading="loading"
>
<Grid ref="gridRef" :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -345,7 +345,7 @@ onMounted(() => {
<CollapseIcon />
全部收起
</Button>
<div class="text-gray-500 text-sm">
<div class="text-sm text-gray-500">
💡 提示:可直接拖拽菜单名称列进行排序
</div>
</Space>
@@ -356,7 +356,7 @@ onMounted(() => {
<!-- 图标列 -->
<template #icon="{ row }: { row: any }">
<div v-if="row.icon" class="flex items-center justify-center">
<component :is="getMenuIcon(row)" class="w-4 h-4 text-blue-600" />
<component :is="getMenuIcon(row)" class="h-4 w-4 text-blue-600" />
</div>
<span v-else class="text-gray-400">-</span>
</template>
@@ -377,7 +377,10 @@ onMounted(() => {
<!-- 权限名称列 -->
<template #permissions="{ row }: { row: any }">
<div v-if="row.permissions && row.permissions.length > 0" class="flex flex-wrap gap-1">
<div
v-if="row.permissions && row.permissions.length > 0"
class="flex flex-wrap gap-1"
>
<Tag
v-for="permission in row.permissions"
:key="permission.id"
@@ -394,15 +397,15 @@ onMounted(() => {
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleAddChild(row)">
<PlusCircleIcon class="w-3 h-3" />
<PlusCircleIcon class="h-3 w-3" />
增加下级
</Button>
<Button size="small" @click="handleEdit(row)">
<EditIcon class="w-3 h-3" />
<EditIcon class="h-3 w-3" />
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
<TrashIcon class="w-3 h-3" />
<TrashIcon class="h-3 w-3" />
删除
</Button>
</Space>
@@ -410,10 +413,6 @@ onMounted(() => {
</Grid>
<!-- 菜单表单模态框 -->
<MenuFormModal
ref="menuFormModalRef"
@success="handleModalSuccess"
/>
<MenuFormModal ref="menuFormModalRef" @success="handleModalSuccess" />
</Page>
</template>
@@ -1,22 +1,25 @@
<script lang="ts" setup>
import type { PermissionVO } from '#/api/system/permission';
import { ref } from 'vue';
import { Form, Input, Select, Switch, message } from 'ant-design-vue';
import { useVbenModal } from '@vben/common-ui';
import {
createPermissionApi,
import { Form, Input, message, Select, Switch } from 'ant-design-vue';
import {
createPermissionApi,
updatePermissionApi,
type PermissionVO
} from '#/api/system/permission';
interface Emits {
(e: 'success'): void;
}
const emit = defineEmits<Emits>();
defineOptions({ name: 'PermissionFormModal' });
const emit = defineEmits<Emits>();
// 创建Vben Modal实例
const [Modal, modalApi] = useVbenModal({
title: '权限管理',
@@ -34,7 +37,7 @@ const [Modal, modalApi] = useVbenModal({
// 响应式数据
const formRef = ref();
const isEdit = ref(false);
const currentPermissionData = ref<PermissionVO.PermissionInfoVO | null>(null);
const currentPermissionData = ref<null | PermissionVO.PermissionInfoVO>(null);
// 内部表单数据类型
interface FormData {
@@ -54,7 +57,6 @@ const formData = ref<FormData>({
remark: '',
});
// 状态选项(开关组件不需要选项数组)
// 权限类型选项
@@ -83,17 +85,17 @@ function close() {
}
// 暴露给父组件的方法
function open(permissionData?: PermissionVO.PermissionInfoVO | null) {
function open(permissionData?: null | PermissionVO.PermissionInfoVO) {
isEdit.value = !!permissionData;
currentPermissionData.value = permissionData || null;
// 更新模态框标题
modalApi.setState({
title: isEdit.value ? '编辑权限' : '添加权限'
title: isEdit.value ? '编辑权限' : '添加权限',
});
resetForm();
if (permissionData) {
formData.value = {
code: permissionData.code,
@@ -103,7 +105,7 @@ function open(permissionData?: PermissionVO.PermissionInfoVO | null) {
remark: permissionData.remark || '',
};
}
modalApi.open();
}
@@ -111,16 +113,16 @@ function open(permissionData?: PermissionVO.PermissionInfoVO | null) {
async function handleSubmit() {
try {
await formRef.value?.validate();
// 设置模态框为loading状态
modalApi.setState({ confirmLoading: true });
// 转换状态值为数字
const submitData = {
...formData.value,
status: formData.value.status ? 1 : 0
status: formData.value.status ? 1 : 0,
};
if (isEdit.value && currentPermissionData.value) {
await updatePermissionApi(currentPermissionData.value.id, submitData);
message.success('更新成功');
@@ -128,12 +130,13 @@ async function handleSubmit() {
await createPermissionApi(submitData);
message.success('创建成功');
}
close();
emit('success');
} catch (error: any) {
console.error('保存权限失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '保存权限失败';
const errorMessage =
error?.response?.data?.message || error?.message || '保存权限失败';
message.error(errorMessage);
} finally {
modalApi.setState({ confirmLoading: false });
@@ -155,29 +158,47 @@ defineExpose({
:wrapper-col="{ span: 18 }"
class="space-y-5"
>
<Form.Item label="权限码" name="code" :rules="[
{ required: true, message: '请输入权限码' },
{ min: 2, max: 50, message: '权限码长度为2-50个字符' },
{ pattern: /^[a-zA-Z0-9:_-]+$/, message: '权限码只能包含字母、数字、冒号、下划线和连字符' }
]">
<Input v-model:value="formData.code" placeholder="请输入权限码,如 user:add" />
<Form.Item
label="权限码"
name="code"
:rules="[
{ required: true, message: '请输入权限码' },
{ min: 2, max: 50, message: '权限码长度为2-50个字符' },
{
pattern: /^[a-zA-Z0-9:_-]+$/,
message: '权限码只能包含字母、数字、冒号、下划线和连字符',
},
]"
>
<Input
v-model:value="formData.code"
placeholder="请输入权限码,如 user:add"
/>
</Form.Item>
<Form.Item label="权限名称" name="name" :rules="[
{ required: true, message: '请输入权限名称' },
{ min: 2, max: 50, message: '权限名称长度为2-50个字符' }
]">
<Form.Item
label="权限名称"
name="name"
:rules="[
{ required: true, message: '请输入权限名称' },
{ min: 2, max: 50, message: '权限名称长度为2-50个字符' },
]"
>
<Input v-model:value="formData.name" placeholder="请输入权限名称" />
</Form.Item>
<Form.Item label="权限类型" name="type" :rules="[{ required: true, message: '请选择权限类型' }]">
<Form.Item
label="权限类型"
name="type"
:rules="[{ required: true, message: '请选择权限类型' }]"
>
<Select
v-model:value="formData.type"
placeholder="请选择权限类型"
:options="typeOptions"
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Switch
v-model:checked="formData.status"
@@ -186,10 +207,10 @@ defineExpose({
class="w-12"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注信息"
:rows="3"
/>
@@ -197,4 +218,3 @@ defineExpose({
</Form>
</Modal>
</template>
@@ -1,36 +1,38 @@
<script lang="ts" setup>
import { ref, computed } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PermissionDTO, PermissionVO } from '#/api/system/permission';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Space, Tag } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {
deletePermissionApi,
import { Button, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePermissionApi,
getPermissionPageApi,
type PermissionVO,
type PermissionDTO
} from '#/api/system/permission';
import type { PageQueryDTO } from '#/types/common';
import PermissionFormModal from './components/PermissionFormModal.vue';
defineOptions({ name: 'PermissionManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
defineOptions({ name: 'PermissionManagement' });
// 响应式数据
const loading = ref(false);
const permissionFormModalRef = ref();
// 搜索表单
const searchForm = ref({
code: undefined as undefined | string,
name: undefined as undefined | string,
type: undefined as undefined | string,
status: undefined as undefined | number,
code: undefined as string | undefined,
name: undefined as string | undefined,
type: undefined as string | undefined,
status: undefined as number | undefined,
});
// 状态选项
@@ -143,7 +145,25 @@ const gridOptions: VxeGridProps<any> = {
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'] as ('PrevJump' | 'PrevPage' | 'Number' | 'NextPage' | 'NextJump' | 'Sizes' | 'FullJump' | 'Total')[],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
@@ -163,7 +183,8 @@ const gridOptions: VxeGridProps<any> = {
};
} catch (error: any) {
console.error('查询数据失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '查询数据失败';
const errorMessage =
error?.response?.data?.message || error?.message || '查询数据失败';
message.error(errorMessage);
return {
items: [],
@@ -213,7 +234,8 @@ const handleDelete = async (row: PermissionVO.PermissionInfoVO) => {
refreshTable();
} catch (error: any) {
console.error('删除失败:', error);
const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
const errorMessage =
error?.response?.data?.message || error?.message || '删除失败';
message.error(errorMessage);
}
};
@@ -227,15 +249,16 @@ const handleBatchDelete = async () => {
}
try {
const deletePromises = selectedRows.map((row: PermissionVO.PermissionInfoVO) =>
deletePermissionApi(row.id)
const deletePromises = selectedRows.map(
(row: PermissionVO.PermissionInfoVO) => deletePermissionApi(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 || '批量删除失败';
const errorMessage =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(errorMessage);
}
};
@@ -285,9 +308,7 @@ const getStatusColor = (status: number) => {
</template>
<!-- VbenVxeGrid 表格 -->
<Grid
:loading="loading"
>
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
@@ -295,11 +316,7 @@ const getStatusColor = (status: number) => {
<PlusIcon />
添加权限
</Button>
<Button
v-if="hasSelected"
danger
@click="handleBatchDelete"
>
<Button v-if="hasSelected" danger @click="handleBatchDelete">
批量删除
</Button>
</Space>
@@ -318,21 +335,20 @@ const getStatusColor = (status: number) => {
{{ getStatusText(row.status) }}
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">
编辑
</Button>
<Button size="small" danger @click="handleDelete(row)">
删除
</Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 权限表单弹窗 -->
<PermissionFormModal ref="permissionFormModalRef" @success="handleModalSuccess" />
<PermissionFormModal
ref="permissionFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>