6 Commits

Author SHA1 Message Date
ZhuRui 742c764508 feat: 样式同步 2026-07-25 11:52:49 +08:00
ZhuRui 352f52006f feat: 样式修改 2026-07-25 11:50:43 +08:00
ZhuRui 3b4dd72b11 feat: 添加banner页面 添加菜单 2026-07-25 09:39:56 +08:00
ZhuRui 03f1b6c220 feat: 优化路由 搭建赛事管理页面基础 处理部分样式问题 完成赛事列表页面搭建 2026-07-24 15:57:20 +08:00
chenzhen 5523695518 feat: 运营平台基建 搭建 2026-07-23 15:00:19 +08:00
chenzhen 3b5a908ee4 feat: 架构调整 2026-07-23 11:27:33 +08:00
68 changed files with 10588 additions and 337 deletions
+1 -4
View File
@@ -1,4 +1 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit "$1"
npx --no -- commitlint --edit $1
-3
View File
@@ -1,4 +1 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
+15 -12
View File
@@ -1,14 +1,17 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="CPMS 运营平台" />
<title>CPMS 运营平台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="六个羽友赛事运营平台" />
<title>六羽赛事运营平台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+74 -4
View File
@@ -1,12 +1,12 @@
{
"name": "cpms_web_admin_pc",
"version": "1.0.0",
"name": "cpms_operation_platform",
"version": "0.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cpms_web_admin_pc",
"version": "1.0.0",
"name": "cpms_operation_platform",
"version": "0.0.0",
"dependencies": {
"@ant-design/icons-vue": "^7.0.1",
"ant-design-vue": "^4.0.0",
@@ -19,6 +19,7 @@
"devDependencies": {
"@commitlint/cli": "^20.4.3",
"@commitlint/config-conventional": "^20.4.3",
"@rollup/plugin-strip": "^3.0.4",
"@types/node": "^20.10.0",
"@types/qs": "^6.15.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
@@ -35,6 +36,7 @@
"prettier": "^3.0.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
"vite-plugin-remove-console": "^2.2.0",
"vue-tsc": "^2.0.0"
},
"engines": {
@@ -939,6 +941,65 @@
"dev": true,
"license": "MIT"
},
"node_modules/@rollup/plugin-strip": {
"version": "3.0.4",
"resolved": "https://registry.npmmirror.com/@rollup/plugin-strip/-/plugin-strip-3.0.4.tgz",
"integrity": "sha512-LDRV49ZaavxUo2YoKKMQjCxzCxugu1rCPQa0lDYBOWLj6vtzBMr8DcoJjsmg+s450RbKbe3qI9ZLaSO+O1oNbg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.3"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/pluginutils": {
"version": "5.4.0",
"resolved": "https://registry.npmmirror.com/@rollup/pluginutils/-/pluginutils-5.4.0.tgz",
"integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0",
"estree-walker": "^2.0.2",
"picomatch": "^4.0.2"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/pluginutils/node_modules/picomatch": {
"version": "4.0.5",
"resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz",
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/@rollup/rollup-darwin-x64": {
"version": "4.62.2",
"cpu": [
@@ -2972,6 +3033,8 @@
},
"node_modules/express": {
"version": "5.2.1",
"resolved": "http://192.168.2.127:4873/express/-/express-5.2.1.tgz",
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
"license": "MIT",
"dependencies": {
"accepts": "^2.0.0",
@@ -5721,6 +5784,13 @@
}
}
},
"node_modules/vite-plugin-remove-console": {
"version": "2.2.0",
"resolved": "https://registry.npmmirror.com/vite-plugin-remove-console/-/vite-plugin-remove-console-2.2.0.tgz",
"integrity": "sha512-qgjh5pz75MdE9Kzs8J0kBwaCfifHV0ezRbB9rpGsIOxam+ilcGV7WOk91vFJXquzRmiKrFh3Hxlh0JJWAmXTbQ==",
"dev": true,
"license": "MIT"
},
"node_modules/vscode-uri": {
"version": "3.1.0",
"resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.1.0.tgz",
+5 -4
View File
@@ -6,22 +6,21 @@
"type": "module",
"scripts": {
"dev": "vite",
"serve": "vite",
"build:dev": "vue-tsc --noEmit && vite build --mode development",
"build:test": "vue-tsc --noEmit && vite build --mode test",
"build:prod": "vue-tsc --noEmit && vite build --mode production",
"preview": "vite preview",
"type-check": "vue-tsc --noEmit",
"local": "node start-debug.js",
"lint": "eslint src --ext .js,.ts,.tsx",
"lint:fix": "eslint src --ext .js,.ts,.tsx --fix",
"format": "prettier --write \"src/**/*.{js,ts,tsx,json,less,css,md}\"",
"prepare": "husky install"
"prepare": "husky"
},
"dependencies": {
"@ant-design/icons-vue": "^7.0.1",
"@yp-component/root": "^0.0.46",
"ant-design-vue": "^4.0.0",
"china-area-data": "^5.0.1",
"dayjs": "^1.11.21",
"express": "^5.2.1",
"html2canvas": "^1.4.1",
"qs": "^6.15.0",
@@ -31,6 +30,7 @@
"devDependencies": {
"@commitlint/cli": "^20.4.3",
"@commitlint/config-conventional": "^20.4.3",
"@rollup/plugin-strip": "^3.0.4",
"@types/node": "^20.10.0",
"@types/qs": "^6.15.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
@@ -47,6 +47,7 @@
"prettier": "^3.0.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
"vite-plugin-remove-console": "^2.2.0",
"vue-tsc": "^2.0.0"
},
"lint-staged": {
+4440
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -1,7 +1,10 @@
import { defineComponent } from 'vue';
import { ConfigProvider } from 'ant-design-vue';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import zhCN from 'ant-design-vue/locale/zh_CN';
import { RouterView } from 'vue-router';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
/**
* 根组件
@@ -13,6 +16,7 @@ export default defineComponent({
const theme = {
token: {
colorPrimary: '#1677ff',
borderRadius: 8,
},
};
+16
View File
@@ -0,0 +1,16 @@
import { get } from '@/utils/request';
import type { MenuNode, PermissionCode } from '@/types';
/**
* 获取当前用户的菜单树(后端下发)
*/
export function fetchMenuTree(): Promise<MenuNode[]> {
return get('/menu/tree');
}
/**
* 获取当前用户的权限编码列表
*/
export function fetchPermissions(): Promise<PermissionCode[]> {
return get('/permission/list');
}
+27
View File
@@ -0,0 +1,27 @@
import { get } from '@/utils/request';
import type { OssUploadTypeValue } from '@/utils/oss';
/** OSS 签名数据 */
export interface OssSignData {
host: string;
dir: string;
policy: string;
signature: string;
x_oss_credential: string;
x_oss_date: string;
security_token: string;
}
/**
* 获取 OSS 上传签名
* @param type 上传类型(参见 OssUploadType
*/
export async function fetchOssSign(type: OssUploadTypeValue): Promise<OssSignData> {
// 后端签名接口地址(待对接时调整)
const res: any = await get('/sys/oss/getUploadSign', { type });
const data = res?.data as OssSignData;
if (!data?.host) {
throw new Error(res?.msg || '获取上传凭证失败');
}
return data;
}
+58
View File
@@ -55,3 +55,61 @@ a {
::-webkit-scrollbar-track {
background: transparent;
}
// ===== 页面布局公共类 =====
// 页面容器:纵向 flex,占满高度;筛选区与表格区作为直接子元素
.page-container {
display: flex;
flex-direction: column;
height: 100%;
}
// 页面筛选区域:横向 flex,可换行
.page-filter {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: 16px;
row-gap: 12px;
flex-shrink: 0;
padding: 16px;
background-color: #fff;
border-radius: 10px;
}
// 筛选区域操作按钮组:横向 flex
.page-filter-actions {
display: flex;
align-items: center;
gap: 10px;
margin-left: 0;
}
// 表格显示区域:纵向 flex,占据剩余高度。
// overflow: hidden 防止子元素撑开容器,滚动由 Table 的 scroll.x/y 接管。
// 分页组件作为独立子元素置于 Table 下方,不占用 Table 的 scroll 空间。
.page-table {
display: flex;
flex-direction: column;
flex: 1;
background-color: #fff;
min-height: 0;
min-width: 0;
margin-top: 16px;
overflow: hidden;
border-radius: 10px;
}
.page-pagination {
flex-shrink: 0;
display: flex;
justify-content: flex-end;
padding: 14px;
}
// ===== antd 组件覆盖 =====
// Tag 默认 margin-right: 8px,会挤开表格列或卡片内间距,统一去掉
.ant-tag {
margin-right: 0;
}
+62
View File
@@ -0,0 +1,62 @@
* {
box-sizing: border-box;
}
html,
body,
#app {
height: 100%;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
font-size: 14px;
color: rgba(0, 0, 0, 0.88);
background-color: #f5f5f5;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
color: #1677ff;
text-decoration: none;
}
a:hover {
opacity: 0.85;
}
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
border-radius: 3px;
}
::-webkit-scrollbar-track {
background: transparent;
}
.page-container {
display: flex;
flex-direction: column;
height: 100%;
}
.page-filter {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: 16px;
row-gap: 12px;
flex-shrink: 0;
}
.page-filter-actions {
display: flex;
align-items: center;
gap: 10px;
margin-left: 0;
}
.page-table {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
margin-top: 16px;
}
+142
View File
@@ -0,0 +1,142 @@
import type { MenuNode } from '@/types';
/**
* ====== 兜底路由配置 ======
*
* 当后端菜单接口不可用时,使用此配置作为降级方案。
* 数据格式与后端 `/menu/tree` 接口返回完全一致,
* 因此可以直接通过 transformMenuToRoutes / transformMenuNode 复用同一套处理逻辑。
*
* ## 后端应返回的数组格式示例
*
* ```json
* [
* { "id": "dashboard", "name": "工作台", "path": "dashboard", "component": "dashboard", "icon": "DashboardOutlined" },
* {
* "id": "events", "name": "赛事管理", "path": "events", "icon": "TrophyOutlined",
* "children": [
* { "id": "events_list", "name": "赛事列表", "path": "events/list", "component": "events/list" },
* { "id": "events_orders", "name": "订单管理", "path": "events/orders", "component": "events/orders" }
* ]
* }
* ]
* ```
*
* ### 字段说明
* | 字段 | 类型 | 必填 | 说明 |
* |------|------|------|------|
* | id | number\|string | 是 | 唯一标识 |
* | name | string | 是 | 菜单名称/路由 name |
* | path | string | 是 | 路由相对路径(不带 / 前缀) |
* | component | string | 否 | 组件路径(映射 src/pages/ 下目录,如 "events/list" |
* | icon | string | 否 | antd 图标名(如 DashboardOutlined |
* | sort | number | 否 | 排序权重(越小越前) |
* | hideInMenu | boolean | 否 | 是否在菜单中隐藏 |
* | externalLink | string | 否 | 外链地址 |
* | activeMenu | string | 否 | 高亮菜单路径 |
* | disabled | boolean | 否 | 禁用标记(禁用后路由不注册、菜单不显示) |
* | children | MenuNode[] | 否 | 子路由 |
*
* ### 关于 routes → menuItems 的转换
* `menuStore.ts` 中的 `transformMenuNode()` 已完成此功能,
* 它将 MenuNode[] 递归转换为 antd Menu 组件所需的 MenuItemRaw[] 格式。
*/
export const FALLBACK_MENU_NODES: MenuNode[] = [
{
id: 'events',
name: '赛事管理',
path: 'events',
icon: 'TrophyOutlined',
children: [
{
id: 'events_list',
name: '赛事列表',
path: 'events/list',
component: 'events/list',
},
{
id: 'events_orders',
name: '订单管理',
path: 'events/orders',
component: 'events/orders',
},
{
id: 'events_users',
name: '用户列表',
path: 'events/users',
component: 'events/users',
},
{
id: 'events_banner',
name: 'Banner配置',
path: 'events/banner',
component: 'events/banner',
},
{
id: 'events_logs',
name: '赛事操作日志',
path: 'events/logs',
component: 'events/logs',
},
],
},
{
id: 'finance',
name: '账务管理',
path: 'finance',
icon: 'TransactionOutlined',
children: [
{
id: 'finance_withdraw',
name: '提现申请',
path: 'finance/withdraw',
component: 'finance/withdraw',
},
{
id: 'finance_wallet',
name: '用户钱包',
path: 'finance/wallet',
component: 'finance/wallet',
},
{
id: 'finance_payments',
name: '支付流水',
path: 'finance/payments',
component: 'finance/payments',
},
{
id: 'finance_reports',
name: '账务报表',
path: 'finance/reports',
component: 'finance/reports',
},
],
},
{
id: 'system',
name: '系统管理',
path: 'system',
icon: 'SettingOutlined',
children: [
{
id: 'system_users',
name: '用户管理',
path: 'system/users',
component: 'system/users',
},
{
id: 'system_roles',
name: '角色权限',
path: 'system/roles',
component: 'system/roles',
},
{
id: 'system_logs',
name: '操作日志',
path: 'system/logs',
component: 'system/logs',
},
],
},
];
+2
View File
@@ -7,4 +7,6 @@ export * from './useAuth';
export * from './useWebSocket';
export * from './useBasicLayout';
export * from './useBreadcrumb';
export * from './useThrottleFn';
export * from './useContainerSize';
export * from './useContext';
+30 -2
View File
@@ -1,6 +1,9 @@
// src/hooks/useAuth.ts
import { useState } from './useState';
import { watch } from 'vue';
import { useMenuStore } from '@/stores/menuStore';
import { usePermissionStore } from '@/stores/permissionStore';
import router from '@/router';
const TOKEN_KEY = 'MY_APP_AUTH_TOKEN';
@@ -15,17 +18,42 @@ function createAuth() {
}
});
const login = (newToken: string) => {
const isLoggedIn = () => !!token.value;
/**
* 登录:保存 token → 拉取菜单+权限 → 动态注册路由 → 跳转首页
*/
const login = async (newToken: string) => {
setToken(newToken);
const { loadMenu, homePath } = useMenuStore();
const { loadPermissions } = usePermissionStore();
// 并行拉取菜单和权限
await Promise.all([loadMenu(), loadPermissions()]);
// 跳转到首页(动态路由已注册完成)
router.push(homePath.value);
};
/**
* 退出:清除 token → 清除菜单+权限 → 清除动态路由 → 跳转登录页
*/
const logout = () => {
setToken(null);
const { clearMenu } = useMenuStore();
const { clearPermissions } = usePermissionStore();
clearMenu();
clearPermissions();
router.push('/login');
};
return {
token,
isLoggedIn: () => !!token.value,
isLoggedIn,
login,
logout,
};
+54
View File
@@ -0,0 +1,54 @@
import { ref, onMounted, onUnmounted, type Ref } from 'vue';
/**
* 监听容器尺寸变化,返回动态 width/height 给 Table 的 scroll 属性使用。
*
* 基于 ResizeObserver,窗口缩放 / 侧边栏收起展开 / 筛选区折叠 等任何导致
* 容器尺寸变化的行为都会自动触发重新计算,无需额外处理。
*
* 用法:
* ```ts
* const { containerRef, width, height } = useContainerSize();
* // <div ref={containerRef}>
* // <Table scroll={{ x: width.value, y: height.value }} />
* // </div>
* ```
*
* @param headerOffset 从容器高度中扣除的表头偏移量,默认 45
*/
export function useContainerSize(options?: { headerOffset?: number }) {
const { headerOffset = 45 } = options ?? {};
const containerRef = ref<HTMLElement | null>(null) as Ref<HTMLElement | null>;
const width = ref(0);
const height = ref(0);
let observer: ResizeObserver | null = null;
const updateSize = () => {
const el = containerRef.value;
if (!el) return;
width.value = el.clientWidth;
height.value = Math.max(el.clientHeight - headerOffset, 200);
};
onMounted(() => {
updateSize();
const el = containerRef.value;
if (!el) return;
observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const w = entry.contentRect.width;
const h = entry.contentRect.height;
if (w !== width.value) width.value = w;
if (h !== height.value) height.value = Math.max(h - headerOffset, 200);
}
});
observer.observe(el);
});
onUnmounted(() => observer?.disconnect());
return { containerRef, width, height };
}
+3 -6
View File
@@ -1,5 +1,5 @@
// src/hooks/useDebounce.ts
import { watch, onUnmounted } from 'vue';
import { watch, onUnmounted, Ref } from 'vue';
import { useState } from './useState';
export interface UseDebounceOptions {
@@ -8,14 +8,11 @@ export interface UseDebounceOptions {
maxWait?: number;
}
export function useDebounce<T>(
source: any, // Ref<T>
options: number | UseDebounceOptions = {},
) {
export function useDebounce<T>(source: Ref<T>, options: number | UseDebounceOptions = {}) {
const config = typeof options === 'number' ? { delay: options } : options;
const { delay = 300, immediate = false, maxWait } = config;
const [debouncedValue, setDebouncedValue] = useState<T>(source.value);
const [debouncedValue, setDebouncedValue] = useState<T>(source.value as T);
const [isPending, setIsPending] = useState(false);
let timer: any = null;
+46
View File
@@ -0,0 +1,46 @@
import { ref } from 'vue';
/**
* 节流函数封装
* @param fn 需要节流的函数
* @param delay 节流间隔时间(ms),默认 500
* @returns 返回节流后的函数,连续调用时只会在每个 delay 周期内执行一次
*/
export function useThrottleFn<T extends (...args: any[]) => any>(
fn: T,
delay: number = 500,
): T & { cancel: () => void } {
const lastTime = ref<number>(0);
let timer: any = null;
const throttled = function (this: any, ...args: any[]) {
const now = Date.now();
const remaining = delay - (now - lastTime.value);
if (remaining <= 0) {
// 冷却时间已过,立即执行
if (timer) {
clearTimeout(timer);
timer = null;
}
lastTime.value = now;
fn.apply(this, args);
} else if (!timer) {
// 冷却时间未过,延后执行
timer = setTimeout(() => {
lastTime.value = Date.now();
timer = null;
fn.apply(this, args);
}, remaining);
}
} as T & { cancel: () => void };
throttled.cancel = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
return throttled;
}
+13 -20
View File
@@ -1,9 +1,6 @@
.container {
min-height: 100vh;
}
.sider {
box-shadow: 2px 0 8px rgba(0, 0, 0, 0.08);
height: 100vh;
}
.logo {
@@ -12,8 +9,8 @@
align-items: center;
justify-content: center;
overflow: hidden;
color: #fff;
background: rgba(255, 255, 255, 0.08);
color: #1a1a1a;
background: #fff;
}
.logoText {
@@ -22,14 +19,6 @@
white-space: nowrap;
}
.header {
background: #fff;
padding: 0 16px;
display: flex;
align-items: center;
box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
.trigger {
font-size: 18px;
cursor: pointer;
@@ -45,13 +34,17 @@
.content {
margin: 16px;
padding: 24px;
background: #fff;
border-radius: 8px;
min-height: 280px;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.footer {
text-align: center;
color: rgba(0, 0, 0, 0.45);
.main {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
+46
View File
@@ -0,0 +1,46 @@
.container {
min-height: 100vh;
height: 100vh;
}
.logo {
height: 56px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
color: #1a1a1a;
background: #fff;
}
.logoText {
font-size: 16px;
font-weight: 600;
white-space: nowrap;
}
.trigger {
font-size: 18px;
cursor: pointer;
transition: color 0.3s;
padding: 0 12px;
display: inline-flex;
align-items: center;
}
.trigger:hover {
color: #1677ff;
}
.content {
margin: 16px;
padding: 24px;
background: #fff;
border-radius: 8px;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.main {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
+75 -13
View File
@@ -1,4 +1,5 @@
import { computed, defineComponent, ref } from 'vue';
import { computed, defineComponent, h, ref } from 'vue';
import type { CSSProperties } from 'vue';
import { useRouter, useRoute, RouterView } from 'vue-router';
import { Layout, Menu } from 'ant-design-vue';
import type { MenuProps } from 'ant-design-vue';
@@ -7,13 +8,75 @@ import {
InfoCircleOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
SettingOutlined,
TransactionOutlined,
TrophyOutlined,
} from '@ant-design/icons-vue';
import { useMenuStore } from '@/stores/menuStore';
import styles from './BasicLayout.module.less';
const { Header, Sider, Content, Footer } = Layout;
const headerStyle: CSSProperties = {
background: '#fff',
padding: '0 16px',
display: 'flex',
alignItems: 'center',
color: '#1a1a1a',
boxShadow: '0 1px 4px rgba(0, 21, 41, 0.08)',
};
const siderStyle: CSSProperties = {
background: '#fff',
boxShadow: '2px 0 8px rgba(0, 21, 41, 0.08)',
};
const footerStyle: CSSProperties = {
padding: '0 50px 16px 50px',
textAlign: 'center',
color: '#3a3a3a',
userSelect: 'none',
};
/**
* 基础布局:左侧导航 + 顶部栏 + 内容区 + 页脚
* 图标名 → 组件映射
* 后端下发的 icon 字符串在此映射为 antd icon 组件
* 扩展新图标只需在此添加一行
*/
const ICON_MAP: Record<string, any> = {
DashboardOutlined,
InfoCircleOutlined,
SettingOutlined,
TransactionOutlined,
TrophyOutlined,
};
/**
* 将 menuStore 中的 menuItems 转为 antd Menu 的 items 格式
* 递归处理 iconName → icon VNode
*/
function resolveMenuItems(items: any[]): MenuProps['items'] {
return items.map((item) => {
const resolved: any = {
key: item.key,
label: item.label,
};
// iconName 字符串转为 VNode
if (item.iconName && ICON_MAP[item.iconName]) {
resolved.icon = () => h(ICON_MAP[item.iconName]);
}
if (item.children?.length) {
resolved.children = resolveMenuItems(item.children);
}
return resolved;
});
}
/**
* 基础布局:左侧导航(后端菜单驱动) + 顶部栏 + 内容区 + 页脚
*/
export default defineComponent({
name: 'BasicLayout',
@@ -22,12 +85,11 @@ export default defineComponent({
const router = useRouter();
const collapsed = ref(false);
const { menuItems } = useMenuStore();
const selectedKeys = computed<string[]>(() => [route.path]);
const menuItems: MenuProps['items'] = [
{ key: '/dashboard', icon: () => <DashboardOutlined />, label: '工作台' },
{ key: '/about', icon: () => <InfoCircleOutlined />, label: '关于' },
];
const resolvedItems = computed(() => resolveMenuItems(menuItems.value));
const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
router.push(key as string);
@@ -39,21 +101,21 @@ export default defineComponent({
return () => (
<Layout class={styles.container}>
<Sider class={styles.sider} collapsed={collapsed.value} trigger={null} collapsible>
<Sider style={siderStyle} collapsed={collapsed.value} trigger={null} collapsible>
<div class={styles.logo}>
<span class={styles.logoText}>{collapsed.value ? 'CPMS' : 'CPMS 运营平台'}</span>
<span class={styles.logoText}>{collapsed.value ? '6羽' : '六羽赛事运营平台'}</span>
</div>
<Menu
theme="dark"
theme="light"
mode="inline"
selectedKeys={selectedKeys.value}
items={menuItems}
items={resolvedItems.value}
onClick={handleMenuClick}
/>
</Sider>
<Layout>
<Header class={styles.header}>
<Layout class={styles.main}>
<Header style={headerStyle}>
<span class={styles.trigger} onClick={toggleCollapsed}>
{collapsed.value ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</span>
@@ -63,7 +125,7 @@ export default defineComponent({
<RouterView />
</Content>
<Footer class={styles.footer}>CPMS ©{new Date().getFullYear()}</Footer>
<Footer style={footerStyle}> ©{new Date().getFullYear()}</Footer>
</Layout>
</Layout>
);
+1
View File
@@ -4,6 +4,7 @@ import 'ant-design-vue/dist/reset.css';
import App from './App';
import router from './router';
import './router/guard'; // 路由守卫:登录鉴权 + 动态菜单加载
import './assets/styles/index.less';
const app = createApp(App);
@@ -1,6 +1,6 @@
import { defineComponent } from 'vue';
import { Card } from 'ant-design-vue';
import styles from './About.module.less';
import styles from './index.module.less';
interface TechItem {
name: string;
@@ -1,6 +1,6 @@
import { defineComponent } from 'vue';
import { Card, Col, Row, Statistic } from 'ant-design-vue';
import styles from './Dashboard.module.less';
import styles from './index.module.less';
interface StatItem {
title: string;
@@ -0,0 +1,113 @@
.form {
:global {
.ant-form-item {
margin-bottom: 16px;
}
.ant-form-item-explain-error {
font-size: 12px;
}
}
}
/* ===== 上传 ===== */
.uploader {
position: relative;
}
.uploadCard {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 140px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
background-color: #fafafa;
cursor: pointer;
transition: border-color 0.2s;
gap: 4px;
&:hover {
border-color: #1677ff;
}
}
.uploadCardError {
border-color: #ff4d4f;
}
.uploadIcon {
font-size: 32px;
color: #999;
font-weight: 300;
line-height: 1;
}
.uploadHint {
color: #666;
font-size: 14px;
}
.uploadTip {
color: #999;
font-size: 12px;
text-align: center;
line-height: 1.6;
}
/* ===== 预览 ===== */
.previewWrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
border: 1px solid #e8e8e8;
border-radius: 6px;
background-color: #fff;
padding: 12px;
}
.previewImg {
width: 100%;
max-width: 420px;
max-height: 160px;
object-fit: contain;
border-radius: 4px;
}
.previewActions {
display: flex;
gap: 8px;
}
/* ===== 提示 ===== */
.tip {
padding: 8px 12px;
margin-bottom: 16px;
background-color: #f0f5ff;
border: 1px solid #d6e4ff;
border-radius: 4px;
color: #1677ff;
font-size: 13px;
}
/* ===== 时间行(双列)===== */
.timeRow {
display: flex;
gap: 16px;
.timeItem {
flex: 1;
}
}
/* ===== 底部按钮 ===== */
.footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
border-top: 1px solid #f0f0f0;
margin-top: 8px;
}
@@ -0,0 +1,479 @@
import { defineComponent, ref, reactive, watch } from 'vue';
import {
Modal,
Form,
Input,
Select,
DatePicker,
InputNumber,
Button,
message,
Spin,
} from 'ant-design-vue';
import { JUMP_TYPE_OPTIONS, EVENT_OPTIONS, REGION_OPTIONS } from '../model/useBannerModel';
import { uploadFilesOneByOne, OssUploadType } from '@/utils/oss';
import dayjs from 'dayjs';
import styles from './BannerFormModal.module.less';
/** 默认表单数据 */
const getDefaultForm = () => ({
title: '',
imageUrl: '',
imageStatus: 'empty' as 'empty' | 'uploading' | 'success' | 'error',
jumpType: 'event_detail' as 'event_detail' | 'miniprogram_page' | 'custom_link' | 'none',
relatedEventId: '',
pagePath: '',
customUrl: '',
region: 'home',
displayTimeRange: null as [string, string] | null,
sort: 1,
});
/** 表单字段最大长度限制 */
const TITLE_MAX = 50;
const PATH_MAX = 200;
const URL_MAX = 500;
interface BannerFormModalProps {
visible: boolean;
record: any;
submitting?: boolean;
onClose: () => void;
onSave: (formData: any) => void;
}
/**
* Banner 新增/编辑表单弹窗
*/
export default defineComponent({
name: 'BannerFormModal',
props: {
visible: { type: Boolean, default: false },
record: { type: Object, default: null },
submitting: { type: Boolean, default: false },
onClose: { type: Function, required: true },
onSave: { type: Function, required: true },
},
setup(props: BannerFormModalProps) {
const formRef = ref<any>();
const fileInputRef = ref<HTMLInputElement | null>(null);
const formData = reactive(getDefaultForm());
/** 根据 record 初始化表单 */
const initFormFromRecord = (record: any) => {
const fresh = getDefaultForm();
if (!record) {
Object.assign(formData, fresh);
return;
}
let pagePath = '';
let customUrl = '';
if (record.jumpType === 'miniprogram_page') {
pagePath = record.jumpUrl || '';
} else if (record.jumpType === 'custom_link') {
customUrl = record.jumpUrl || '';
}
Object.assign(formData, {
...fresh,
title: record.title || '',
imageUrl: record.imageUrl || '',
imageStatus: record.imageUrl ? ('success' as const) : ('empty' as const),
jumpType: record.jumpType || 'event_detail',
relatedEventId: record.relatedEventId || '',
pagePath,
customUrl,
region: record.region && record.region !== record.city ? record.region : 'home',
displayTimeRange:
record.displayStartTime && record.displayEndTime
? ([record.displayStartTime, record.displayEndTime] as [string, string])
: null,
sort: record.sort ?? 1,
});
};
/** 监听 visible 变化重置表单 */
watch(
() => props.visible,
(val) => {
if (val) {
initFormFromRecord(props.record);
setTimeout(() => formRef.value?.clearValidate(), 0);
}
},
{ immediate: true },
);
/** 监听 jumpType 变化时清理联动字段 */
watch(
() => formData.jumpType,
(newType) => {
if (newType !== 'event_detail') formData.relatedEventId = '';
if (newType !== 'miniprogram_page') formData.pagePath = '';
if (newType !== 'custom_link') formData.customUrl = '';
const fieldsToValidate: string[] = [];
if (newType === 'event_detail') fieldsToValidate.push('relatedEventId');
if (newType === 'miniprogram_page') fieldsToValidate.push('pagePath');
if (newType === 'custom_link') fieldsToValidate.push('customUrl');
if (fieldsToValidate.length) formRef.value?.clearValidate(fieldsToValidate);
},
);
/** 触发隐藏的文件选择器 */
const triggerFilePicker = () => {
if (formData.imageStatus === 'uploading') return;
fileInputRef.value?.click();
};
/** 处理文件选择 */
const handleFileChange = async (e: Event) => {
const target = e.target as HTMLInputElement;
const file = target.files?.[0];
// 重置 input 以便同一文件可再次选择
target.value = '';
if (!file) return;
if (!/^image\//.test(file.type)) {
message.error('请选择图片文件');
return;
}
const MAX_SIZE = 5 * 1024 * 1024;
if (file.size > MAX_SIZE) {
message.error('图片大小不能超过 5MB');
return;
}
// 本地预览
const localUrl = URL.createObjectURL(file);
formData.imageUrl = localUrl;
formData.imageStatus = 'uploading';
try {
await uploadFilesOneByOne([file], OssUploadType.Banner, {
onSuccess: (url) => {
URL.revokeObjectURL(localUrl);
formData.imageUrl = url;
formData.imageStatus = 'success';
message.success('图片上传成功');
},
onError: (err, idx) => {
console.error(`[Banner] 上传失败 (${idx}):`, err);
URL.revokeObjectURL(localUrl);
formData.imageUrl = '';
formData.imageStatus = 'error';
message.error('图片上传失败');
},
});
} catch (err: any) {
console.error('[Banner] 获取上传凭证失败:', err);
URL.revokeObjectURL(localUrl);
formData.imageUrl = '';
formData.imageStatus = 'error';
message.error(err?.message || '图片上传失败');
}
};
/** 删除已上传图片 */
const handleRemoveImage = () => {
if (formData.imageUrl && formData.imageUrl.startsWith('blob:')) {
URL.revokeObjectURL(formData.imageUrl);
}
formData.imageUrl = '';
formData.imageStatus = 'empty';
};
/** 提交表单 */
const handleSubmit = async () => {
try {
await formRef.value?.validate();
} catch {
return;
}
// 防御:上传中时禁止提交
if (formData.imageStatus === 'uploading') {
message.warning('图片仍在上传中,请稍候');
return;
}
// 构造提交数据:根据 jumpType 整理 jumpUrl
const payload: any = { ...formData };
if (payload.jumpType === 'event_detail') {
payload.jumpUrl = payload.relatedEventId;
} else if (payload.jumpType === 'miniprogram_page') {
payload.jumpUrl = payload.pagePath;
} else if (payload.jumpType === 'custom_link') {
payload.jumpUrl = payload.customUrl;
} else {
payload.jumpUrl = '';
}
payload.displayStartTime = payload.displayTimeRange?.[0] || '';
payload.displayEndTime = payload.displayTimeRange?.[1] || '';
props.onSave(payload);
};
return () => (
<Modal
title={props.record ? '编辑 Banner' : '新增 Banner'}
visible={props.visible}
onCancel={props.onClose}
width={640}
destroyOnClose
footer={null}
centered
>
<Form ref={formRef} layout="vertical" model={formData} class={styles.form} requiredMark>
{/* ===== Banner 标题 ===== */}
<Form.Item
label="Banner标题"
name="title"
rules={[
{ required: true, message: '请输入 Banner 标题' },
{ max: TITLE_MAX, message: `标题最多 ${TITLE_MAX} 个字符` },
]}
>
<Input
placeholder="请输入标题"
maxlength={TITLE_MAX}
allowClear
v-model:value={formData.title}
/>
</Form.Item>
{/* ===== 上传图片 ===== */}
<Form.Item
label="上传图片"
name="imageUrl"
rules={[
{
validator: async () => {
if (!formData.imageUrl || formData.imageUrl.startsWith('blob:')) {
return Promise.reject(new Error('请上传 Banner 图片'));
}
return Promise.resolve();
},
},
]}
>
<div class={styles.uploader}>
<input
ref={fileInputRef}
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={handleFileChange}
/>
{formData.imageStatus === 'empty' || formData.imageStatus === 'error' ? (
<div
class={`${styles.uploadCard} ${
formData.imageStatus === 'error' ? styles.uploadCardError : ''
}`}
onClick={triggerFilePicker}
>
<span class={styles.uploadIcon}>+</span>
<span class={styles.uploadHint}></span>
<span class={styles.uploadTip}>
1053*351
<br />
1
</span>
</div>
) : (
<div class={styles.previewWrapper}>
<Spin spinning={formData.imageStatus === 'uploading'} tip="上传中...">
<img class={styles.previewImg} src={formData.imageUrl} alt="banner preview" />
</Spin>
<div class={styles.previewActions}>
<Button size="small" onClick={triggerFilePicker}>
</Button>
<Button size="small" danger onClick={handleRemoveImage}>
</Button>
</div>
</div>
)}
</div>
</Form.Item>
{/* ===== 跳转类型 ===== */}
<Form.Item
label="跳转类型"
name="jumpType"
rules={[{ required: true, message: '请选择跳转类型' }]}
>
<Select
options={JUMP_TYPE_OPTIONS as any}
placeholder="请选择"
v-model:value={formData.jumpType}
/>
</Form.Item>
{/* ===== 联动字段:根据跳转类型动态展示 ===== */}
{formData.jumpType === 'event_detail' && (
<Form.Item
label="关联赛事"
name="relatedEventId"
rules={[{ required: true, message: '请选择关联赛事' }]}
>
<Select
options={EVENT_OPTIONS as any}
placeholder="不关联"
allowClear
v-model:value={formData.relatedEventId}
/>
</Form.Item>
)}
{formData.jumpType === 'miniprogram_page' && (
<Form.Item
label="页面路径"
name="pagePath"
rules={[
{ required: true, message: '请输入页面路径' },
{
pattern: /^\//,
message: '页面路径需以 / 开头',
},
{ max: PATH_MAX, message: `路径最多 ${PATH_MAX} 个字符` },
]}
>
<Input
placeholder="/pages/index/index"
maxlength={PATH_MAX}
allowClear
v-model:value={formData.pagePath}
/>
</Form.Item>
)}
{formData.jumpType === 'custom_link' && (
<Form.Item
label="自定义链接"
name="customUrl"
rules={[
{ required: true, message: '请输入自定义链接' },
{
pattern: /^https?:\/\//i,
message: '请输入以 http/https 开头的链接',
},
{ max: URL_MAX, message: `链接最多 ${URL_MAX} 个字符` },
]}
>
<Input
placeholder="https://xxx"
maxlength={URL_MAX}
allowClear
v-model:value={formData.customUrl}
/>
</Form.Item>
)}
{formData.jumpType === 'none' && (
<div class={styles.tip}>"无链接" Banner </div>
)}
{/* ===== 所属区域 ===== */}
<Form.Item
label="所属区域"
name="region"
rules={[{ required: true, message: '请选择所属区域' }]}
>
<Select
options={REGION_OPTIONS as any}
placeholder="首页"
v-model:value={formData.region}
/>
</Form.Item>
{/* ===== 展示时间(开始/结束) ===== */}
<div class={styles.timeRow}>
<Form.Item
label="开始时间"
name="displayStartTime"
class={styles.timeItem}
rules={[{ required: true, message: '请选择开始时间' }]}
>
<DatePicker
placeholder="年-月-日"
format="YYYY-MM-DD"
value={
formData.displayTimeRange?.[0] ? dayjs(formData.displayTimeRange[0]) : undefined
}
onUpdate:value={(v: any) => {
formData.displayTimeRange = [
v ? v.format('YYYY-MM-DD') : '',
formData.displayTimeRange?.[1] || '',
];
}}
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item
label="结束时间"
name="displayEndTime"
class={styles.timeItem}
rules={[
{ required: true, message: '请选择结束时间' },
{
validator: async () => {
const [s, e] = formData.displayTimeRange || [];
if (s && e && new Date(e) < new Date(s)) {
return Promise.reject(new Error('结束时间不能早于开始时间'));
}
return Promise.resolve();
},
},
]}
>
<DatePicker
placeholder="年-月-日"
format="YYYY-MM-DD"
value={
formData.displayTimeRange?.[1] ? dayjs(formData.displayTimeRange[1]) : undefined
}
onUpdate:value={(v: any) => {
formData.displayTimeRange = [
formData.displayTimeRange?.[0] || '',
v ? v.format('YYYY-MM-DD') : '',
];
}}
style={{ width: '100%' }}
/>
</Form.Item>
</div>
{/* ===== 排序 ===== */}
<Form.Item
label="排序"
name="sort"
rules={[
{ required: true, message: '请输入排序' },
{ type: 'number', min: 1, max: 999, message: '排序范围 1-999' },
]}
extra="数字越小越靠前"
>
<InputNumber
placeholder="数字越小越靠前"
min={1}
max={999}
precision={0}
style={{ width: '200px' }}
v-model:value={formData.sort}
/>
</Form.Item>
</Form>
{/* ===== 底部按钮 ===== */}
<div class={styles.footer}>
<Button onClick={props.onClose}></Button>
<Button type="primary" loading={props.submitting} onClick={handleSubmit}>
</Button>
</div>
</Modal>
);
},
});
+14
View File
@@ -0,0 +1,14 @@
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
+280
View File
@@ -0,0 +1,280 @@
import { defineComponent } from 'vue';
import {
Button,
Input,
Table,
Form,
Space,
Select,
Tooltip,
Pagination,
Modal,
Image,
} from 'ant-design-vue';
import { useBannerModel, BANNER_STATUS_OPTIONS } from './model/useBannerModel';
import { useContainerSize } from '@/hooks';
import BannerFormModal from './components/BannerFormModal';
import styles from './index.module.less';
/**
* bodyCell 渲染函数
*/
function renderBodyCell({
column,
text,
record,
renderJumpType,
renderStatus,
onEdit,
onToggleStatus,
onDelete,
}: {
column: any;
text: any;
record: any;
renderJumpType: (type: string) => any;
renderStatus: (status: string) => any;
onEdit: (record: any) => void;
onToggleStatus: (record: any) => void;
onDelete: (record: any) => void;
}) {
// 图片列:80 * 44
if (column.key === 'image') {
return (
<Image
src={record.imageUrl}
width={80}
height={44}
style={{ objectFit: 'cover', borderRadius: '4px' }}
fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAAAoCAMAAABQp/7DAAAANlBMVEUAAADg4ODd3d3c3Nzb29va2trZ2dnY2NjX19fW1tbV1dXU1NTT09PS0tLR0dHQ0NDPz8/Pz8/BwHhiAAAAEnRSTlMAHx8/P09fb2+Pn5+vv7/P39+GGqSCAAABMklEQVRIx+2T27KDIAxFSRQQRbz//7edUwyhBWc6+7AuH4QNEiAllDbKj5M/4CAbMR3lH7+9LZxk3wpP3lxHJ8lbFm3OMpysbsPehDdHcLIKHGjs1hKc3NaRyNoTOFnujhFZZxfF0MKsA6hB6w2Ck9UPYNOGA5ysXsLGlhPWNpysOkAHTt25PsHJeA3HqCzUDoaCLQYrvG3tO+z1BjyC8GII/TVHcWyit+BS8Q5fU3hA2F/F5awWeCgT9CzHwMjJjFAXiAOfGFjTQSBXGpgl9BlQDf84sIKGAleYwQcUoYSHErFgB8EDn5iu3gKCgwVZOFooAyfLUBK7B27M4PWAlVmsFESoFwtKeYTlBHF1LuhzF2K9Q+/nJ1DQBSxcoGOrL4I3s0DPASBvfFq8t9gPAAAAAElFTkSuQmCC"
/>
);
}
// 标题列:超长截断 + Tooltip
if (column.dataIndex === 'title') {
const maxLen = 18;
const raw = text || '';
const display = raw.length > maxLen ? raw.slice(0, maxLen) + '...' : raw;
return raw.length > maxLen ? (
<Tooltip title={raw}>
<span>{display}</span>
</Tooltip>
) : (
<span>{display}</span>
);
}
// 跳转类型列:彩色 Tag
if (column.dataIndex === 'jumpType') {
return renderJumpType(text);
}
// 关联赛事列:为空显示 "-"
if (column.dataIndex === 'relatedEvent') {
return <span>{text || '-'}</span>;
}
// 所属区域列:省 + 市 拼接
if (column.key === 'region') {
return (
<span>
{record.province}
{record.city}
</span>
);
}
// 展示时间列:日期时间段
if (column.key === 'displayTime') {
return (
<span>
{record.displayStartTime} {record.displayEndTime}
</span>
);
}
// 状态列:启用中(绿色) / 已禁用(灰色半透明)
if (column.dataIndex === 'status') {
return renderStatus(text);
}
// 操作列
if (column.key === 'action') {
const isEnabled = record.status === 'enabled';
return (
<Space>
<Button type="link" size="small" onClick={() => onEdit(record)}>
</Button>
<Button
type="link"
size="small"
style={isEnabled ? { color: '#faad14' } : { color: '#52c41a' }}
onClick={() => onToggleStatus(record)}
>
{isEnabled ? '禁用' : '启用'}
</Button>
<Button type="link" size="small" danger onClick={() => onDelete(record)}>
</Button>
</Space>
);
}
return;
}
/**
* Banner 配置
*/
export default defineComponent({
name: 'EventBanner',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
pagination,
modalVisible,
editingRecord,
formSubmitting,
renderJumpType,
renderStatus,
handleSearch,
handleReset,
handlePageChange,
handleAdd,
handleEdit,
handleCloseModal,
handleSave,
handleDelete,
handleToggleStatus,
} = useBannerModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
/** 删除二次确认 */
const confirmDelete = (record: any) => {
Modal.confirm({
title: '删除确认',
content: `确认要删除 "${record.title}" 吗?`,
okText: '确认',
cancelText: '取消',
okButtonProps: { danger: true },
onOk: () => handleDelete(record),
});
};
/** 启用/禁用二次确认 */
const confirmToggleStatus = (record: any) => {
const isEnabled = record.status === 'enabled';
const actionText = isEnabled ? '禁用' : '启用';
Modal.confirm({
title: `${actionText}确认`,
content: `确认要${actionText} "${record.title}" 吗?`,
okText: '确认',
cancelText: '取消',
onOk: () => handleToggleStatus(record),
});
};
/** 最终表格列:模型列 + 操作 */
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 220,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="标题" name="searchTitle">
<Input
placeholder="请输入 Banner 标题"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Select
value={filterForm.status}
options={BANNER_STATUS_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.status = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</Button>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleAdd}>
</Button>
</Space>
</Form.Item>
</Form>
</div>
{/* ===== 表格区 ===== */}
<div class="page-table">
<div ref={containerRef} class={styles.tableBody}>
<Table
columns={tableColumns}
dataSource={dataSource.value}
loading={loading.value}
scroll={{ x: 'max-content', y: height.value }}
pagination={false}
>
{{
bodyCell: (args: any) =>
renderBodyCell({
...args,
renderJumpType,
renderStatus,
onEdit: handleEdit,
onToggleStatus: confirmToggleStatus,
onDelete: confirmDelete,
}),
}}
</Table>
</div>
{/* 独立分页,右下方 */}
<div class="page-pagination">
<Pagination
current={pagination.value.current}
pageSize={pagination.value.pageSize}
total={pagination.value.total}
showSizeChanger
showTotal={(total: number) => `${total}`}
onChange={handlePageChange}
onShowSizeChange={handlePageChange}
/>
</div>
</div>
{/* ===== 新增/编辑弹窗 ===== */}
<BannerFormModal
visible={modalVisible.value}
record={editingRecord.value}
submitting={formSubmitting.value}
onClose={handleCloseModal}
onSave={handleSave}
/>
</div>
);
},
});
@@ -0,0 +1,323 @@
import { computed, reactive, toRef, Ref, h } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** Banner 状态选项(筛选) */
export const BANNER_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'enabled', label: '启用' },
{ value: 'disabled', label: '禁用' },
] as const;
/** 跳转类型选项(表单下拉) */
export const JUMP_TYPE_OPTIONS = [
{ value: 'event_detail', label: '赛事详情页' },
{ value: 'miniprogram_page', label: '小程序页面' },
{ value: 'custom_link', label: '自定义链接' },
{ value: 'none', label: '无链接' },
] as const;
/** 跳转类型映射(用于表格 Tag 渲染) */
const JUMP_TYPE_MAP: Record<string, { label: string; color: string }> = {
event_detail: { label: '赛事详情页', color: 'blue' },
miniprogram_page: { label: '小程序页面', color: 'cyan' },
custom_link: { label: '自定义链接', color: 'purple' },
none: { label: '无链接', color: 'default' },
};
/** Banner 状态映射 */
const STATUS_MAP: Record<string, { label: string; color: string }> = {
enabled: { label: '启用中', color: 'green' },
disabled: { label: '已禁用', color: 'default' },
};
/** 关联赛事选项(mock */
export const EVENT_OPTIONS = [
{ value: '', label: '不关联' },
{ value: 'EV20260701001', label: '2026全国青少年羽毛球锦标赛暨体育文化交流大会' },
{ value: 'EV20260701002', label: '国际马拉松城市联赛' },
{ value: 'EV20260701003', label: '全民健身运动会' },
{ value: 'EV20260701004', label: '上海国际马拉松公开赛' },
{ value: 'EV20260701005', label: '北京城市定向越野挑战赛' },
];
/** 所属区域选项(mock */
export const REGION_OPTIONS = [
{ value: 'home', label: '首页' },
{ value: 'guangdong_shenzhen', label: '广东省深圳市' },
{ value: 'zhejiang_hangzhou', label: '浙江省杭州市' },
{ value: 'beijing', label: '北京市' },
{ value: 'shanghai', label: '上海市' },
];
// ============================================================
// 假数据(表格)
// ============================================================
const MOCK_DATA = Array.from({ length: 12 }, (_, i) => {
const jumpType = (['event_detail', 'miniprogram_page', 'custom_link', 'none'] as const)[i % 4];
const provinces = ['广东省', '浙江省', '北京市', '上海市'];
const cities = ['深圳市', '杭州市', '北京市', '上海市'];
return {
key: `${i + 1}`,
id: `BANNER${String(i + 1).padStart(4, '0')}`,
sort: i + 1,
imageUrl: `https://picsum.photos/seed/banner${i + 1}/80/44`,
title:
i % 4 === 0
? '2026全国青少年羽毛球锦标赛火热报名中'
: i % 4 === 1
? '马拉松城市联赛限时优惠'
: i % 4 === 2
? '健身运动会专属福利'
: '平台品牌宣传活动',
jumpType,
jumpUrl:
jumpType === 'custom_link'
? 'https://example.com/activity'
: jumpType === 'miniprogram_page'
? '/pages/activity/detail'
: '',
relatedEventId:
jumpType === 'event_detail'
? (['EV20260701001', 'EV20260701002', 'EV20260701003'] as const)[i % 3]
: '',
relatedEvent:
jumpType === 'event_detail'
? (() => {
const map: Record<string, string> = {
EV20260701001: '2026全国青少年羽毛球锦标赛暨体育文化交流大会',
EV20260701002: '国际马拉松城市联赛',
EV20260701003: '全民健身运动会',
};
return map[(['EV20260701001', 'EV20260701002', 'EV20260701003'] as const)[i % 3]] || '';
})()
: '',
region: provinces[i % 4],
city: cities[i % 4],
displayStartTime: '2026-08-01 00:00',
displayEndTime: '2026-08-31 23:59',
createTime: `2026-07-${String((i % 28) + 1).padStart(2, '0')} ${String((i * 2 + 8) % 24).padStart(2, '0')}:${String((i * 7) % 60).padStart(2, '0')}`,
status: (i % 4 === 0 ? 'disabled' : 'enabled') as 'enabled' | 'disabled',
};
});
// ============================================================
// Model
// ============================================================
/**
* Banner 配置页数据模型
*/
export function useBannerModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
searchTitle: '',
status: '' as '' | 'enabled' | 'disabled',
});
// 防抖 300ms
const { debouncedValue: debouncedTitle } = useDebounce(
toRef(filterForm, 'searchTitle') as Ref<string>,
{ delay: 300 },
);
// ===== 表格状态 =====
const [loading, setLoading] = useState<boolean>(false);
const [dataSource, setDataSource] = useState<any[]>(MOCK_DATA);
const [pagination, setPagination] = useState({
current: 1,
pageSize: 10,
total: MOCK_DATA.length,
});
// ===== 弹窗状态 =====
const [modalVisible, setModalVisible] = useState<boolean>(false);
const [editingRecord, setEditingRecord] = useState<any>(null);
// ===== 提交态(用于表单弹窗的确认按钮 loading)=====
const [formSubmitting, setFormSubmitting] = useState<boolean>(false);
// ===== 表格列配置(纯数据列,复杂渲染在页面 bodyCell 中处理)=====
const columns = [
{ title: '排序', dataIndex: 'sort', key: 'sort', width: 70, align: 'center' as const },
{ title: '图片', key: 'image', width: 100, align: 'center' as const },
{ title: '标题', dataIndex: 'title', key: 'title', width: 220 },
{
title: '跳转类型',
dataIndex: 'jumpType',
key: 'jumpType',
width: 120,
align: 'center' as const,
},
{ title: '关联赛事', dataIndex: 'relatedEvent', key: 'relatedEvent', width: 200 },
{ title: '所属区域', key: 'region', width: 140 },
{ title: '展示时间', key: 'displayTime', width: 260 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 160 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 100, align: 'center' as const },
];
// ===== 计算属性 =====
const hasFilter = computed(() => {
return debouncedTitle.value.trim() !== '' || filterForm.status !== '';
});
const isEdit = computed(() => editingRecord.value !== null);
// ===== 方法 =====
/** 查询(节流 500ms */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
title: debouncedTitle.value,
status: filterForm.status,
});
// TODO: 替换为真实 API 调用
setDataSource(MOCK_DATA);
setPagination({ ...pagination.value, total: MOCK_DATA.length });
message.success('查询成功');
} catch (error: any) {
message.error(error.msg || '查询失败');
} finally {
setLoading(false);
}
}, 500);
/** 重置(节流 500ms */
const handleReset = useThrottleFn(() => {
filterForm.searchTitle = '';
filterForm.status = '';
setPagination({ current: 1, pageSize: 10, total: MOCK_DATA.length });
setDataSource(MOCK_DATA);
}, 500);
const handlePageChange = (page: number, pageSize: number) => {
setPagination({ ...pagination.value, current: page, pageSize });
handleSearch();
};
/** 打开新增弹窗 */
const handleAdd = () => {
setEditingRecord(null);
setModalVisible(true);
};
/** 打开编辑弹窗 */
const handleEdit = (record: any) => {
setEditingRecord(record);
setModalVisible(true);
};
/** 关闭弹窗 */
const handleCloseModal = () => {
setModalVisible(false);
setEditingRecord(null);
};
/** 提交表单(新增/编辑) */
const handleSave = useThrottleFn(async (formPayload: any) => {
if (formSubmitting.value) return;
setFormSubmitting(true);
try {
const payload = {
...formPayload,
displayStartTime: formPayload.displayTimeRange?.[0] || '',
displayEndTime: formPayload.displayTimeRange?.[1] || '',
};
console.log(isEdit.value ? '编辑 Banner' : '新增 Banner', payload);
// TODO: 替换为真实 API 调用
message.success(isEdit.value ? '编辑成功' : '新增成功');
handleCloseModal();
handleSearch();
} catch (error: any) {
message.error(error.msg || '操作失败');
} finally {
setFormSubmitting(false);
}
}, 500);
/** 删除(节流 500ms */
const handleDelete = useThrottleFn(async (record: any) => {
setLoading(true);
try {
console.log('删除 Banner:', record.id);
// TODO: 替换为真实 API 调用
message.success('删除成功');
handleSearch();
} catch (error: any) {
message.error(error.msg || '删除失败');
} finally {
setLoading(false);
}
}, 500);
/** 启用/禁用切换(节流 500ms */
const handleToggleStatus = useThrottleFn(async (record: any) => {
setLoading(true);
try {
const newStatus = record.status === 'enabled' ? 'disabled' : 'enabled';
const actionText = newStatus === 'enabled' ? '启用' : '禁用';
console.log(`${actionText} Banner:`, record.id);
// TODO: 替换为真实 API 调用
// 更新本地数据
setDataSource(
dataSource.value.map((item: any) =>
item.key === record.key ? { ...item, status: newStatus } : item,
),
);
message.success(`${actionText}成功`);
} catch (error: any) {
message.error(error.msg || '操作失败');
} finally {
setLoading(false);
}
}, 500);
// ===== 供页面 bodyCell 使用的渲染工具 =====
const renderJumpType = (type: string) => {
const info = JUMP_TYPE_MAP[type] || { label: type || '-', color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
};
const renderStatus = (status: string) => {
const info = STATUS_MAP[status] || { label: status || '-', color: 'default' };
const tagProps: any = { color: info.color };
// 已禁用状态添加半透明样式
if (status === 'disabled') {
tagProps.style = { opacity: 0.5 };
}
return h(Tag, tagProps, () => info.label);
};
return {
filterForm,
loading,
dataSource,
columns,
pagination,
hasFilter,
modalVisible,
setModalVisible,
editingRecord,
isEdit,
formSubmitting,
renderJumpType,
renderStatus,
handleSearch,
handleReset,
handlePageChange,
handleAdd,
handleEdit,
handleCloseModal,
handleSave,
handleDelete,
handleToggleStatus,
};
}
@@ -0,0 +1,67 @@
.section {
margin-bottom: 24px;
}
.section:last-child {
margin-bottom: 0;
}
.sectionTitle {
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 12px;
padding-left: 8px;
border-left: 3px solid #1677ff;
}
.textBlock {
font-size: 13px;
line-height: 1.8;
color: rgba(0, 0, 0, 0.65);
white-space: pre-wrap;
background: #fafafa;
padding: 12px 16px;
border-radius: 4px;
border: 1px solid #f0f0f0;
}
// Descriptions 列宽稍微压缩一些,避免单标签被挤
.desc :global(.ant-descriptions-item-label) {
width: 110px;
color: rgba(0, 0, 0, 0.65);
}
// 组别信息下的子表格
.group {
margin-bottom: 16px;
}
.group:last-child {
margin-bottom: 0;
}
.groupTitle {
font-size: 13px;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 8px;
font-weight: 500;
}
.paginationRow {
display: flex;
justify-content: flex-end;
margin-top: 8px;
}
// 分组信息列表
.divisionList {
display: flex;
flex-direction: column;
gap: 6px;
}
.divisionItem {
font-size: 13px;
color: rgba(0, 0, 0, 0.65);
}
@@ -0,0 +1,208 @@
import { defineComponent } from 'vue';
import { Modal, Descriptions, Image, Table, Pagination, Space } from 'ant-design-vue';
import styles from './EventDetailModal.module.less';
interface EventDetailModalProps {
visible: boolean;
record: any;
onClose: () => void;
}
// ===== Mock 数据 =====
const MOCK_DETAIL = {
name: '第二届全国地学羽毛球邀请赛',
eventTime: '2026.05.26 08:00 ~ 2026.05.31 22:00',
descr:
'赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍赛事介绍。',
registerTime: '2026.05.24 08:00 ~ 2026.05.26 22:00',
cancelDeadline: '2026.05.25 22:00',
region: '北京市 北京市 东城区',
address: '李宁体育馆',
venueNo: '李宁体育馆',
publicEvent: '在首页展示赛事',
needIdCard: '无需提供',
needIdCardImage: '无需提供',
createTime: '2026.05.26 08:00',
creator: '张三',
status: '报名中',
enrolledCount: 100,
cancelledCount: 1,
maxCount: 1000,
crossedCount: 50,
completedCount: 50,
cover: 'https://picsum.photos/seed/eventcover/600/300',
announcement:
'赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告赛事公告。',
};
// 假组别数据
const MOCK_GROUPS = [
{
key: 'group1',
title: '组别1:男子单打(单打)',
players: [
{
key: '1',
name: '张三',
gender: '男',
phone: '12345678995',
idNo: 'xxxxxxxxxxxxxxxx',
idImg: '',
},
{ key: '2', name: '李四', gender: '男', phone: '', idNo: '', idImg: '' },
],
},
{
key: 'group2',
title: '组别2:女子双打(双打)',
players: [
{
key: '1',
name: '张三',
gender: '女',
phone: '12345678995',
idNo: 'xxxxxxxxxxxxxxxx',
idImg: '',
},
{ key: '2', name: '李四', gender: '女', phone: '', idNo: '', idImg: '' },
],
},
];
// 假分组数据
const MOCK_DIVISIONS = ['分组1:男子小组1(循环赛)', '分组2:女子小组1(淘汰赛)'];
const PLAYER_COLUMNS = [
{ title: '选手', dataIndex: 'name', key: 'name', width: 100 },
{ title: '性别', dataIndex: 'gender', key: 'gender', width: 80 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 150 },
{ title: '证件号', dataIndex: 'idNo', key: 'idNo', width: 180 },
{
title: '证件图片',
dataIndex: 'idImg',
key: 'idImg',
width: 180,
customRender: () => (
<Space>
<Image width={48} height={32} src="https://picsum.photos/seed/idimg1/96/64" />
<Image width={48} height={32} src="https://picsum.photos/seed/idimg2/96/64" />
</Space>
),
},
];
export default defineComponent({
name: 'EventDetailModal',
props: {
visible: { type: Boolean, default: false },
record: { type: Object, default: () => ({}) },
onClose: { type: Function, required: true },
},
setup(props: EventDetailModalProps) {
const detail = MOCK_DETAIL;
return () => (
<Modal
visible={props.visible}
title="查看详情"
width={900}
onCancel={props.onClose}
footer={null}
centered
destroyOnClose
>
{/* ===== 基础信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<Descriptions size="small" bordered column={3} class={styles.desc}>
{/* 第一行:赛事名称(1 列) + 赛事时间(占 2 列) */}
<Descriptions.Item label="赛事名称">{detail.name}</Descriptions.Item>
<Descriptions.Item label="赛事时间" span={2}>
{detail.eventTime}
</Descriptions.Item>
{/* 第二行:赛事说明(占 3 列,独占整行) */}
<Descriptions.Item label="赛事说明" span={3}>
{detail.descr}
</Descriptions.Item>
<Descriptions.Item label="报名起止时间">{detail.registerTime}</Descriptions.Item>
<Descriptions.Item label="取消报名截止时间" span={2}>
{detail.cancelDeadline}
</Descriptions.Item>
<Descriptions.Item label="省市区">{detail.region}</Descriptions.Item>
<Descriptions.Item label="地点">{detail.address}</Descriptions.Item>
<Descriptions.Item label="场地编号">{detail.venueNo}</Descriptions.Item>
<Descriptions.Item label="公开活动">{detail.publicEvent}</Descriptions.Item>
<Descriptions.Item label="证件号">{detail.needIdCard}</Descriptions.Item>
<Descriptions.Item label="证件图片">{detail.needIdCardImage}</Descriptions.Item>
<Descriptions.Item label="创建时间">{detail.createTime}</Descriptions.Item>
<Descriptions.Item label="创建人">{detail.creator}</Descriptions.Item>
<Descriptions.Item label="状态">{detail.status}</Descriptions.Item>
<Descriptions.Item label="报名人数">{detail.enrolledCount}</Descriptions.Item>
<Descriptions.Item label="取消报名人数" span={1}>
{detail.cancelledCount}
</Descriptions.Item>
<Descriptions.Item label="最大人数">{detail.maxCount}</Descriptions.Item>
<Descriptions.Item label="对岸数量">{detail.crossedCount}</Descriptions.Item>
<Descriptions.Item label="已完成对岸数量">{detail.completedCount}</Descriptions.Item>
</Descriptions>
</div>
{/* ===== 封面 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<Image src={detail.cover} />
</div>
{/* ===== 赛事公告 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<div class={styles.textBlock}>{detail.announcement}</div>
</div>
{/* ===== 组别信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
{MOCK_GROUPS.map((group) => (
<div key={group.key} class={styles.group}>
<div class={styles.groupTitle}>{group.title}</div>
<Table
columns={PLAYER_COLUMNS}
dataSource={group.players}
size="small"
pagination={false}
bordered
/>
<div class={styles.paginationRow}>
<Pagination
current={1}
pageSize={10}
total={5}
showSizeChanger={false}
size="small"
/>
</div>
</div>
))}
</div>
{/* ===== 分组信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<div class={styles.divisionList}>
{MOCK_DIVISIONS.map((d) => (
<div key={d} class={styles.divisionItem}>
{d}
</div>
))}
</div>
</div>
</Modal>
);
},
});
@@ -0,0 +1,51 @@
.section {
margin-bottom: 20px;
}
.section:last-child {
margin-bottom: 0;
}
.sectionTitle {
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 10px;
padding-left: 8px;
border-left: 3px solid #1677ff;
}
.textBlock {
font-size: 13px;
line-height: 1.5;
color: rgba(0, 0, 0, 0.65);
white-space: pre-wrap;
background: #fafafa;
padding: 12px 16px;
border-radius: 4px;
border: 1px solid #f0f0f0;
}
.imageGrid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
.imageCell {
width: 100%;
aspect-ratio: 3 / 2;
background: #f5f5f5;
border-radius: 4px;
overflow: hidden;
border: 1px solid #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
}
.imageCell :global(.ant-image) {
width: 100%;
height: 100%;
object-fit: cover;
}
@@ -0,0 +1,45 @@
.section {
margin-bottom: 20px;
}
.section:last-child {
margin-bottom: 0;
}
.sectionTitle {
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 10px;
padding-left: 8px;
border-left: 3px solid #1677ff;
}
.textBlock {
font-size: 13px;
line-height: 1.5;
color: rgba(0, 0, 0, 0.65);
white-space: pre-wrap;
background: #fafafa;
padding: 12px 16px;
border-radius: 4px;
border: 1px solid #f0f0f0;
}
.imageGrid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
.imageCell {
width: 100%;
aspect-ratio: 3 / 2;
background: #f5f5f5;
border-radius: 4px;
overflow: hidden;
border: 1px solid #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
}
.imageCell :global(.ant-image) {
width: 100%;
height: 100%;
object-fit: cover;
}
@@ -0,0 +1,66 @@
import { defineComponent } from 'vue';
import { Modal, Image } from 'ant-design-vue';
import styles from './EventRegulationModal.module.less';
interface EventRegulationModalProps {
visible: boolean;
onClose: () => void;
}
/** 规程文字 */
const REGULATION_TEXT = [
'一、赛事目的:推动羽毛球运动发展,提高运动员技术水平,增进体育文化交流。',
'二、参赛资格:凡身体健康、年龄符合要求的羽毛球爱好者均可报名参加。',
'三、比赛规则:采用中国羽毛球协会审定的最新《羽毛球竞赛规则》。',
'四、赛制安排:比赛分小组赛和淘汰赛两个阶段,小组赛采用单循环,淘汰赛采用单败淘汰。',
'五、器材要求:参赛运动员自备球拍,比赛用球由组委会统一提供。',
'六、裁判设置:每场比赛设主裁判1名、副裁判2名,确保比赛公平公正。',
].join('\n\n');
/** 规程图片(mock8 张示例图,4 列 grid */
const REGULATION_IMAGES = Array.from({ length: 8 }, (_, i) => ({
id: i + 1,
src: `https://picsum.photos/seed/reg${i + 1}/300/200`,
alt: `规程图片 ${i + 1}`,
}));
export default defineComponent({
name: 'EventRegulationModal',
props: {
visible: { type: Boolean, default: false },
onClose: { type: Function, required: true },
},
setup(props: EventRegulationModalProps) {
return () => (
<Modal
visible={props.visible}
title="赛事规程"
width={760}
onCancel={props.onClose}
footer={null}
centered
destroyOnClose
>
{/* 规程文字 */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<div class={styles.textBlock}>{REGULATION_TEXT}</div>
</div>
{/* 规程图片:4 列 grid,点击可浏览 */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<Image.PreviewGroup>
<div class={styles.imageGrid}>
{REGULATION_IMAGES.map((img) => (
<div key={img.id} class={styles.imageCell}>
<Image src={img.src} />
</div>
))}
</div>
</Image.PreviewGroup>
</div>
</Modal>
);
},
});
+18
View File
@@ -0,0 +1,18 @@
/**
* 表格 body 容器:占满 flex 剩余空间,并确保 antd 嵌套 div 逐层传递 height: 100%
* 使得 Table scroll.y = 'calc(100% - 55px)' 中的 100% 能正确解析。
*/
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
+300
View File
@@ -0,0 +1,300 @@
import { defineComponent } from 'vue';
import {
Button,
Input,
Table,
Form,
Space,
Select,
DatePicker,
Cascader,
Tooltip,
Pagination,
Modal,
} from 'ant-design-vue';
import {
useEventListModel,
EVENT_STATUS_OPTIONS,
PUBLIC_EVENT_OPTIONS,
ID_CARD_OPTIONS,
ID_CARD_IMAGE_OPTIONS,
} from './model/useEventListModel';
import { regionOptions } from '@/utils/areaData';
import { useContainerSize, useState } from '@/hooks';
import EventRegulationModal from './components/EventRegulationModal';
import EventDetailModal from './components/EventDetailModal';
import styles from './index.module.less';
const { RangePicker } = DatePicker;
/**
* bodyCell 渲染函数
*/
function renderBodyCell({
column,
text,
record,
onView,
onRemove,
onViewRegulation,
}: {
column: any;
text: any;
record: any;
onView: (record: any) => void;
onRemove: (record: any) => void;
onViewRegulation: (record: any) => void;
}) {
if (column.dataIndex === 'eventName') {
const maxLen = 15;
const raw = text || '';
const display = raw.length > maxLen ? raw.slice(0, maxLen) + '...' : raw;
return raw.length > maxLen ? (
<Tooltip title={raw}>
<span>{display}</span>
</Tooltip>
) : (
<span>{display}</span>
);
}
if (column.key === 'regulation') {
return (
<a style={{ cursor: 'pointer' }} onClick={() => onViewRegulation(record)}>
</a>
);
}
if (column.key === 'action') {
const isRemoved = record.status === 'removed';
return (
<Space>
<Button type="link" size="small" onClick={() => onView(record)}>
</Button>
<Button
type="link"
size="small"
danger={!isRemoved}
style={isRemoved ? { color: '#52c41a' } : {}}
onClick={() => onRemove(record)}
>
{isRemoved ? '上架' : '下架'}
</Button>
</Space>
);
}
return;
}
/**
* 赛事列表
*/
export default defineComponent({
name: 'EventList',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
pagination,
handleSearch,
handleReset,
handlePageChange,
} = useEventListModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
// 弹窗状态
const [regulationModalVisible, setRegulationModalVisible] = useState<boolean>(false);
const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
const [currentRecord, setCurrentRecord] = useState<any>({});
const handleView = (record: any) => {
console.log('查看赛事:', record.eventId);
setCurrentRecord(record);
setDetailModalVisible(true);
};
const handleRemove = (record: any) => {
const isRemoved = record.status === 'removed';
const actionText = isRemoved ? '上架' : '下架';
Modal.confirm({
title: `${actionText}确认`,
content: `确认${actionText}"${record.eventName}"该赛事吗,下架后用户将无法搜索和报名该赛事,已有报名和订单不受影响。`,
okText: '确认',
cancelText: '取消',
onOk: () => {
console.log(`${actionText}赛事:`, record.eventId);
// TODO: 替换为真实 API 调用
},
});
};
const handleViewRegulation = (record: any) => {
console.log('查看规程:', record.eventId);
setCurrentRecord(record);
setRegulationModalVisible(true);
};
/** 最终表格列:模型列 + 赛事规程 + 操作 */
const tableColumns = [
...columns,
{ title: '赛事规程', key: 'regulation', width: 100, align: 'center' as const },
{
title: '操作',
key: 'action',
width: 160,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="创建时间" name="createTimeRange">
<RangePicker
value={filterForm.createTimeRange as any}
style={{ width: '260px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.createTimeRange = val)}
/>
</Form.Item>
<Form.Item label="赛事时间" name="eventTimeRange">
<RangePicker
value={filterForm.eventTimeRange as any}
style={{ width: '260px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.eventTimeRange = val)}
/>
</Form.Item>
<Form.Item label="赛事名称" name="searchName">
<Input
placeholder="请输入赛事名称"
style={{ width: '180px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="创建人" name="searchCreator">
<Input
placeholder="请输入创建人"
style={{ width: '150px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Select
value={filterForm.status}
options={EVENT_STATUS_OPTIONS as any}
style={{ width: '110px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.status = val || '')}
/>
</Form.Item>
<Form.Item label="公开活动" name="publicEvent">
<Select
value={filterForm.publicEvent}
options={PUBLIC_EVENT_OPTIONS as any}
style={{ width: '170px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.publicEvent = val || '')}
/>
</Form.Item>
<Form.Item label="证件号" name="needIdCard">
<Select
value={filterForm.needIdCard}
options={ID_CARD_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.needIdCard = val || '')}
/>
</Form.Item>
<Form.Item label="证件图片" name="needIdCardImage">
<Select
value={filterForm.needIdCardImage}
options={ID_CARD_IMAGE_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.needIdCardImage = val || '')}
/>
</Form.Item>
<Form.Item label="省市区" name="region">
<Cascader
value={filterForm.region as any}
options={regionOptions}
style={{ width: '220px' }}
placeholder="请选择省市区"
allowClear
changeOnSelect
onUpdate:value={(val: any) => (filterForm.region = val || [])}
/>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</Button>
<Button onClick={handleReset}></Button>
</Space>
</Form.Item>
</Form>
</div>
{/* ===== 表格区 ===== */}
<div class="page-table">
<div ref={containerRef} class={styles.tableBody}>
<Table
columns={tableColumns}
dataSource={dataSource.value}
loading={loading.value}
scroll={{ x: 'max-content', y: height.value }}
pagination={false}
>
{{
bodyCell: (args: any) =>
renderBodyCell({
...args,
onView: handleView,
onRemove: handleRemove,
onViewRegulation: handleViewRegulation,
}),
}}
</Table>
</div>
{/* 独立分页,右下方 */}
<div class="page-pagination">
<Pagination
current={pagination.value.current}
pageSize={pagination.value.pageSize}
total={pagination.value.total}
showSizeChanger
showTotal={(total: number) => `${total}`}
onChange={handlePageChange}
onShowSizeChange={handlePageChange}
/>
</div>
</div>
{/* ===== 弹窗区 ===== */}
<EventRegulationModal
visible={regulationModalVisible.value}
onClose={() => setRegulationModalVisible(false)}
/>
<EventDetailModal
visible={detailModalVisible.value}
record={currentRecord.value}
onClose={() => setDetailModalVisible(false)}
/>
</div>
);
},
});
@@ -0,0 +1,255 @@
import { computed, reactive, toRef, Ref, h } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 赛事状态选项 */
export const EVENT_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'enrolling', label: '报名中' },
{ value: 'ongoing', label: '进行中' },
{ value: 'finished', label: '已结束' },
{ value: 'deleted', label: '已删除' },
{ value: 'removed', label: '已下架' },
] as const;
/** 公开活动选项 */
export const PUBLIC_EVENT_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'show', label: '在首页展示赛事' },
{ value: 'hide', label: '不在首页展示赛事' },
] as const;
/** 证件号选项 */
export const ID_CARD_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'no', label: '无需提供' },
{ value: 'yes', label: '需提供' },
] as const;
/** 证件图片选项 */
export const ID_CARD_IMAGE_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'no', label: '无需提供' },
{ value: 'yes', label: '需提供' },
] as const;
// ============================================================
// 假数据
// ============================================================
const MOCK_DATA = Array.from({ length: 12 }, (_, i) => ({
key: `${i + 1}`,
eventId: `EV2026070100${String(i + 1).padStart(2, '0')}`,
eventName:
i % 3 === 0
? '2026全国青少年羽毛球锦标赛暨体育文化交流大会'
: i % 3 === 1
? '国际马拉松城市联赛'
: '全民健身运动会',
eventTimeStart: '2026-08-12 09:00',
eventTimeEnd: '2026-08-15 18:00',
province: '广东省',
city: '深圳市',
district: '南山区',
address: '深圳湾体育中心',
needIdCard: i % 2 === 0 ? '是' : '否',
needIdCardImage: i % 2 === 0 ? '是' : '否',
creatorNickname: ['张运营', '李管理', '王策划', '赵赛事'][i % 4],
creatorPhone: ['13800138001', '13900139002', '13700137003', '13600136004'][i % 4],
createTime: '2026-07-01 14:30:00',
status: (['enrolling', 'ongoing', 'finished', 'deleted', 'removed'] as const)[i % 5],
enrolledCount: [128, 256, 512, 64, 0][i % 5],
cancelledCount: [5, 12, 8, 3, 0][i % 5],
}));
/** 状态标签映射 */
const STATUS_MAP: Record<string, { label: string; color: string }> = {
enrolling: { label: '报名中', color: 'blue' },
ongoing: { label: '进行中', color: 'green' },
finished: { label: '已结束', color: 'default' },
deleted: { label: '已删除', color: 'red' },
removed: { label: '已下架', color: 'orange' },
};
// ============================================================
// Model
// ============================================================
/**
* 赛事列表页数据模型
*/
export function useEventListModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
createTimeRange: null as [string, string] | null,
eventTimeRange: null as [string, string] | null,
searchName: '',
searchCreator: '',
status: '',
region: [] as string[],
publicEvent: '',
needIdCard: '',
needIdCardImage: '',
});
// 可搜索字段防抖
const { debouncedValue: debouncedName } = useDebounce(
toRef(filterForm, 'searchName') as Ref<string>,
{ delay: 300 },
);
const { debouncedValue: debouncedCreator } = useDebounce(
toRef(filterForm, 'searchCreator') as Ref<string>,
{ delay: 300 },
);
// ===== 表格状态 =====
const [loading, setLoading] = useState<boolean>(false);
const [dataSource, setDataSource] = useState<any[]>(MOCK_DATA);
const [pagination, setPagination] = useState({
current: 1,
pageSize: 10,
total: MOCK_DATA.length,
});
// ===== 表格列配置 =====
const columns = [
{ title: '赛事ID', dataIndex: 'eventId', key: 'eventId', width: 180 },
{
title: '赛事名称',
dataIndex: 'eventName',
key: 'eventName',
width: 160,
},
{
title: '赛事时间',
key: 'eventTime',
width: 260,
customRender: ({ record }: { record: any }) =>
`${record.eventTimeStart}${record.eventTimeEnd}`,
},
{
title: '省市区',
key: 'region',
width: 200,
customRender: ({ record }: { record: any }) =>
`${record.province} ${record.city} ${record.district}`,
},
{ title: '地点', dataIndex: 'address', key: 'address', width: 180 },
{
title: '是否提供证件号',
dataIndex: 'needIdCard',
key: 'needIdCard',
width: 160,
},
{
title: '是否提供证件图片',
dataIndex: 'needIdCardImage',
key: 'needIdCardImage',
width: 160,
},
{
title: '创建人昵称',
dataIndex: 'creatorNickname',
key: 'creatorNickname',
width: 110,
},
{
title: '创建人手机号',
dataIndex: 'creatorPhone',
key: 'creatorPhone',
width: 130,
},
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 170 },
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 90,
customRender: ({ text }: { text: string }) => {
const info = STATUS_MAP[text] || { label: text, color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
},
},
{ title: '报名人数', dataIndex: 'enrolledCount', key: 'enrolledCount', width: 90 },
{ title: '取消报名人数', dataIndex: 'cancelledCount', key: 'cancelledCount', width: 140 },
];
// ===== 计算属性 =====
const hasFilter = computed(() => {
return (
filterForm.createTimeRange !== null ||
filterForm.eventTimeRange !== null ||
debouncedName.value.trim() !== '' ||
debouncedCreator.value.trim() !== '' ||
filterForm.status !== '' ||
filterForm.region.length > 0 ||
filterForm.publicEvent !== '' ||
filterForm.needIdCard !== '' ||
filterForm.needIdCardImage !== ''
);
});
// ===== 方法 =====
/** 查询 */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
createTimeRange: filterForm.createTimeRange,
eventTimeRange: filterForm.eventTimeRange,
name: debouncedName.value,
creator: debouncedCreator.value,
status: filterForm.status,
region: filterForm.region,
publicEvent: filterForm.publicEvent,
needIdCard: filterForm.needIdCard,
needIdCardImage: filterForm.needIdCardImage,
});
// TODO: 替换为真实 API 调用
setDataSource(MOCK_DATA);
setPagination({ ...pagination.value, total: MOCK_DATA.length });
message.success('查询成功');
} catch (error: any) {
message.error(error.msg || '查询失败');
} finally {
setLoading(false);
}
}, 500);
/** 重置 */
const handleReset = useThrottleFn(() => {
filterForm.createTimeRange = null;
filterForm.eventTimeRange = null;
filterForm.searchName = '';
filterForm.searchCreator = '';
filterForm.status = '';
filterForm.region = [];
filterForm.publicEvent = '';
filterForm.needIdCard = '';
filterForm.needIdCardImage = '';
setPagination({ current: 1, pageSize: 10, total: MOCK_DATA.length });
setDataSource(MOCK_DATA);
}, 500);
const handlePageChange = (page: number, pageSize: number) => {
setPagination({ ...pagination.value, current: page, pageSize });
handleSearch();
};
return {
filterForm,
loading,
dataSource,
columns,
pagination,
hasFilter,
handleSearch,
handleReset,
handlePageChange,
};
}
@@ -0,0 +1,196 @@
// ===== 自定义标题栏 =====
.modalHeader {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 0 16px;
margin-bottom: 16px;
border-bottom: 1px solid #f0f0f0;
}
.modalTitle {
font-size: 16px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
}
.closeBtn {
width: 28px;
height: 28px;
border: none;
background: transparent;
font-size: 22px;
line-height: 1;
color: rgba(0, 0, 0, 0.45);
cursor: pointer;
border-radius: 4px;
transition: all 0.2s;
&:hover {
background: rgba(0, 0, 0, 0.04);
color: rgba(0, 0, 0, 0.85);
}
}
// ===== 内容区 =====
.modalBody {
padding-top: 0;
}
// ===== 订单信息 grid =====
.infoGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
row-gap: 12px;
column-gap: 24px;
font-size: 13px;
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #f0f0f0;
}
.infoItem {
display: flex;
align-items: baseline;
min-width: 0;
}
.infoLabel {
color: rgba(0, 0, 0, 0.65);
flex-shrink: 0;
}
// ===== 通用 section =====
.section {
margin-bottom: 24px;
}
.section:last-child {
margin-bottom: 0;
}
.sectionTitle {
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 12px;
padding-left: 8px;
border-left: 3px solid #1677ff;
}
// ===== 退款记录 =====
.refundHeader {
margin-bottom: 12px;
}
.refundSummary {
display: flex;
gap: 32px;
font-size: 13px;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 12px;
}
/** 固定高度 + 滚动 */
.refundList {
max-height: 320px;
overflow-y: auto;
padding-right: 4px;
// 自定义滚动条样式
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-thumb {
background: #d9d9d9;
border-radius: 3px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
}
.refundCard {
padding: 14px 16px;
margin-bottom: 12px;
background: #fafafa;
border: 1px solid #f0f0f0;
border-radius: 6px;
}
.refundCard:last-child {
margin-bottom: 0;
}
.refundCardHeader {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
padding-bottom: 10px;
border-bottom: 1px dashed #e0e0e0;
}
.refundIndex {
font-size: 13px;
font-weight: 500;
color: rgba(0, 0, 0, 0.85);
}
.refundCardBody {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px 24px;
font-size: 13px;
color: rgba(0, 0, 0, 0.65);
line-height: 1.8;
}
.refundCol {
min-width: 0;
}
.refundAmount {
color: rgba(0, 0, 0, 0.85);
font-weight: 500;
}
.partialMark {
margin-left: 4px;
color: #fa8c16;
font-size: 12px;
}
.refundEmpty {
padding: 32px 0;
text-align: center;
font-size: 13px;
color: rgba(0, 0, 0, 0.45);
background: #fafafa;
border-radius: 6px;
border: 1px dashed #e0e0e0;
}
// 分页:右下角
.refundPagination {
display: flex;
justify-content: flex-end;
margin-top: 12px;
}
// ===== 底部按钮区 =====
.modalFooter {
display: flex;
justify-content: flex-end;
gap: 12px;
padding-top: 16px;
margin-top: 8px;
border-top: 1px solid #f0f0f0;
}
// ===== Modal 外层包裹:去除 antd 默认内边距,让自定义标题贴合 =====
.orderModalWrap {
:global(.ant-modal-body) {
padding-top: 16px;
}
}
@@ -0,0 +1,270 @@
import { defineComponent, ref, computed } from 'vue';
import { Modal, Table, Button, Tag, Pagination, Image, Space } from 'ant-design-vue';
import styles from './OrderDetailModal.module.less';
interface OrderDetailModalProps {
visible: boolean;
record: any;
onClose: () => void;
/** 触发"重新退款"二次确认对话框 */
onReRefund: (record: any) => void;
}
const PLAYER_COLUMNS = [
{ title: '真实姓名', dataIndex: 'name', key: 'name', width: 100, align: 'center' as const },
{ title: '性别', dataIndex: 'gender', key: 'gender', width: 80, align: 'center' as const },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 130 },
{ title: '证件号', dataIndex: 'idNo', key: 'idNo', width: 180 },
{
title: '证件图片',
dataIndex: 'idImg',
key: 'idImg',
width: 170,
customRender: ({ text }: { text: string[] }) => (
<Space>
{(text || []).map((src) => (
<Image key={src} width={60} height={40} src={src} />
))}
</Space>
),
},
{
title: '比赛组别',
dataIndex: 'groupName',
key: 'groupName',
width: 110,
align: 'center' as const,
},
{
title: '订单金额',
dataIndex: 'orderAmount',
key: 'orderAmount',
width: 100,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '优惠金额',
dataIndex: 'discountAmount',
key: 'discountAmount',
width: 100,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '实付金额',
dataIndex: 'paidAmount',
key: 'paidAmount',
width: 100,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '退款金额',
dataIndex: 'refundAmount',
key: 'refundAmount',
width: 100,
align: 'right' as const,
customRender: ({ text }: { text: number }) => (text ? text.toFixed(2) : '-'),
},
];
const REFUND_STATUS_MAP: Record<string, { label: string; color: string }> = {
success: { label: '退款成功', color: 'green' },
failed: { label: '退款失败', color: 'red' },
};
export default defineComponent({
name: 'OrderDetailModal',
props: {
visible: { type: Boolean, default: false },
record: { type: Object, default: () => ({}) },
onClose: { type: Function, required: true },
onReRefund: { type: Function, required: true },
},
setup(props: OrderDetailModalProps) {
const refundPage = ref<number>(1);
const refundPageSize = ref<number>(2);
/** 退款记录 */
const refundRecords = computed<any[]>(() => props.record?.refundRecords || []);
const hasRefund = computed(() => refundRecords.value.length > 0);
/** 当前页展示的退款记录 */
const pagedRefunds = computed(() => {
const start = (refundPage.value - 1) * refundPageSize.value;
return refundRecords.value.slice(start, start + refundPageSize.value);
});
/** 已退金额合计 */
const totalRefunded = computed(() =>
refundRecords.value
.filter((r) => r.status === 'success')
.reduce((sum, r) => sum + (r.amount || 0), 0),
);
const handleRefundPageChange = (page: number, pageSize: number) => {
refundPage.value = page;
refundPageSize.value = pageSize;
};
const handleConfirm = () => {
// 无退款信息时:仅关闭弹窗
props.onClose();
};
const handleReRefund = () => {
props.onReRefund(props.record);
};
return () => (
<Modal
visible={props.visible}
onCancel={props.onClose}
footer={null}
width={1000}
centered
destroyOnClose
closable={false}
wrapClassName={styles.orderModalWrap}
>
{/* ===== 自定义标题栏 ===== */}
<div class={styles.modalHeader}>
<span class={styles.modalTitle}></span>
<button class={styles.closeBtn} onClick={props.onClose} aria-label="关闭">
×
</button>
</div>
<div class={styles.modalBody}>
{/* ===== 订单信息 ===== */}
<div class={styles.infoGrid}>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{props.record?.eventName}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{props.record?.orderId}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{props.record?.orderTime}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{props.record?.payTime}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{props.record?.totalAmount?.toFixed(2)}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{(props.record?.discountAmount || 0).toFixed(2)}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}></span>
<span>{props.record?.paidAmount?.toFixed(2)}</span>
</div>
<div class={styles.infoItem}>
<span class={styles.infoLabel}>退</span>
<span>{props.record?.refundAmount?.toFixed(2)}</span>
</div>
</div>
{/* ===== 选手信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<Table
columns={PLAYER_COLUMNS}
dataSource={props.record?.players || []}
size="small"
bordered
pagination={false}
scroll={{ x: 'max-content' }}
/>
</div>
{/* ===== 退款记录 ===== */}
<div class={styles.section}>
<div class={styles.refundHeader}>
<span class={styles.sectionTitle}>退</span>
</div>
{hasRefund.value ? (
<>
<div class={styles.refundSummary}>
<span>退{totalRefunded.value.toFixed(2)}</span>
<span>退{refundRecords.value.length}</span>
</div>
{/* 固定高度 + 内部滚动 */}
<div class={styles.refundList}>
{pagedRefunds.value.map((r, idx) => {
const statusInfo = REFUND_STATUS_MAP[r.status] || {
label: '-',
color: 'default',
};
const realIdx = (refundPage.value - 1) * refundPageSize.value + idx + 1;
return (
<div key={r.key} class={styles.refundCard}>
<div class={styles.refundCardHeader}>
<span class={styles.refundIndex}>{realIdx}退</span>
<Tag color={statusInfo.color}>{statusInfo.label}</Tag>
</div>
<div class={styles.refundCardBody}>
<div class={styles.refundCol}>
<div>
退
<span class={styles.refundAmount}>
¥{r.amount.toFixed(2)}
{r.isPartial && (
<span class={styles.partialMark}>退</span>
)}
</span>
</div>
<div>{r.applyTime}</div>
<div>{r.completeTime || '-'}</div>
</div>
<div class={styles.refundCol}>
<div>退{r.method}</div>
<div>退{r.thirdPartyNo || '-'}</div>
</div>
</div>
</div>
);
})}
</div>
<div class={styles.refundPagination}>
<Pagination
current={refundPage.value}
pageSize={refundPageSize.value}
total={refundRecords.value.length}
showSizeChanger={false}
size="small"
onChange={handleRefundPageChange}
/>
</div>
</>
) : (
<div class={styles.refundEmpty}>退</div>
)}
</div>
</div>
{/* ===== 底部按钮 ===== */}
<div class={styles.modalFooter}>
<Button onClick={props.onClose}></Button>
{hasRefund.value ? (
<Button danger onClick={handleReRefund}>
退
</Button>
) : (
<Button type="primary" onClick={handleConfirm}>
</Button>
)}
</div>
</Modal>
);
},
});
+37
View File
@@ -0,0 +1,37 @@
/**
* 表格 body 容器:占满 flex 剩余空间,并确保 antd 嵌套 div 逐层传递 height: 100%
* 使得 Table scroll.y = 'calc(100% - 55px)' 中的 100% 能正确解析。
*/
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
.summaryBar {
flex-shrink: 0;
display: flex;
align-items: center;
gap: 20px;
padding: 8px 0;
font-size: 14px;
color: #1a1a1a;
.summaryItem {
font-weight: 500;
.summaryLabel {
color: #666;
font-weight: 400;
}
}
}
+268
View File
@@ -0,0 +1,268 @@
import { defineComponent } from 'vue';
import {
Button,
Input,
Table,
Form,
Space,
Select,
DatePicker,
Tooltip,
Pagination,
Modal,
} from 'ant-design-vue';
import { useOrderModel, ORDER_STATUS_OPTIONS, REFUND_STATUS_OPTIONS } from './model/useOrderModel';
import { useContainerSize, useState } from '@/hooks';
import OrderDetailModal from './components/OrderDetailModal';
import styles from './index.module.less';
const { RangePicker } = DatePicker;
/**
* 触发「重新退款」二次确认对话框
* 表格中的重新退款按钮和详情弹窗中的重新退款按钮均调用此函数。
*/
function promptReRefund(record: any) {
Modal.confirm({
title: '确认要重新退款吗?',
content: (
<div>
<div>退{(record.refundAmount || 0).toFixed(2)}</div>
<div>退退</div>
</div>
),
okText: '确认',
cancelText: '取消',
onOk: () => {
console.log('重新退款:', record.orderId);
// TODO: 替换为真实 API 调用
},
});
}
/**
* bodyCell 渲染函数
*/
function renderBodyCell({
column,
text,
record,
onView,
onReRefund,
}: {
column: any;
text: any;
record: any;
onView: (record: any) => void;
onReRefund: (record: any) => void;
}) {
// 赛事名称:最多15字符,超出显示 Tooltip
if (column.dataIndex === 'eventName') {
const maxLen = 15;
const raw = text || '';
const display = raw.length > maxLen ? raw.slice(0, maxLen) + '...' : raw;
return raw.length > maxLen ? (
<Tooltip title={raw}>
<span>{display}</span>
</Tooltip>
) : (
<span>{display}</span>
);
}
if (column.key === 'action') {
const showReRefund = record.refundStatus === 'refund_failed';
return (
<Space>
<Button type="link" size="small" onClick={() => onView(record)}>
</Button>
{showReRefund && (
<Button type="link" size="small" onClick={() => onReRefund(record)}>
退
</Button>
)}
</Space>
);
}
return;
}
/**
* 订单管理
*/
export default defineComponent({
name: 'EventOrders',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
summary,
pagination,
handleSearch,
handleReset,
handlePageChange,
} = useOrderModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
// 详情弹窗状态
const [detailVisible, setDetailVisible] = useState<boolean>(false);
const [currentRecord, setCurrentRecord] = useState<any>({});
const handleView = (record: any) => {
setCurrentRecord(record);
setDetailVisible(true);
};
const handleReRefund = (record: any) => {
promptReRefund(record);
};
/** 最终表格列:模型列 + 操作 */
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 160,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="订单时间" name="orderTimeRange">
<RangePicker
value={filterForm.orderTimeRange as any}
style={{ width: '260px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.orderTimeRange = val)}
/>
</Form.Item>
<Form.Item label="订单编号" name="searchOrderId">
<Input
placeholder="请输入订单编号"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="赛事名称" name="searchEventName">
<Input
placeholder="请输入赛事名称"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="选手名称" name="searchPlayerName">
<Input
placeholder="请输入选手名称"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="订单状态" name="orderStatus">
<Select
value={filterForm.orderStatus}
options={ORDER_STATUS_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.orderStatus = val || '')}
/>
</Form.Item>
<Form.Item label="退款状态" name="refundStatus">
<Select
value={filterForm.refundStatus}
options={REFUND_STATUS_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.refundStatus = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</Button>
<Button onClick={handleReset}></Button>
</Space>
</Form.Item>
</Form>
</div>
{/* ===== 表格区 ===== */}
<div class="page-table">
{/* 金额汇总 */}
<div class={styles.summaryBar}>
<span class={styles.summaryItem}>
<span class={styles.summaryLabel}></span>
{summary.value.totalOrderAmount.toFixed(2)}
</span>
<span class={styles.summaryItem}>
<span class={styles.summaryLabel}></span>
{summary.value.totalPaidAmount.toFixed(2)}
</span>
<span class={styles.summaryItem}>
<span class={styles.summaryLabel}>退</span>
{summary.value.totalRefundAmount.toFixed(2)}
</span>
</div>
<div ref={containerRef} class={styles.tableBody}>
<Table
columns={tableColumns}
dataSource={dataSource.value}
loading={loading.value}
scroll={{ x: 'max-content', y: height.value }}
pagination={false}
>
{{
bodyCell: (args: any) =>
renderBodyCell({
...args,
onView: handleView,
onReRefund: handleReRefund,
}),
}}
</Table>
</div>
{/* 独立分页,右下方 */}
<div class="page-pagination">
<Pagination
current={pagination.value.current}
pageSize={pagination.value.pageSize}
total={pagination.value.total}
showSizeChanger
showTotal={(total: number) => `${total}`}
onChange={handlePageChange}
onShowSizeChange={handlePageChange}
/>
</div>
</div>
{/* ===== 详情弹窗 ===== */}
<OrderDetailModal
visible={detailVisible.value}
record={currentRecord.value}
onClose={() => setDetailVisible(false)}
onReRefund={(record) => {
// 关闭详情弹窗,再弹出二次确认
setDetailVisible(false);
promptReRefund(record);
}}
/>
</div>
);
},
});
@@ -0,0 +1,343 @@
import { computed, reactive, toRef, Ref, h } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 订单状态选项 */
export const ORDER_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'paid', label: '已支付' },
{ value: 'partial_refund', label: '部分退款' },
{ value: 'full_refund', label: '全部退款' },
{ value: 'closed', label: '已关闭' },
] as const;
/** 退款状态选项 */
export const REFUND_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'refund_success', label: '退款成功' },
{ value: 'refund_failed', label: '退款失败' },
] as const;
/** 订单状态 Tag 映射 */
const ORDER_STATUS_MAP: Record<string, { label: string; color: string }> = {
paid: { label: '已支付', color: 'green' },
partial_refund: { label: '部分退款', color: 'orange' },
full_refund: { label: '全部退款', color: 'blue' },
closed: { label: '已关闭', color: 'default' },
};
/** 退款状态 Tag 映射 */
const REFUND_STATUS_MAP: Record<string, { label: string; color: string }> = {
refund_success: { label: '退款成功', color: 'green' },
refund_failed: { label: '退款失败', color: 'red' },
};
// ============================================================
// 假数据
// ============================================================
const MOCK_DATA = Array.from({ length: 12 }, (_, i) => {
const orderStatus = (['paid', 'paid', 'partial_refund', 'full_refund', 'closed'] as const)[i % 5];
const refundStatus: string =
orderStatus === 'partial_refund' || orderStatus === 'full_refund'
? (['refund_success', 'refund_success', 'refund_failed'] as const)[i % 3]
: '';
const totalAmount = [188.0, 256.5, 399.0, 128.0, 520.0][i % 5];
const discountAmount = i % 3 === 0 ? 20.0 : i % 3 === 1 ? 10.0 : 0;
const refundAmount =
orderStatus === 'partial_refund'
? 50.0
: orderStatus === 'full_refund'
? totalAmount - discountAmount
: 0;
// ===== 选手信息(详情弹窗用) =====
const playerNames = ['张三', '李四', '王五'];
const players = playerNames.slice(0, (i % 3) + 1).map((name, idx) => ({
key: `${i + 1}-${idx}`,
name,
gender: idx === 1 ? '女' : '男',
phone: '12345678956',
idNo: 'xxxxxxxxxxxxxxxx',
idImg: [
'https://picsum.photos/seed/idimg-a/120/80',
'https://picsum.photos/seed/idimg-b/120/80',
],
groupName: ['男子单打', '女子双打', '混合双打'][idx],
orderAmount: [100.0, 50.0, 38.0][idx],
discountAmount: 0,
paidAmount: [100.0, 50.0, 38.0][idx],
refundAmount: idx === 1 && orderStatus === 'full_refund' ? 50.0 : 0,
}));
// ===== 退款记录(详情弹窗用) =====
const refundRecords: any[] = [];
if (orderStatus === 'partial_refund' || orderStatus === 'full_refund') {
if (i % 4 === 2) {
refundRecords.push(
{
key: `${i + 1}-r1`,
amount: 50.0,
isPartial: true,
applyTime: '2026-06-07 16:20',
completeTime: '2026-06-07 16:25',
method: '原路退回(微信支付)',
thirdPartyNo: '5030000789202606071625102846',
status: 'success',
},
{
key: `${i + 1}-r2`,
amount: 49.0,
isPartial: false,
applyTime: '2026-06-08 10:00',
completeTime: '',
method: '原路退回(微信支付)',
thirdPartyNo: '',
status: 'failed',
},
);
} else if (i % 4 === 0) {
refundRecords.push({
key: `${i + 1}-r1`,
amount: 30.0,
isPartial: true,
applyTime: '2026-06-05 09:30',
completeTime: '2026-06-05 09:35',
method: '原路退回(微信支付)',
thirdPartyNo: '5030000789202606050935000123',
status: 'success',
});
}
}
return {
key: `${i + 1}`,
orderId: `ORD202607${String(i + 1).padStart(5, '0')}`,
eventName:
i % 3 === 0
? '2026全国青少年羽毛球锦标赛暨体育文化交流大会'
: i % 3 === 1
? '国际马拉松城市联赛'
: '全民健身运动会',
playerName: ['张选手', '李选手', '王选手', '赵选手'][i % 4],
phone: ['13800138001', '13900139002', '13700137003', '13600136004'][i % 4],
groupName: ['男子青年组', '女子青年组', '男子中年组', '女子中年组'][i % 4],
registrant: ['张报名', '李报名', '王报名', '赵报名'][i % 4],
registrantPhone: ['13800138001', '13900139002', '13700137003', '13600136004'][i % 4],
registrantCount: [1, 2, 1, 3][i % 4],
orderTime: '2026-07-15 10:30:00',
payTime: '2026-07-15 10:32:15',
totalAmount,
discountAmount,
paidAmount: totalAmount - discountAmount,
refundAmount,
orderStatus,
refundStatus,
players,
refundRecords,
};
});
// ============================================================
// 金额汇总假数据
// ============================================================
const MOCK_SUMMARY = {
totalOrderAmount: 113255.0,
totalPaidAmount: 113255.0,
totalRefundAmount: 1255.0,
};
// ============================================================
// Model
// ============================================================
/**
* 订单列表页数据模型
*/
export function useOrderModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
orderTimeRange: null as [string, string] | null,
searchOrderId: '',
searchEventName: '',
searchPlayerName: '',
orderStatus: '',
refundStatus: '',
});
// 可搜索字段防抖
const { debouncedValue: debouncedOrderId } = useDebounce(
toRef(filterForm, 'searchOrderId') as Ref<string>,
{ delay: 300 },
);
const { debouncedValue: debouncedEventName } = useDebounce(
toRef(filterForm, 'searchEventName') as Ref<string>,
{ delay: 300 },
);
const { debouncedValue: debouncedPlayerName } = useDebounce(
toRef(filterForm, 'searchPlayerName') as Ref<string>,
{ delay: 300 },
);
// ===== 表格状态 =====
const [loading, setLoading] = useState<boolean>(false);
const [dataSource, setDataSource] = useState<any[]>(MOCK_DATA);
const [pagination, setPagination] = useState({
current: 1,
pageSize: 10,
total: MOCK_DATA.length,
});
// ===== 金额汇总 =====
const [summary, setSummary] = useState(MOCK_SUMMARY);
// ===== 表格列配置 =====
const columns = [
{ title: '订单编号', dataIndex: 'orderId', key: 'orderId', width: 200 },
{ title: '赛事名称', dataIndex: 'eventName', key: 'eventName', width: 180 },
{ title: '选手名称', dataIndex: 'playerName', key: 'playerName', width: 100 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 130 },
{ title: '比赛组别', dataIndex: 'groupName', key: 'groupName', width: 120 },
{ title: '报名人', dataIndex: 'registrant', key: 'registrant', width: 100 },
{ title: '报名人手机号', dataIndex: 'registrantPhone', key: 'registrantPhone', width: 130 },
{
title: '报名人数',
dataIndex: 'registrantCount',
key: 'registrantCount',
width: 90,
align: 'center' as const,
},
{ title: '订单时间', dataIndex: 'orderTime', key: 'orderTime', width: 170 },
{ title: '支付时间', dataIndex: 'payTime', key: 'payTime', width: 170 },
{
title: '订单总金额',
dataIndex: 'totalAmount',
key: 'totalAmount',
width: 120,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '总优惠金额',
dataIndex: 'discountAmount',
key: 'discountAmount',
width: 120,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '实付总金额',
dataIndex: 'paidAmount',
key: 'paidAmount',
width: 120,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '退款总金额',
dataIndex: 'refundAmount',
key: 'refundAmount',
width: 120,
align: 'right' as const,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '订单状态',
dataIndex: 'orderStatus',
key: 'orderStatus',
width: 100,
align: 'center' as const,
customRender: ({ text }: { text: string }) => {
const info = ORDER_STATUS_MAP[text] || { label: text || '-', color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
},
},
{
title: '退款状态',
dataIndex: 'refundStatus',
key: 'refundStatus',
width: 100,
align: 'center' as const,
customRender: ({ text }: { text: string }) => {
if (!text) return h('span', '-');
const info = REFUND_STATUS_MAP[text] || { label: text, color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
},
},
];
// ===== 计算属性 =====
const hasFilter = computed(() => {
return (
filterForm.orderTimeRange !== null ||
debouncedOrderId.value.trim() !== '' ||
debouncedEventName.value.trim() !== '' ||
debouncedPlayerName.value.trim() !== '' ||
filterForm.orderStatus !== '' ||
filterForm.refundStatus !== ''
);
});
// ===== 方法 =====
/** 查询 */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
orderTimeRange: filterForm.orderTimeRange,
orderId: debouncedOrderId.value,
eventName: debouncedEventName.value,
playerName: debouncedPlayerName.value,
orderStatus: filterForm.orderStatus,
refundStatus: filterForm.refundStatus,
});
// TODO: 替换为真实 API 调用
setDataSource(MOCK_DATA);
setPagination({ ...pagination.value, total: MOCK_DATA.length });
setSummary(MOCK_SUMMARY);
message.success('查询成功');
} catch (error: any) {
message.error(error.msg || '查询失败');
} finally {
setLoading(false);
}
}, 500);
/** 重置 */
const handleReset = useThrottleFn(() => {
filterForm.orderTimeRange = null;
filterForm.searchOrderId = '';
filterForm.searchEventName = '';
filterForm.searchPlayerName = '';
filterForm.orderStatus = '';
filterForm.refundStatus = '';
setPagination({ current: 1, pageSize: 10, total: MOCK_DATA.length });
setDataSource(MOCK_DATA);
setSummary(MOCK_SUMMARY);
}, 500);
const handlePageChange = (page: number, pageSize: number) => {
setPagination({ ...pagination.value, current: page, pageSize });
handleSearch();
};
return {
filterForm,
loading,
dataSource,
columns,
summary,
pagination,
hasFilter,
handleSearch,
handleReset,
handlePageChange,
};
}
+18
View File
@@ -0,0 +1,18 @@
/**
* 表格 body 容器:占满 flex 剩余空间,并确保 antd 嵌套 div 逐层传递 height: 100%
* 使得 Table scroll.y = 'calc(100% - 55px)' 中的 100% 能正确解析。
*/
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
+181
View File
@@ -0,0 +1,181 @@
import { defineComponent } from 'vue';
import {
Button,
Input,
Table,
Form,
Space,
Select,
Image,
Pagination,
Modal,
} from 'ant-design-vue';
import { useUserModel, USER_STATUS_OPTIONS } from './model/useUserModel';
import { useContainerSize } from '@/hooks';
import styles from './index.module.less';
/**
* bodyCell 渲染函数
*/
function renderBodyCell({
column,
text,
record,
onToggleStatus,
}: {
column: any;
text: any;
record: any;
onToggleStatus: (record: any) => void;
}) {
// 证件图片:有则显示,无则不显示
if (column.dataIndex === 'idImg') {
const images = record.idImg || [];
if (images.length === 0) {
return '-';
}
return (
<Space>
{images.map((src: string) => (
<Image key={src} width={48} height={32} src={src} />
))}
</Space>
);
}
if (column.key === 'action') {
const isActive = record.status === 'active';
return (
<Button type="link" size="small" danger={isActive} onClick={() => onToggleStatus(record)}>
{isActive ? '禁用' : '启用'}
</Button>
);
}
return;
}
/**
* 用户列表
*/
export default defineComponent({
name: 'EventUsers',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
pagination,
handleSearch,
handleReset,
handlePageChange,
} = useUserModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
const handleToggleStatus = (record: any) => {
const isActive = record.status === 'active';
const actionText = isActive ? '禁用' : '启用';
Modal.confirm({
title: `${actionText}确认`,
content: `确认${actionText}用户"${record.nickName}"吗?`,
okText: '确认',
cancelText: '取消',
onOk: () => {
console.log(`${actionText}用户:`, record.userId);
// TODO: 替换为真实 API 调用
},
});
};
/** 最终表格列:模型列 + 操作 */
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 100,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="用户昵称" name="searchUserName">
<Input
placeholder="请输入用户昵称"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="手机号" name="searchPhone">
<Input
placeholder="请输入手机号"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Select
value={filterForm.status}
options={USER_STATUS_OPTIONS as any}
style={{ width: '110px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.status = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</Button>
<Button onClick={handleReset}></Button>
</Space>
</Form.Item>
</Form>
</div>
{/* ===== 表格区 ===== */}
<div class="page-table">
<div ref={containerRef} class={styles.tableBody}>
<Table
columns={tableColumns}
dataSource={dataSource.value}
loading={loading.value}
scroll={{ x: 'max-content', y: height.value }}
pagination={false}
>
{{
bodyCell: (args: any) =>
renderBodyCell({
...args,
onToggleStatus: handleToggleStatus,
}),
}}
</Table>
</div>
{/* 独立分页,右下方 */}
<div class="page-pagination">
<Pagination
current={pagination.value.current}
pageSize={pagination.value.pageSize}
total={pagination.value.total}
showSizeChanger
showTotal={(total: number) => `${total}`}
onChange={handlePageChange}
onShowSizeChange={handlePageChange}
/>
</div>
</div>
</div>
);
},
});
@@ -0,0 +1,160 @@
import { computed, reactive, toRef, Ref, h } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 用户状态选项 */
export const USER_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'active', label: '正常' },
{ value: 'disabled', label: '禁用' },
] as const;
/** 用户状态 Tag 映射 */
const USER_STATUS_MAP: Record<string, { label: string; color: string }> = {
active: { label: '正常', color: 'green' },
disabled: { label: '禁用', color: 'red' },
};
// ============================================================
// 假数据
// ============================================================
const MOCK_DATA = Array.from({ length: 12 }, (_, i) => ({
key: `${i + 1}`,
userId: `U202607${String(i + 1).padStart(5, '0')}`,
nickName: ['羽毛球小将', '马拉松达人', '健身爱好者', '游泳健将'][i % 4],
phone: ['13800138001', '13900139002', '13700137003', '13600136004'][i % 4],
realName: ['张三', '李四', '王五', '赵六'][i % 4],
gender: i % 2 === 0 ? '男' : '女',
idNo: '320101199001011234',
// 证图片来源:奇数索引有,偶数无
idImg:
i % 2 === 1
? ['https://picsum.photos/seed/idcard-a/120/80', 'https://picsum.photos/seed/idcard-b/120/80']
: [],
status: (i % 4 === 3 ? 'disabled' : 'active') as string,
loginTime: '2026-07-20 14:30:00',
}));
// ============================================================
// Model
// ============================================================
/**
* 用户列表页数据模型
*/
export function useUserModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
searchUserName: '',
searchPhone: '',
status: '',
});
// 各字段防抖 300ms
const { debouncedValue: debouncedUserName } = useDebounce(
toRef(filterForm, 'searchUserName') as Ref<string>,
{ delay: 300 },
);
const { debouncedValue: debouncedPhone } = useDebounce(
toRef(filterForm, 'searchPhone') as Ref<string>,
{ delay: 300 },
);
// ===== 表格状态 =====
const [loading, setLoading] = useState<boolean>(false);
const [dataSource, setDataSource] = useState<any[]>(MOCK_DATA);
const [pagination, setPagination] = useState({
current: 1,
pageSize: 10,
total: MOCK_DATA.length,
});
// ===== 表格列配置 =====
const columns = [
{ title: '用户昵称', dataIndex: 'nickName', key: 'nickName', width: 120 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 140 },
{ title: '真实姓名', dataIndex: 'realName', key: 'realName', width: 100 },
{ title: '性别', dataIndex: 'gender', key: 'gender', width: 80 },
{ title: '证件号', dataIndex: 'idNo', key: 'idNo', width: 180 },
{
title: '证件图片',
dataIndex: 'idImg',
key: 'idImg',
width: 140,
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 90,
align: 'center' as const,
customRender: ({ text }: { text: string }) => {
const info = USER_STATUS_MAP[text] || { label: text, color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
},
},
{ title: '登录时间', dataIndex: 'loginTime', key: 'loginTime', width: 170 },
];
// ===== 计算属性 =====
const hasFilter = computed(() => {
return (
debouncedUserName.value.trim() !== '' ||
debouncedPhone.value.trim() !== '' ||
filterForm.status !== ''
);
});
// ===== 方法 =====
/** 查询(节流 500ms */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
userName: debouncedUserName.value,
phone: debouncedPhone.value,
status: filterForm.status,
});
// TODO: 替换为真实 API 调用
setDataSource(MOCK_DATA);
setPagination({ ...pagination.value, total: MOCK_DATA.length });
message.success('查询成功');
} catch (error: any) {
message.error(error.msg || '查询失败');
} finally {
setLoading(false);
}
}, 500);
/** 重置(节流 500ms */
const handleReset = useThrottleFn(() => {
filterForm.searchUserName = '';
filterForm.searchPhone = '';
filterForm.status = '';
setPagination({ current: 1, pageSize: 10, total: MOCK_DATA.length });
setDataSource(MOCK_DATA);
}, 500);
const handlePageChange = (page: number, pageSize: number) => {
setPagination({ ...pagination.value, current: page, pageSize });
handleSearch();
};
return {
filterForm,
loading,
dataSource,
columns,
pagination,
hasFilter,
handleSearch,
handleReset,
handlePageChange,
};
}
+15
View File
@@ -0,0 +1,15 @@
import { defineComponent } from 'vue';
/**
* 支付流水
*/
export default defineComponent({
name: 'FinancePayments',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
},
});
+15
View File
@@ -0,0 +1,15 @@
import { defineComponent } from 'vue';
/**
* 账务报表
*/
export default defineComponent({
name: 'FinanceReports',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
},
});
+15
View File
@@ -0,0 +1,15 @@
import { defineComponent } from 'vue';
/**
* 用户钱包
*/
export default defineComponent({
name: 'FinanceWallet',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
},
});
+15
View File
@@ -0,0 +1,15 @@
import { defineComponent } from 'vue';
/**
* 提现申请
*/
export default defineComponent({
name: 'FinanceWithdraw',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
},
});
+798 -12
View File
@@ -1,20 +1,806 @@
// ── 登录页 — 左右分栏 — 动画背景版 ──
// 左侧:深色品牌展示区,含浮动光球、网格呼吸、脉冲涟漪、粒子点阵等多层动画
// 右侧:白色登录表单区,入场渐显动画
.container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
overflow: hidden;
}
.card {
width: 400px;
max-width: 90vw;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
// ━━━━ 左侧品牌展示区 ━━━━
.brand {
flex: 1;
display: flex;
flex-direction: column;
position: relative;
background: linear-gradient(160deg, #0c1e3a 0%, #132744 50%, #0a1628 100%);
color: #fff;
overflow: hidden;
padding: 40px 56px 40px 64px;
}
:global(.ant-card-head-title) {
text-align: center;
font-size: 18px;
font-weight: 600;
// ── 动画层1: 浮动光球 ──
.orb1 {
position: absolute;
width: 460px;
height: 460px;
border-radius: 50%;
background: radial-gradient(
circle,
rgba(22, 119, 255, 0.14) 0%,
rgba(22, 119, 255, 0.04) 40%,
transparent 70%
);
top: -100px;
right: 20%;
z-index: 0;
animation: orbFloat1 12s ease-in-out infinite;
filter: blur(2px);
}
.orb2 {
position: absolute;
width: 360px;
height: 360px;
border-radius: 50%;
background: radial-gradient(
circle,
rgba(82, 196, 26, 0.1) 0%,
rgba(82, 196, 26, 0.03) 40%,
transparent 70%
);
bottom: 40px;
left: 10%;
z-index: 0;
animation: orbFloat2 15s ease-in-out infinite;
filter: blur(2px);
}
.orb3 {
position: absolute;
width: 280px;
height: 280px;
border-radius: 50%;
background: radial-gradient(
circle,
rgba(250, 173, 20, 0.08) 0%,
rgba(250, 173, 20, 0.02) 40%,
transparent 70%
);
top: 50%;
left: 55%;
z-index: 0;
animation: orbFloat3 18s ease-in-out infinite;
filter: blur(3px);
}
// ── 动画层2: 脉冲涟漪 ──
.pulse {
position: absolute;
width: 200px;
height: 200px;
border-radius: 50%;
border: 1px solid rgba(22, 119, 255, 0.15);
top: 30%;
right: 15%;
z-index: 0;
animation: pulseExpand 4s ease-out infinite;
&::before {
content: '';
position: absolute;
inset: 30px;
border-radius: 50%;
border: 1px solid rgba(22, 119, 255, 0.08);
animation: pulseExpand 4s ease-out infinite 1s;
}
&::after {
content: '';
position: absolute;
inset: 60px;
border-radius: 50%;
border: 1px solid rgba(22, 119, 255, 0.04);
animation: pulseExpand 4s ease-out infinite 2s;
}
}
// ── 动画层3: 网格呼吸 ──
.brandGrid {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
background-image:
linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
background-size: 50px 50px;
animation: gridBreathe 6s ease-in-out infinite;
}
// ── 动画层4: 粒子点阵 ──
.particles {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
}
.particle {
position: absolute;
width: 3px;
height: 3px;
border-radius: 50%;
background: rgba(22, 119, 255, 0.5);
animation: particleFloat 8s ease-in-out infinite;
&::before {
content: '';
position: absolute;
width: 2px;
height: 2px;
border-radius: 50%;
background: rgba(105, 177, 255, 0.3);
top: -8px;
left: 3px;
animation: particleFloat 6s ease-in-out infinite reverse;
}
}
// ── 动画层5: 扫描线 ──
.scanLine {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 2px;
background: linear-gradient(90deg, transparent, rgba(22, 119, 255, 0.3), transparent);
z-index: 1;
animation: scanDown 8s linear infinite;
}
// ━━━━ 动画定义 ━━━━
@keyframes orbFloat1 {
0%,
100% {
transform: translate(0, 0) scale(1);
}
25% {
transform: translate(30px, 20px) scale(1.05);
}
50% {
transform: translate(-20px, 40px) scale(0.95);
}
75% {
transform: translate(10px, -30px) scale(1.02);
}
}
@keyframes orbFloat2 {
0%,
100% {
transform: translate(0, 0) scale(1);
}
33% {
transform: translate(-40px, -20px) scale(1.08);
}
66% {
transform: translate(30px, 30px) scale(0.92);
}
}
@keyframes orbFloat3 {
0%,
100% {
transform: translate(0, 0);
}
50% {
transform: translate(-50px, -40px);
}
}
@keyframes pulseExpand {
0% {
transform: scale(0.8);
opacity: 0.6;
}
100% {
transform: scale(1.6);
opacity: 0;
}
}
@keyframes gridBreathe {
0%,
100% {
opacity: 0.6;
}
50% {
opacity: 1;
}
}
@keyframes particleFloat {
0%,
100% {
transform: translateY(0) translateX(0);
opacity: 0.5;
}
25% {
transform: translateY(-30px) translateX(10px);
opacity: 1;
}
50% {
transform: translateY(-60px) translateX(-5px);
opacity: 0.3;
}
75% {
transform: translateY(-30px) translateX(15px);
opacity: 0.8;
}
}
@keyframes scanDown {
0% {
top: -2px;
}
100% {
top: 100%;
}
}
// ━━━━ 内容层 ━━━━
.brandInner {
position: relative;
z-index: 2;
display: flex;
flex-direction: column;
flex: 1;
animation: fadeInUp 0.8s ease-out both;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
// ── Logo ──
.logoRow {
display: flex;
align-items: center;
gap: 14px;
margin-bottom: 48px;
}
.logoMark {
width: 48px;
height: 48px;
border-radius: 14px;
background: linear-gradient(135deg, #1677ff, #69b1ff);
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
font-weight: 800;
color: #fff;
box-shadow: 0 4px 20px rgba(22, 119, 255, 0.45);
animation: logoPulse 3s ease-in-out infinite;
position: relative;
&::after {
content: '';
position: absolute;
top: 4px;
left: 4px;
width: 18px;
height: 7px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.3);
}
}
@keyframes logoPulse {
0%,
100% {
box-shadow: 0 4px 20px rgba(22, 119, 255, 0.45);
}
50% {
box-shadow:
0 4px 30px rgba(22, 119, 255, 0.7),
0 0 60px rgba(22, 119, 255, 0.2);
}
}
.logoText {
font-size: 18px;
font-weight: 600;
letter-spacing: 2px;
color: rgba(255, 255, 255, 0.9);
}
// ── 大标题 ──
.brandTitle {
font-size: 32px;
font-weight: 700;
line-height: 1.35;
letter-spacing: 1px;
margin-bottom: 12px;
animation: fadeInUp 0.8s ease-out 0.1s both;
}
.brandSubtitle {
font-size: 15px;
line-height: 1.7;
color: rgba(255, 255, 255, 0.55);
margin-bottom: 40px;
max-width: 400px;
animation: fadeInUp 0.8s ease-out 0.2s both;
}
// ── 数据统计条 ──
.statsRow {
display: flex;
gap: 36px;
margin-bottom: 44px;
animation: fadeInUp 0.8s ease-out 0.3s both;
}
.statItem {
display: flex;
flex-direction: column;
gap: 4px;
}
.statValue {
font-size: 28px;
font-weight: 700;
color: #fff;
letter-spacing: 1px;
}
.statLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.45);
letter-spacing: 1px;
}
.statHighlight {
color: #69b1ff;
}
// ── 赛事模拟卡片 ──
.eventCards {
display: flex;
gap: 16px;
margin-bottom: 44px;
animation: fadeInUp 0.8s ease-out 0.4s both;
}
.eventCard {
flex: 1;
padding: 20px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
backdrop-filter: blur(8px);
transition: all 0.3s ease;
position: relative;
overflow: hidden;
// 内部光效装饰
&::before {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: radial-gradient(circle at 30% 30%, rgba(22, 119, 255, 0.06) 0%, transparent 50%);
animation: cardShimmer 5s linear infinite;
pointer-events: none;
}
&:hover {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(22, 119, 255, 0.3);
transform: translateY(-3px);
box-shadow: 0 8px 24px rgba(22, 119, 255, 0.15);
}
}
@keyframes cardShimmer {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.eventIcon {
width: 36px;
height: 36px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: 700;
color: #fff;
margin-bottom: 12px;
position: relative;
z-index: 1;
&.blue {
background: linear-gradient(135deg, #1677ff, #4096ff);
box-shadow: 0 2px 12px rgba(22, 119, 255, 0.3);
}
&.green {
background: linear-gradient(135deg, #52c41a, #73d13d);
box-shadow: 0 2px 12px rgba(82, 196, 26, 0.3);
}
&.orange {
background: linear-gradient(135deg, #fa8c16, #ffa940);
box-shadow: 0 2px 12px rgba(250, 140, 22, 0.3);
}
}
.eventTitle {
font-size: 15px;
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
margin-bottom: 6px;
position: relative;
z-index: 1;
}
.eventDesc {
font-size: 12px;
color: rgba(255, 255, 255, 0.45);
line-height: 1.5;
position: relative;
z-index: 1;
}
// ── 步骤流程 ──
.flowSteps {
display: flex;
align-items: center;
gap: 0;
animation: fadeInUp 0.8s ease-out 0.5s both;
}
.step {
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
position: relative;
}
// ── 星点效果 ──
// 中心发光点 + 四条十字光芒 + 缓慢旋转 + 闪烁呼吸
.stepDot {
position: relative;
width: 20px;
height: 20px;
margin-bottom: 12px;
// 中心核心圆点
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 6px;
height: 6px;
border-radius: 50%;
background: #fff;
box-shadow:
0 0 4px 2px rgba(22, 119, 255, 0.8),
0 0 12px 4px rgba(22, 119, 255, 0.5),
0 0 24px 8px rgba(22, 119, 255, 0.2);
transform: translate(-50%, -50%);
animation: starCorePulse 2s ease-in-out infinite;
}
// 十字光芒线(横+纵)
&::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
transform: translate(-50%, -50%) rotate(45deg);
animation:
starSpin 6s linear infinite,
starGlowPulse 2s ease-in-out infinite;
// 横向光芒
background:
linear-gradient(
0deg,
transparent 45%,
rgba(22, 119, 255, 0.9) 48%,
#fff 50%,
rgba(22, 119, 255, 0.9) 52%,
transparent 55%
),
linear-gradient(
90deg,
transparent 45%,
rgba(22, 119, 255, 0.9) 48%,
#fff 50%,
rgba(22, 119, 255, 0.9) 52%,
transparent 55%
);
}
}
// 步骤之间的连线
.stepLine {
flex: 1;
height: 1px;
min-width: 20px;
background: linear-gradient(90deg, rgba(22, 119, 255, 0.5), rgba(22, 119, 255, 0.15));
align-self: center;
margin-top: -6px; // 微调与星点中心对齐(因为label占空间)
}
@keyframes starCorePulse {
0%,
100% {
box-shadow:
0 0 4px 2px rgba(22, 119, 255, 0.8),
0 0 12px 4px rgba(22, 119, 255, 0.5),
0 0 24px 8px rgba(22, 119, 255, 0.2);
}
50% {
box-shadow:
0 0 6px 3px rgba(22, 119, 255, 1),
0 0 20px 6px rgba(22, 119, 255, 0.7),
0 0 40px 12px rgba(22, 119, 255, 0.3);
}
}
@keyframes starSpin {
0% {
transform: translate(-50%, -50%) rotate(0deg);
}
100% {
transform: translate(-50%, -50%) rotate(360deg);
}
}
@keyframes starGlowPulse {
0%,
100% {
opacity: 0.7;
}
50% {
opacity: 1;
}
}
.stepLabel {
font-size: 13px;
color: rgba(255, 255, 255, 0.7);
font-weight: 500;
text-align: center;
}
// ── 左侧底部版权 ──
.brandFooter {
margin-top: auto;
font-size: 12px;
color: rgba(255, 255, 255, 0.2);
letter-spacing: 1px;
}
// ━━━━ 右侧登录区 ━━━━
.loginSide {
width: 460px;
min-width: 380px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 48px;
background: #fff;
position: relative;
}
.loginWrapper {
width: 100%;
max-width: 340px;
animation: fadeInRight 0.6s ease-out 0.3s both;
}
@keyframes fadeInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.loginTitle {
font-size: 24px;
font-weight: 700;
color: rgba(0, 0, 0, 0.88);
margin-bottom: 6px;
}
.loginDesc {
font-size: 14px;
color: rgba(0, 0, 0, 0.45);
margin-bottom: 36px;
}
.loginForm {
:global(.ant-input-affix-wrapper) {
padding: 10px 14px;
border-radius: 10px;
border-color: #d9d9d9;
transition: all 0.3s;
&:hover {
border-color: #1677ff;
}
&:focus-within {
border-color: #1677ff;
box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.08);
}
}
:global(.ant-input-prefix) {
color: rgba(0, 0, 0, 0.3);
margin-right: 8px;
}
:global(.ant-form-item) {
margin-bottom: 22px;
}
}
.loginBtn {
height: 46px;
border-radius: 10px;
font-size: 15px;
font-weight: 600;
letter-spacing: 3px;
transition: all 0.3s;
&:hover {
transform: translateY(-1px);
box-shadow: 0 4px 16px rgba(22, 119, 255, 0.35);
}
}
// ── 记住密码行 ──
.rememberRow {
margin-bottom: 8px;
:global(.ant-checkbox-wrapper) {
color: rgba(0, 0, 0, 0.55);
font-size: 13px;
}
:global(.ant-checkbox-checked .ant-checkbox-inner) {
background-color: #1677ff;
border-color: #1677ff;
}
}
.loginFooter {
margin-top: 28px;
text-align: center;
font-size: 12px;
color: rgba(0, 0, 0, 0.25);
}
// ━━━━ 响应式 — PC 端自适应 ━━━━
// ── 大屏 (>1200px): 默认样式,无需额外处理 ──
// ── 中屏 (≤1200px): 缩减间距、光球尺寸、字号 ──
@media screen and (max-width: 1200px) {
.brand {
padding: 32px 36px 32px 40px;
}
.brandTitle {
font-size: 28px;
}
.brandSubtitle {
font-size: 14px;
margin-bottom: 32px;
}
.statsRow {
gap: 24px;
margin-bottom: 32px;
}
.statValue {
font-size: 24px;
}
.eventCards {
gap: 12px;
margin-bottom: 32px;
}
.eventCard {
padding: 16px;
}
.eventIcon {
width: 32px;
height: 32px;
margin-bottom: 10px;
}
.eventTitle {
font-size: 14px;
}
.eventDesc {
font-size: 11px;
}
.orb1 {
width: 360px;
height: 360px;
}
.orb2 {
width: 280px;
height: 280px;
}
.orb3 {
width: 200px;
height: 200px;
}
.loginSide {
width: 400px;
min-width: 340px;
padding: 36px 40px;
}
.loginWrapper {
max-width: 320px;
}
.loginTitle {
font-size: 22px;
}
.loginDesc {
font-size: 13px;
}
.stepLabel {
font-size: 12px;
}
}
+203 -41
View File
@@ -1,8 +1,8 @@
import { defineComponent, reactive, ref } from 'vue';
import { Button, Card, Form, FormItem, Input, message } from 'ant-design-vue';
import { Button, Checkbox, Form, FormItem, Input, message } from 'ant-design-vue';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import { auth } from '@/hooks/useAuth';
import { useEffect } from '@/hooks/useEffect';
import styles from './index.module.less';
interface LoginForm {
@@ -10,20 +10,31 @@ interface LoginForm {
password: string;
}
/**
* 登录页
*/
export default defineComponent({
name: 'LoginPage',
setup() {
const router = useRouter();
const loading = ref(false);
const rememberMe = ref(false);
const form = reactive<LoginForm>({
username: 'admin',
password: '123456',
username: '',
password: '',
});
useEffect(() => {
const saved = localStorage.getItem('cpms_login_remember');
if (saved) {
try {
const data = JSON.parse(saved);
form.username = data.username || '';
form.password = data.password || '';
rememberMe.value = true;
} catch {
localStorage.removeItem('cpms_login_remember');
}
}
}, []);
const rules = {
username: [{ required: true, message: '请输入用户名' }],
password: [{ required: true, message: '请输入密码' }],
@@ -37,46 +48,197 @@ export default defineComponent({
loading.value = true;
// TODO: 替换为真实登录接口
// const res = await post<LoginResult>('/login', { ...form });
// auth.login(res.token);
setTimeout(() => {
auth.login('mock_token_' + Date.now());
try {
await new Promise((r) => setTimeout(r, 600));
await auth.login('mock_token_' + Date.now());
message.success('登录成功');
if (rememberMe.value) {
localStorage.setItem(
'cpms_login_remember',
JSON.stringify({
username: form.username,
password: form.password,
}),
);
} else {
localStorage.removeItem('cpms_login_remember');
}
} catch (err) {
message.error('登录失败,请重试');
} finally {
loading.value = false;
router.push('/dashboard');
}, 600);
}
};
const particles = [
{ top: '8%', left: '15%', delay: '0s', duration: '8s' },
{ top: '22%', left: '65%', delay: '1.5s', duration: '7s' },
{ top: '45%', left: '25%', delay: '0.8s', duration: '9s' },
{ top: '60%', left: '75%', delay: '2s', duration: '6.5s' },
{ top: '75%', left: '40%', delay: '3s', duration: '8.5s' },
{ top: '15%', left: '80%', delay: '1s', duration: '7.5s' },
{ top: '35%', left: '50%', delay: '2.5s', duration: '6s' },
{ top: '85%', left: '20%', delay: '0.5s', duration: '9.5s' },
{ top: '50%', left: '90%', delay: '3.5s', duration: '8s' },
{ top: '92%', left: '55%', delay: '1.2s', duration: '7s' },
];
return () => (
<div class={styles.container}>
<Card class={styles.card} title="CPMS 运营平台">
<Form model={form} rules={rules} layout="vertical" onFinish={handleSubmit}>
<FormItem name="username">
<Input
v-model={[form.username, 'value']}
placeholder="用户名"
size="large"
v-slots={{ prefix: () => <UserOutlined /> }}
<div class={styles.brand}>
<div class={styles.orb1} />
<div class={styles.orb2} />
<div class={styles.orb3} />
<div class={styles.pulse} />
<div class={styles.brandGrid} />
<div class={styles.scanLine} />
<div class={styles.particles}>
{particles.map((p, i) => (
<div
key={i}
class={styles.particle}
style={{
top: p.top,
left: p.left,
animationDelay: p.delay,
animationDuration: p.duration,
}}
/>
</FormItem>
<FormItem name="password">
<Input
v-model={[form.password, 'value']}
type="password"
placeholder="密码"
size="large"
v-slots={{ prefix: () => <LockOutlined /> }}
/>
</FormItem>
<FormItem>
<Button type="primary" html-type="submit" size="large" block loading={loading.value}>
</Button>
</FormItem>
</Form>
</Card>
))}
</div>
<div class={styles.brandInner}>
<div class={styles.logoRow}>
<div class={styles.logoMark}>6</div>
<span class={styles.logoText}></span>
</div>
<h1 class={styles.brandTitle}></h1>
<p class={styles.brandSubtitle}>
</p>
<div class={styles.statsRow}>
<div class={styles.statItem}>
<span class={styles.statValue}>
<span class={styles.statHighlight}>1,200</span>+
</span>
<span class={styles.statLabel}></span>
</div>
<div class={styles.statItem}>
<span class={styles.statValue}>
<span class={styles.statHighlight}>50,000</span>+
</span>
<span class={styles.statLabel}></span>
</div>
<div class={styles.statItem}>
<span class={styles.statValue}>
<span class={styles.statHighlight}>100</span>%
</span>
<span class={styles.statLabel}></span>
</div>
</div>
<div class={styles.eventCards}>
<div class={styles.eventCard}>
<div class={[styles.eventIcon, styles.blue]}>📋</div>
<div class={styles.eventTitle}></div>
<div class={styles.eventDesc}>线</div>
</div>
<div class={styles.eventCard}>
<div class={[styles.eventIcon, styles.green]}>🏆</div>
<div class={styles.eventTitle}></div>
<div class={styles.eventDesc}></div>
</div>
<div class={styles.eventCard}>
<div class={[styles.eventIcon, styles.orange]}>📊</div>
<div class={styles.eventTitle}></div>
<div class={styles.eventDesc}></div>
</div>
</div>
<div class={styles.flowSteps}>
<div class={styles.step}>
<span class={styles.stepDot} />
<span class={styles.stepLabel}></span>
</div>
<div class={styles.stepLine} />
<div class={styles.step}>
<span class={styles.stepDot} />
<span class={styles.stepLabel}></span>
</div>
<div class={styles.stepLine} />
<div class={styles.step}>
<span class={styles.stepDot} />
<span class={styles.stepLabel}></span>
</div>
<div class={styles.stepLine} />
<div class={styles.step}>
<span class={styles.stepDot} />
<span class={styles.stepLabel}></span>
</div>
<div class={styles.stepLine} />
<div class={styles.step}>
<span class={styles.stepDot} />
<span class={styles.stepLabel}></span>
</div>
</div>
<div class={styles.brandFooter}> ©{new Date().getFullYear()}</div>
</div>
</div>
<div class={styles.loginSide}>
<div class={styles.loginWrapper}>
<h2 class={styles.loginTitle}></h2>
<p class={styles.loginDesc}></p>
<Form
class={styles.loginForm}
model={form}
rules={rules}
layout="vertical"
onFinish={handleSubmit}
>
<FormItem name="username">
<Input
v-model={[form.username, 'value']}
placeholder="请输入用户名"
size="large"
v-slots={{ prefix: () => <UserOutlined /> }}
/>
</FormItem>
<FormItem name="password">
<Input
v-model={[form.password, 'value']}
type="password"
placeholder="请输入密码"
size="large"
v-slots={{ prefix: () => <LockOutlined /> }}
/>
</FormItem>
{/* 记住密码 */}
<div class={styles.rememberRow}>
<Checkbox v-model={[rememberMe.value, 'checked']}></Checkbox>
</div>
<FormItem>
<Button
class={styles.loginBtn}
type="primary"
htmlType="submit"
size="large"
block
loading={loading.value}
>
</Button>
</FormItem>
</Form>
<div class={styles.loginFooter}> ©{new Date().getFullYear()}</div>
</div>
</div>
</div>
);
},
@@ -10,7 +10,7 @@ export default defineComponent({
setup() {
const router = useRouter();
const goHome = () => router.push('/');
const goHome = () => router.push('/login');
return () => (
<Result
+15
View File
@@ -0,0 +1,15 @@
import { defineComponent } from 'vue';
/**
* 角色权限
*/
export default defineComponent({
name: 'SystemRoles',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
},
});
+15
View File
@@ -0,0 +1,15 @@
import { defineComponent } from 'vue';
/**
* 用户管理
*/
export default defineComponent({
name: 'SystemUsers',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
},
});
+14
View File
@@ -0,0 +1,14 @@
// @ts-nocheck
/**
* Vite import.meta.glob 动态收集所有页面组件
*
* TS 不理解 import.meta.glob 的 glob 模式语法(含 **),
* 所以整个文件禁用类型检查。
* Vite 在构建时会正确处理 glob 模式并生成对应的动态 import。
*
* 返回格式: { '/src/pages/dashboard/index.tsx': () => Promise<Module> }
* 新增页面只需在 src/pages/ 下创建目录和 index.tsx,无需修改映射表。
*/
const pageModules = import.meta.glob('/src/pages/**/index.tsx');
export { pageModules };
+53
View File
@@ -0,0 +1,53 @@
import router from '@/router';
import { auth } from '@/hooks/useAuth';
/**
* 全局路由守卫
* 核心流程:
* 1. /login → 已登录则跳首页,未登录则放行
* 2. 未登录 → 跳转 /login
* 3. 已登录但菜单未加载 → 加载菜单+权限 → 重新导航(确保动态路由生效)
* 4. 已登录且菜单已加载 → 放行
*
* 关键:当 loadMenu 动态注册路由后,必须用 next({ path, replace: true })
* 重新触发导航,否则当前导航仍使用旧路由表,会匹配到 404。
* 注意:不能用 next({ ...to, replace: true }),因为展开 to 会把旧的
* matched 信息带过去,导致仍然匹配到 /:pathMatch(.*)*。
*/
router.beforeEach(async (to, _from, next) => {
// 设置页面标题
const appTitle = import.meta.env.VITE_APP_TITLE || 'CPMS 运营平台';
document.title = to.meta.title ? `${to.meta.title} - ${appTitle}` : appTitle;
// ── /login 特殊处理 ──
if (to.path === '/login') {
if (auth.isLoggedIn()) {
const { homePath } = await import('@/stores/menuStore').then((m) => m.useMenuStore());
next(homePath.value);
} else {
next();
}
return;
}
// ── 未登录 → 跳转登录页 ──
if (!auth.isLoggedIn()) {
next('/login');
return;
}
// ── 已登录:确保菜单和动态路由已加载 ──
const { loadMenu, loaded } = await import('@/stores/menuStore').then((m) => m.useMenuStore());
if (!loaded.value) {
const { loadPermissions } = await import('@/stores/permissionStore').then((m) =>
m.usePermissionStore(),
);
await Promise.all([loadMenu(), loadPermissions()]);
// 动态路由刚注册,需要用新路由表重新匹配当前路径
next({ path: to.fullPath, replace: true });
return;
}
next();
});
+25 -28
View File
@@ -1,40 +1,37 @@
import { createRouter, createWebHistory } from 'vue-router';
import { routes } from './routes';
import { auth } from '@/hooks/useAuth';
import { constantRoutes } from './routes';
const router = createRouter({
history: createWebHistory(import.meta.env.VITE_BASE_URL || '/'),
routes,
routes: constantRoutes,
scrollBehavior: () => ({ left: 0, top: 0 }),
});
// 路由守卫:登录鉴权 + 页面标题
router.beforeEach((to, _from, next) => {
const isLoggedIn = auth.isLoggedIn();
/**
* 路由白名单:不需要登录即可访问的路径
*/
const WHITE_LIST = ['/login', '/404'];
// 设置页面标题
const appTitle = import.meta.env.VITE_APP_TITLE || 'CPMS 运营平台';
document.title = to.meta.title ? `${to.meta.title} - ${appTitle}` : appTitle;
/**
* 静态路由名称集合(这些路由不会被 resetRouter 移除)
*/
const STATIC_ROUTE_NAMES = new Set(['Login', 'NotFound']);
// 如果访问的是登录页
if (to.path === '/login') {
if (isLoggedIn) {
// 已登录则重定向到首页
next('/dashboard');
} else {
// 未登录则允许访问登录页
next();
/**
* 重置路由:清除动态添加的路由(包括 BasicLayout 和其子路由),
* 恢复到只包含静态路由的状态。用于退出登录时清理。
*/
export function resetRouter() {
const currentRoutes = router.getRoutes();
currentRoutes.forEach((route) => {
const routeName = route.name as string;
// 保留静态路由(Login, NotFound),移除所有动态路由(含 BasicLayout 及其子路由)
if (routeName && !STATIC_ROUTE_NAMES.has(routeName)) {
router.removeRoute(routeName);
}
} else {
// 访问其他页面
if (isLoggedIn) {
// 已登录则允许访问
next();
} else {
// 未登录则重定向到登录页
next('/login');
}
}
});
});
}
export default router;
export { WHITE_LIST };
+10 -48
View File
@@ -1,34 +1,16 @@
import type { RouteRecordRaw } from 'vue-router';
import { createRoute } from './utils';
/**
* ====== 业务路由模块 ======
* 实际项目中按模块拆分,如 eventsRoutes、walletRoutes 等,
* 然后在下方 routes 数组的布局 children 中引入。
* 参考示例(嵌套路由):
* ====== 静态路由(不需要后端下发) ======
* 登录页、404 等不依赖权限的页面写在这里。
* 动态路由由 menuStore 在登录后通过 router.addRoute 注入,
* 后端下发 MenuNode 包含 component 字段,
* 前端通过 import.meta.glob 动态匹配 src/pages 下的组件。
*
* const eventsRoutes = {
* path: '/events',
* name: 'EventsModule',
* redirect: '/events/list',
* meta: { title: '我的赛事', activeMenu: '/events' },
* children: [
* createRoute('list', () => import('@/pages/events/list'), { title: '赛事列表' }),
* {
* path: 'bracket',
* name: 'BracketPage',
* component: () => import('@/pages/events/bracket'),
* meta: { title: '赛事详情' },
* children: [
* createRoute('player-management', () => import('@/pages/events/bracket/player-management'), { title: '选手管理' }),
* createRoute('match-result', () => import('@/pages/events/bracket/match-result'), { title: '比赛结果' }),
* ],
* },
* ],
* };
* 注意: BasicLayout 路由不在此注册,而是由 menuStore 动态添加,
* 这样可以避免空 children 导致的路由匹配问题。
*/
export const routes: RouteRecordRaw[] = [
export const constantRoutes: RouteRecordRaw[] = [
// ── 登录页(不经过布局)──
{
path: '/login',
@@ -37,32 +19,12 @@ export const routes: RouteRecordRaw[] = [
meta: { title: '登录' },
},
// ── 主布局(需要登录)──
{
path: '/',
component: () => import('@/layouts/BasicLayout'),
children: [
// 业务模块路由在此添加,例如:eventsRoutes, walletRoutes
createRoute('/dashboard', () => import('@/views/Dashboard'), {
title: '工作台',
icon: 'DashboardOutlined',
}),
createRoute('/about', () => import('@/views/About'), {
title: '关于',
icon: 'InfoCircleOutlined',
}),
// 默认重定向
{ path: '/', redirect: '/dashboard' },
],
},
// ── 404 ──
// 注意: 通配路由必须放在最后,且不能被动态路由覆盖
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound'),
component: () => import('@/pages/not-found'),
meta: { title: '页面不存在' },
},
];
+272
View File
@@ -0,0 +1,272 @@
import { reactive, computed, toRefs } from 'vue';
import type { RouteRecordRaw } from 'vue-router';
import type { MenuNode, MenuItemRaw } from '@/types';
import router, { resetRouter } from '@/router';
import { fetchMenuTree } from '@/api/menu';
import { pageModules } from '@/router/glob';
import { FALLBACK_MENU_NODES } from '@/config/fallbackRoutes';
/**
* 使用 import.meta.glob 动态收集 src/pages/ 下所有页面组件
* (实际 glob 逻辑在 @/router/glob.ts 中,因为 TS 不支持 glob 语法)
*
* 后端下发 component 字段(如 'dashboard')时,
* 前端自动匹配到 '/src/pages/dashboard/index.tsx' 的懒加载函数。
*
* 扩展新页面时只需在 src/pages/ 下创建目录和 index.tsx,
* 不需要修改任何映射表。
*/
/**
* 将后端的 component 字段解析为 vite 动态 import 函数
* 'dashboard' → 匹配 '/src/pages/dashboard/index.tsx'
* 'events/list' → 匹配 '/src/pages/events/list/index.tsx'
*/
function resolveComponent(component?: string): RouteRecordRaw['component'] | undefined {
if (!component) return undefined;
const globKey = `/src/pages/${component}/index.tsx`;
if (pageModules[globKey]) {
return pageModules[globKey];
}
const aliasKey = `@/pages/${component}/index.tsx`;
if (pageModules[aliasKey]) {
return pageModules[aliasKey];
}
console.warn(`[路由] 未找到页面组件: ${component} (globKey: ${globKey})`);
return undefined;
}
interface MenuState {
/** 后端下发的原始菜单树 */
menuTree: MenuNode[];
/** 转换后的 antd Menu items */
menuItems: MenuItemRaw[];
/** 是否已加载(登录后只加载一次) */
loaded: boolean;
/** 首页路径(第一个可见菜单的 path) */
homePath: string;
}
const state = reactive<MenuState>({
menuTree: [],
menuItems: [],
loaded: false,
homePath: '/dashboard',
});
// ============================================================
// 辅助函数
// ============================================================
/**
* 获取节点的可用子节点(排除 disabled 和 externalLink
*/
function getEnabledChildren(node: MenuNode): MenuNode[] {
if (!node.children?.length) return [];
return node.children.filter((child) => !child.disabled && !child.externalLink);
}
/**
* 将后端 MenuNode 递归转为 antd Menu 的 items 格式
*
* 规则:
* - 过滤 disabled / hideInMenu / externalLink 节点
* - 父节点有 enabledChildren 时递归转换;若所有子节点都被过滤且父节点无 component,则父节点也不显示
* - key 统一加 '/' 前缀,与 route.path 匹配(如 '/dashboard'、'/events/list'
*/
function transformMenuNode(nodes: MenuNode[]): MenuItemRaw[] {
const result: MenuItemRaw[] = [];
for (const node of nodes) {
if (node.disabled || node.hideInMenu || node.externalLink) continue;
const enabledChildren = getEnabledChildren(node);
const item: MenuItemRaw = {
key: '/' + node.path,
label: node.name,
iconName: node.icon,
};
if (enabledChildren.length > 0) {
const childItems = transformMenuNode(enabledChildren);
if (childItems.length > 0) {
item.children = childItems;
}
// 子节点全部被过滤 → 父节点也不显示
else {
continue;
}
}
result.push(item);
}
// 排序
result.sort((a, b) => {
const aNode = nodes.find((n) => '/' + n.path === a.key);
const bNode = nodes.find((n) => '/' + n.path === b.key);
return (aNode?.sort ?? 0) - (bNode?.sort ?? 0);
});
return result;
}
/**
* 将后端 MenuNode 递归转为 vue-router RouteRecordRaw
*
* node.path 存储完整路径(如 'events/list'),
* 但 Vue Router 嵌套路由下子节点的 path 必须相对于父节点(如 'list')。
* 通过 parentPath 参数实现自动剥离前缀。
*
* 规则:
* - 跳过 disabled / externalLink 节点
* - 父节点无 component 且所有子节点被过滤 → 跳过
* - 父节点无 component 时,redirect 自动指向第一个可用子路由(相对路径)
*/
function transformMenuToRoutes(nodes: MenuNode[], parentPath = ''): RouteRecordRaw[] {
const routes: RouteRecordRaw[] = [];
for (const node of nodes) {
if (node.disabled || node.externalLink) continue;
const enabledChildren = getEnabledChildren(node);
const componentLoader = resolveComponent(node.component);
// 无组件且无可用子节点 → 跳过
if (!componentLoader && enabledChildren.length === 0) continue;
// 计算 Vue Router 路由 path: 根节点用完整路径,子节点剥离父级前缀
const routePath = parentPath
? node.path.slice(parentPath.length + 1) // 'events/list' → 'list'
: node.path;
const route: RouteRecordRaw = {
path: routePath,
name: node.name,
meta: {
title: node.name,
icon: node.icon,
hideInMenu: node.hideInMenu,
activeMenu: node.activeMenu,
externalLink: node.externalLink,
},
} as RouteRecordRaw;
if (componentLoader) {
route.component = componentLoader;
}
if (enabledChildren.length > 0) {
// 递归时传入当前节点的完整路径作为父级前缀
route.children = transformMenuToRoutes(enabledChildren, node.path);
// 无组件的父节点 → redirect 指向第一个可用子路由(相对路径)
if (!componentLoader) {
const firstChildRelativePath = enabledChildren[0].path.slice(node.path.length + 1);
route.redirect = firstChildRelativePath;
}
}
routes.push(route);
}
return routes;
}
/**
* 获取第一个可见菜单的路径(用作默认首页)
* 跳过 disabled / hideInMenu / externalLink 节点
* 返回带 '/' 前缀的完整路径
*/
function getFirstMenuPath(nodes: MenuNode[]): string {
for (const node of nodes) {
if (node.disabled || node.externalLink) continue;
const enabledChildren = getEnabledChildren(node);
if (!node.hideInMenu && enabledChildren.length === 0) {
return '/' + node.path;
}
if (enabledChildren.length > 0) {
const childPath = getFirstMenuPath(enabledChildren);
if (childPath) return childPath;
}
}
return '/dashboard';
}
/**
* 注册 BasicLayout 布局路由(如果不存在)
* 动态路由作为其子路由挂载
*/
function ensureLayoutRoute() {
if (!router.hasRoute('BasicLayout')) {
router.addRoute({
path: '/',
name: 'BasicLayout',
component: () => import('@/layouts/BasicLayout'),
children: [],
meta: { title: '首页' },
});
}
}
/**
* 通用"注入路由 + 菜单"流程
* 无论是后端数据还是兜底数据,都走同一套 logic
*/
function applyMenuTree(menuTree: MenuNode[]) {
state.menuTree = menuTree;
state.menuItems = transformMenuNode(menuTree);
state.homePath = getFirstMenuPath(menuTree);
ensureLayoutRoute();
const dynamicRoutes = transformMenuToRoutes(menuTree);
dynamicRoutes.forEach((route) => {
router.addRoute('BasicLayout', route);
});
// 默认重定向到首页
router.addRoute('BasicLayout', { path: '', redirect: state.homePath });
}
// ============================================================
// 暴露给组件使用的 composable
// ============================================================
export function useMenuStore() {
const loadMenu = async () => {
if (state.loaded) return;
try {
const menuTree = await fetchMenuTree();
applyMenuTree(menuTree);
state.loaded = true;
} catch (err) {
console.error('加载菜单失败:', err);
// 降级:使用本地兜底菜单
applyMenuTree(FALLBACK_MENU_NODES);
state.loaded = true;
}
};
const clearMenu = () => {
resetRouter();
state.menuTree = [];
state.menuItems = [];
state.loaded = false;
state.homePath = '/dashboard';
};
return {
...toRefs(state),
menuTree: computed(() => state.menuTree),
menuItems: computed(() => state.menuItems),
loaded: computed(() => state.loaded),
homePath: computed(() => state.homePath),
loadMenu,
clearMenu,
};
}
+66
View File
@@ -0,0 +1,66 @@
import { reactive, computed, toRefs } from 'vue';
import type { PermissionCode } from '@/types';
import { fetchPermissions } from '@/api/menu';
interface PermissionState {
/** 权限编码集合 */
codes: Set<PermissionCode>;
/** 是否已加载 */
loaded: boolean;
}
const state = reactive<PermissionState>({
codes: new Set(),
loaded: false,
});
export function usePermissionStore() {
/**
* 从后端加载权限编码
*/
const loadPermissions = async () => {
if (state.loaded) return;
try {
const codes = await fetchPermissions();
state.codes = new Set(codes);
state.loaded = true;
} catch (err) {
console.error('加载权限失败:', err);
state.codes = new Set();
state.loaded = true;
}
};
/**
* 清除权限(退出登录时调用)
*/
const clearPermissions = () => {
state.codes = new Set();
state.loaded = false;
};
/**
* 判断是否拥有某个权限
* @param code 权限编码,如 'user:delete'
*/
const hasPermission = (code: PermissionCode): boolean => {
return state.codes.has(code);
};
/**
* 判断是否拥有任意一个权限
*/
const hasAnyPermission = (codes: PermissionCode[]): boolean => {
return codes.some((code) => state.codes.has(code));
};
return {
...toRefs(state),
loaded: computed(() => state.loaded),
loadPermissions,
clearPermissions,
hasPermission,
hasAnyPermission,
};
}
+4
View File
@@ -0,0 +1,4 @@
declare module 'china-area-data' {
const data: Record<string, Record<string, string>>;
export default data;
}
+59
View File
@@ -23,6 +23,63 @@ export interface SelectOption {
disabled?: boolean;
}
// ── 菜单 & 权限 ──
/**
* 后端下发的路由/菜单节点
* 后端接口返回完整的路由配置树,包含 path、component、meta 等,
* 前端根据 component 字段通过 import.meta.glob 动态加载对应页面组件,
* 不需要前端维护组件映射表。
*/
export interface MenuNode {
/** 菜单唯一标识 */
id: number | string;
/** 菜单/路由名称(同时作为 route.name) */
name: string;
/** 路由路径(如 /dashboard、/events/list) */
path: string;
/**
* 组件路径(对应 src/pages/ 下的目录名)
* 例如: 'dashboard' → import('@/pages/dashboard')
* 例如: 'events/list' → import('@/pages/events/list')
* 留空或省略 → 纯布局节点(自动重定向到第一个子路由)
*/
component?: string;
/** 菜单图标(antd icon 名,如 DashboardOutlined) */
icon?: string;
/** 排序权重(越小越靠前) */
sort?: number;
/** 是否在菜单中隐藏(如详情页、编辑页不需要在侧边栏显示) */
hideInMenu?: boolean;
/** 外链地址(有值时点击跳转外部 URL,不注册内部路由) */
externalLink?: string;
/** 高亮的菜单路径(用于详情页高亮父级菜单) */
activeMenu?: string;
/** 是否禁用(禁用后路由不注册、菜单不显示) */
disabled?: boolean;
/** 子菜单/子路由 */
children?: MenuNode[];
}
/**
* 菜单项(用于 antd Menu 组件渲染)
*/
export interface MenuItemRaw {
key: string;
icon?: any;
/** antd icon 名称字符串,用于动态解析图标 */
iconName?: string;
label: string;
children?: MenuItemRaw[];
}
/**
* 权限编码
* 后端下发的权限标识列表,用于按钮/操作级权限控制
* 使用方式: v-if="hasPermission('user:delete')"
*/
export type PermissionCode = string;
/** 路由 meta 扩展(与 router/utils.ts 的 AppMeta 保持一致) */
declare module 'vue-router' {
interface RouteMeta {
@@ -38,5 +95,7 @@ declare module 'vue-router' {
activeMenu?: string;
/** 权限标识 */
permission?: string;
/** 外链地址 */
externalLink?: string;
}
}
+33
View File
@@ -0,0 +1,33 @@
import areaData from 'china-area-data';
export interface CascadeOption {
value: string;
label: string;
children?: CascadeOption[];
}
/**
* 将 china-area-data 原始数据转换为 antd Cascader 所需的 options 格式
*
* 原始数据格式: { '86': { '110000': '北京' }, '110000': { '110100': '市辖区' }, ... }
* 目标格式: [{ value: '110000', label: '北京', children: [...] }]
*/
function buildTree(parentCode: string): CascadeOption[] {
const nodes = areaData[parentCode];
if (!nodes) return [];
return Object.entries(nodes).map(([code, name]) => {
const node: CascadeOption = {
value: code,
label: name as string,
};
const children = buildTree(code);
if (children.length > 0) {
node.children = children;
}
return node;
});
}
/** 省市区三级联动数据 */
export const regionOptions: CascadeOption[] = buildTree('86');
+121
View File
@@ -0,0 +1,121 @@
import type { OssSignData } from '@/api/upload';
import { fetchOssSign } from '@/api/upload';
/**
* OSS 上传类型
* 1=证件照 2=赛事封面 3=头像 4=富文本 5=Banner
*/
export const OssUploadType = {
IdCard: '1',
EventCover: '2',
Avatar: '3',
RichText: '4',
Banner: '5',
} as const;
export type OssUploadTypeValue = (typeof OssUploadType)[keyof typeof OssUploadType];
/**
* 生成唯一文件名:16 位大小写字母+数字随机串.ext
*/
export function genFileName(filePath: string, fileName?: string): string {
let suffix = '';
if (fileName) {
const dot = fileName.lastIndexOf('.');
suffix = dot >= 0 ? fileName.slice(dot).toLowerCase() : '';
}
if (!suffix && filePath) {
const dot = filePath.lastIndexOf('.');
suffix = dot >= 0 ? filePath.slice(dot).toLowerCase() : '';
}
if (!suffix) suffix = '.jpg';
const random = Array.from({ length: 16 }, () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return chars.charAt(Math.floor(Math.random() * chars.length));
}).join('');
return `${random}${suffix}`;
}
/** 根据签名和文件名构建 OSS 上传 FormData 字段 */
export function buildOssFormData(sign: OssSignData, fileName: string): Record<string, string> {
return {
key: `${sign.dir}${fileName}`,
policy: sign.policy,
'x-oss-signature': sign.signature,
'x-oss-signature-version': 'OSS4-HMAC-SHA256',
'x-oss-credential': sign.x_oss_credential,
'x-oss-date': sign.x_oss_date,
'x-oss-security-token': sign.security_token,
success_action_status: '200',
};
}
/**
* 使用已有签名上传单个文件到 OSSWeb 版,fetch + FormData
*/
export async function uploadFileWithSign(file: File, sign: OssSignData): Promise<string> {
const fileName = genFileName(file.name, file.name);
const key = `${sign.dir}${fileName}`;
const formData = new FormData();
Object.entries(buildOssFormData(sign, fileName)).forEach(([k, v]) => {
formData.append(k, v);
});
formData.append('file', file);
const res = await fetch(sign.host, {
method: 'POST',
body: formData,
});
if (!res.ok) {
throw new Error(`OSS 上传失败:${res.status} ${res.statusText}`);
}
return `${sign.host}/${key}`;
}
/**
* 上传单个文件到 OSS
* @returns 文件访问 URL
*/
export async function uploadFile(file: File, type: OssUploadTypeValue): Promise<{ url: string }> {
const sign = await fetchOssSign(type);
const url = await uploadFileWithSign(file, sign);
return { url };
}
/**
* 逐张上传文件到 OSS(同一批复用同一签名,单张失败不影响后续)
*/
export async function uploadFilesOneByOne(
files: File[],
type: OssUploadTypeValue,
options?: {
onSuccess?: (url: string, index: number) => void | Promise<void>;
onError?: (error: unknown, index: number) => void;
},
): Promise<{ successCount: number; failCount: number }> {
if (files.length === 0) {
return { successCount: 0, failCount: 0 };
}
const sign = await fetchOssSign(type);
let successCount = 0;
let failCount = 0;
for (let i = 0; i < files.length; i++) {
try {
const url = await uploadFileWithSign(files[i], sign);
successCount++;
await options?.onSuccess?.(url, i);
} catch (err) {
failCount++;
options?.onError?.(err, i);
}
}
return { successCount, failCount };
}
-131
View File
@@ -1,131 +0,0 @@
#!/usr/bin/env node
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const readline = require('readline');
function loadEnv(filePath) {
if (!fs.existsSync(filePath)) return {};
const content = fs.readFileSync(filePath, 'utf8');
const env = {};
content.split('\n').forEach((line) => {
const match = line.match(/^([^=:#]+?)=(.*)$/);
if (match) {
env[match[1].trim()] = match[2].trim().replace(/^['"](.*)['"]$/, '$1');
}
});
return env;
}
function getComponentLibs(env) {
const libs = [];
libs.push({
name: 'cpms_web_component (默认)',
path: path.resolve(__dirname, '../cpms_web_component'),
useKey: null,
usePath: null,
});
for (const key in env) {
if (key.startsWith('COMPONENT_LIB_') && key !== 'COMPONENT_LIB_PATH') {
libs.push({
name: key.replace('COMPONENT_LIB_', ''),
path: path.resolve(__dirname, env[key]),
useKey: key.replace('COMPONENT_LIB_', ''),
usePath: null,
});
}
}
if (env.COMPONENT_LIB_PATH) {
libs.push({
name: '自定义路径',
path: path.resolve(__dirname, env.COMPONENT_LIB_PATH),
useKey: null,
usePath: env.COMPONENT_LIB_PATH,
});
}
return libs;
}
async function selectLib(libs) {
if (libs.length === 1) return libs[0];
console.log('📦 请选择要使用的组件库:');
libs.forEach((lib, i) => {
const exists = fs.existsSync(lib.path) ? '✅' : '❌';
console.log(` ${i + 1}. ${lib.name} ${exists}`);
console.log(` ${lib.path}`);
});
console.log(' 0. 使用 npm 版本');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve) => {
rl.question(`\n请输入选项 (0-${libs.length},回车默认): `, (answer) => {
rl.close();
if (answer === '0') resolve(null);
else if (answer && /^\d+$/.test(answer)) {
const idx = parseInt(answer) - 1;
resolve(idx >= 0 && idx < libs.length ? libs[idx] : libs[0]);
} else {
resolve(libs[0]);
}
});
});
}
async function main() {
const localEnv = loadEnv(path.resolve(__dirname, '.env.local'));
const libs = getComponentLibs(localEnv);
console.log('🚀 启动本地调试模式...\n');
const selected = await selectLib(libs);
const mergedEnv = { ...process.env, ...localEnv, LOCAL_DEBUG: 'true' };
if (!selected) {
console.log('\n📦 使用 npm 版本');
delete mergedEnv.COMPONENT_LIB;
delete mergedEnv.COMPONENT_LIB_PATH;
} else {
const exists = fs.existsSync(selected.path);
if (!exists) {
console.warn(`\n⚠️ 组件库不存在: ${selected.name}`);
console.warn(` ${selected.path}`);
console.warn(' 将使用 npm 版本');
delete mergedEnv.COMPONENT_LIB;
delete mergedEnv.COMPONENT_LIB_PATH;
} else {
console.log(`\n📦 ${selected.name}`);
console.log(`📍 ${selected.path}`);
if (selected.useKey) {
mergedEnv.COMPONENT_LIB = selected.useKey;
delete mergedEnv.COMPONENT_LIB_PATH;
} else if (selected.usePath) {
mergedEnv.COMPONENT_LIB_PATH = selected.usePath;
delete mergedEnv.COMPONENT_LIB;
} else {
delete mergedEnv.COMPONENT_LIB;
delete mergedEnv.COMPONENT_LIB_PATH;
}
}
}
console.log('\n⏳ 启动 Vite...\n');
try {
execSync('npx vite --port 3000 --open --strictPort false', {
stdio: 'inherit',
cwd: process.cwd(),
env: mergedEnv,
});
} catch (error) {
console.error('❌ 启动失败:', error.message);
process.exit(1);
}
}
main();
+30 -5
View File
@@ -1,15 +1,28 @@
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import removeConsole from 'vite-plugin-remove-console';
import strip from '@rollup/plugin-strip';
import { resolve } from 'path';
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
const isProd = mode === 'production';
return {
base: env.VITE_BASE_URL || '/',
plugins: [vue(), vueJsx()],
plugins: [
vue(),
vueJsx(),
// 生产构建:移除 console.log / console.warn / console.error
isProd && removeConsole(),
// 生产构建:移除代码中的注释
isProd &&
strip({
include: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
}),
].filter(Boolean),
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
@@ -27,7 +40,8 @@ export default defineConfig(({ mode }) => {
},
server: {
host: '0.0.0.0',
port: Number(env.VITE_PORT) || 5173,
port: 3000,
strictPort: false,
open: true,
proxy: {
'/api': {
@@ -40,12 +54,23 @@ export default defineConfig(({ mode }) => {
build: {
outDir: 'dist',
sourcemap: mode !== 'production',
// 生产构建移除 console 和注释(esbuild minify 阶段)
minify: isProd ? 'esbuild' : false,
chunkSizeWarningLimit: 1500,
rollupOptions: {
output: {
manualChunks: {
vue: ['vue', 'vue-router'],
antd: ['ant-design-vue'],
// 更细粒度的分包,确保按需加载
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('ant-design-vue') || id.includes('@ant-design')) {
return 'antd';
}
if (id.includes('vue') || id.includes('@vue') || id.includes('vue-router')) {
return 'vue-vendor';
}
// 其他第三方依赖单独打包,未使用的不会进入
return 'vendor';
}
},
},
},