13 Commits

Author SHA1 Message Date
cst 2e7f9a1ceb feat: 财务管理页面编写 2026-07-27 14:57:48 +08:00
cst 9c2dc49d8d feat: 财务管理页面编写 2026-07-27 14:56:44 +08:00
chenzhen 0e0e1e300a Merge pull request 'feature/0723/ZR' (#1) from feature/0723/ZR into release/0.01
Reviewed-on: #1
2026-07-27 10:44:40 +08:00
ZhuRui e238328919 fix: 页面表格容器高度计算优化 2026-07-27 10:19:45 +08:00
ZhuRui 471d868634 fix: 订单管理样式更新 2026-07-27 10:10:03 +08:00
ZhuRui 4c7a0709a4 fix: 处理页面title闪烁问题 2026-07-27 10:06:45 +08:00
ZhuRui 7b6fd59023 fix: 弹窗优化 2026-07-27 10:00:12 +08:00
ZhuRui e3e66ec03b fix: 优化watch 修改编辑用户弹窗样式 2026-07-27 09:51:30 +08:00
ZhuRui 17d5c85904 fix: 依赖更新 2026-07-27 09:14:41 +08:00
ZhuRui 6e1fc98c71 fix: 删除没有必要的wxss 2026-07-27 09:11:54 +08:00
ZhuRui b852754ca6 feat: 图片裁剪功能更新 2026-07-27 09:03:46 +08:00
ZhuRui b86c22e7d2 feat: 补全赛事管理下所有页面 补全系统管理下所有页面 2026-07-25 18:00:22 +08:00
ZhuRui 34d9a778a8 feat: 优化 banner 配置页面 添加图片裁剪 2026-07-25 14:55:56 +08:00
60 changed files with 5651 additions and 565 deletions
+3 -1
View File
@@ -5,7 +5,7 @@
"private": true,
"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",
@@ -18,9 +18,11 @@
},
"dependencies": {
"@ant-design/icons-vue": "^7.0.1",
"@yp-component/root": "^0.0.48",
"ant-design-vue": "^4.0.0",
"china-area-data": "^5.0.1",
"dayjs": "^1.11.21",
"echarts": "^5.6.0",
"express": "^5.2.1",
"html2canvas": "^1.4.1",
"qs": "^6.15.0",
+21
View File
@@ -11,12 +11,18 @@ importers:
'@ant-design/icons-vue':
specifier: ^7.0.1
version: 7.0.1(vue@3.5.40(typescript@5.9.3))
'@yp-component/root':
specifier: ^0.0.48
version: 0.0.48(typescript@5.9.3)
ant-design-vue:
specifier: ^4.0.0
version: 4.2.6(vue@3.5.40(typescript@5.9.3))
china-area-data:
specifier: ^5.0.1
version: 5.0.1
cropperjs:
specifier: ^1.6.2
version: 1.6.2
dayjs:
specifier: ^1.11.21
version: 1.11.21
@@ -839,6 +845,9 @@ packages:
'@vue/shared@3.5.40':
resolution: {integrity: sha512-WxnBtruIqOoV3rA4jeKDWzrYI5h7Cp4+pjwDi8kWGHz+IslhiN+wguLVVhtv2l8VoU02rzDCVfDjgCl1lNpZVg==}
'@yp-component/root@0.0.48':
resolution: {integrity: sha512-TOp8adAob3pMSfecQjEC4uVNCGqNWcShDjSQysd4pYY34i5ldFLRGSiJdpLsFG1xKkcSudiqEc/Si/ZfYoDSqA==}
accepts@2.0.0:
resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
engines: {node: '>= 0.6'}
@@ -1063,6 +1072,9 @@ packages:
typescript:
optional: true
cropperjs@1.6.2:
resolution: {integrity: sha512-nhymn9GdnV3CqiEHJVai54TULFAE3VshJTXSqSJKa8yXAKyBKDWdhHarnlIPrshJ0WMFTGuFvG02YjLXfPiuOA==}
cross-spawn@7.0.6:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
@@ -3025,6 +3037,13 @@ snapshots:
'@vue/shared@3.5.40': {}
'@yp-component/root@0.0.48(typescript@5.9.3)':
dependencies:
cropperjs: 1.6.2
vue: 3.5.40(typescript@5.9.3)
transitivePeerDependencies:
- typescript
accepts@2.0.0:
dependencies:
mime-types: 3.0.2
@@ -3251,6 +3270,8 @@ snapshots:
optionalDependencies:
typescript: 5.9.3
cropperjs@1.6.2: {}
cross-spawn@7.0.6:
dependencies:
path-key: 3.1.1
+1
View File
@@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1784966818945" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1689" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64"><path d="M424.19 675.833l64.823 64.823 229.869-229.869-229.869-229.869-64.823 64.823 118.612 119.072H98.236v91.948h444.567L424.19 675.833zM833.817 97.022H190.183c-51.031 0-91.948 41.376-91.948 91.948v183.895h91.948V188.97h643.633v643.633H190.183V648.708H98.236v183.895c0 50.571 40.917 91.948 91.948 91.948h643.633c50.571 0 91.948-41.376 91.948-91.948V188.97c-0.001-50.571-41.377-91.948-91.948-91.948z" p-id="1690"></path></svg>

After

Width:  |  Height:  |  Size: 749 B

-62
View File
@@ -1,62 +0,0 @@
* {
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;
}
@@ -0,0 +1,48 @@
/**
* 修改密码弹窗 - 表单域控制器
*
* 集中管理弹窗内的所有规则与提示文案。
*/
import type { Rule } from 'ant-design-vue/es/form';
import { isValidPassword } from '@/utils/form';
// ============================================================
// 文案
// ============================================================
/** 弹窗底部提示 */
export const TIPS_TEXT = '修改后立即生效,请妥善保管新密码';
// ============================================================
// 表单规则
// ============================================================
/** 新密码规则:必填 + 至少 8 位 + 字母 + 数字 */
export const newPasswordRules: Rule[] = [
{ required: true, message: '请输入新密码' },
{
validator: (_rule: unknown, value: string) => {
if (!value) return Promise.resolve();
if (!isValidPassword(value)) {
return Promise.reject(new Error('密码至少8位,需包含字母与数字'));
}
return Promise.resolve();
},
},
];
/** 确认密码规则:必填 + 必须与新密码一致 */
export function confirmNewPasswordRules(getPassword: () => string): Rule[] {
return [
{ required: true, message: '请再次输入新密码' },
{
validator: (_rule: unknown, value: string) => {
if (!value) return Promise.resolve();
if (value !== getPassword()) {
return Promise.reject(new Error('两次输入的密码不一致'));
}
return Promise.resolve();
},
},
];
}
@@ -0,0 +1,100 @@
import { defineComponent, ref, reactive } from 'vue';
import { useEffect } from '@/hooks';
import { Modal, Form, Input, Button, message } from 'ant-design-vue';
import { TIPS_TEXT, newPasswordRules, confirmNewPasswordRules } from './controller';
import styles from './style.module.less';
interface ChangePasswordModalProps {
visible: boolean;
submitting?: boolean;
onClose: () => void;
/** 提交回调:父组件负责调用 APIloading 状态由 submitting 控制 */
onSave: (payload: { newPassword: string }) => void;
}
/** 默认表单数据 */
const getDefaultForm = () => ({
newPassword: '',
confirmPassword: '',
});
export default defineComponent({
name: 'ChangePasswordModal',
props: {
visible: { type: Boolean, default: false },
submitting: { type: Boolean, default: false },
onClose: { type: Function, required: true },
onSave: { type: Function, required: true },
},
setup(props: ChangePasswordModalProps) {
const formRef = ref<any>();
const formData = reactive(getDefaultForm());
/** 监听 visible 重置表单 */
useEffect(() => {
if (props.visible) {
Object.assign(formData, getDefaultForm());
setTimeout(() => formRef.value?.clearValidate(), 0);
}
}, [() => props.visible]);
/** 提交 */
const handleSubmit = async () => {
try {
await formRef.value?.validate();
} catch {
return;
}
props.onSave({ newPassword: formData.newPassword });
};
const handleClose = () => {
props.onClose();
};
return () => (
<Modal
title="修改密码"
visible={props.visible}
onCancel={handleClose}
width={420}
destroyOnClose
footer={null}
centered
class={styles.modal}
>
<Form ref={formRef} layout="vertical" model={formData} class={styles.form} requiredMark>
<Form.Item label="新密码" name="newPassword" rules={newPasswordRules}>
<Input.Password
placeholder="至少8位,含字母+数字"
allowClear
v-model:value={formData.newPassword}
/>
</Form.Item>
<Form.Item
label="确认新密码"
name="confirmPassword"
rules={confirmNewPasswordRules(() => formData.newPassword)}
>
<Input.Password
placeholder="再次输入新密码"
allowClear
v-model:value={formData.confirmPassword}
/>
</Form.Item>
<div class={styles.tip}>{TIPS_TEXT}</div>
</Form>
{/* 底部按钮 */}
<div class={styles.footer}>
<Button onClick={handleClose}></Button>
<Button type="primary" loading={props.submitting} onClick={handleSubmit}>
</Button>
</div>
</Modal>
);
},
});
@@ -0,0 +1,37 @@
.form {
:global {
.ant-form-item {
margin-bottom: 16px;
}
.ant-form-item-explain-error {
font-size: 12px;
}
}
}
/* 底部提示文案 */
.tip {
margin-top: -4px;
margin-bottom: 24px;
color: rgba(0, 0, 0, 0.45);
font-size: 12px;
line-height: 1.5;
}
/* 底部按钮 */
.footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
border-top: 1px solid #f0f0f0;
}
/* 微调 Modal 内部样式 */
.modal {
:global {
.ant-modal-body {
padding: 16px 24px 0;
}
}
}
+1
View File
@@ -3,3 +3,4 @@
* 在业务中可通过 `import { HelloWorld } from '@/components'` 使用
*/
export { default as HelloWorld } from './HelloWorld';
export { default as ChangePasswordModal } from './ChangePasswordModal';
+4 -3
View File
@@ -1,6 +1,6 @@
// src/hooks/useAuth.ts
import { useState } from './useState';
import { watch } from 'vue';
import { useEffect } from './useEffect';
import { useMenuStore } from '@/stores/menuStore';
import { usePermissionStore } from '@/stores/permissionStore';
import router from '@/router';
@@ -10,13 +10,14 @@ const TOKEN_KEY = 'MY_APP_AUTH_TOKEN';
function createAuth() {
const [token, setToken] = useState<string | null>(window.localStorage.getItem(TOKEN_KEY));
watch(token, (newToken) => {
useEffect(() => {
const newToken = token.value;
if (newToken) {
window.localStorage.setItem(TOKEN_KEY, newToken);
} else {
window.localStorage.removeItem(TOKEN_KEY);
}
});
}, [token]);
const isLoggedIn = () => !!token.value;
+2 -2
View File
@@ -14,10 +14,10 @@ import { ref, onMounted, onUnmounted, type Ref } from 'vue';
* // </div>
* ```
*
* @param headerOffset 从容器高度中扣除的表头偏移量,默认 45
* @param headerOffset 从容器高度中扣除的表头偏移量,默认 55
*/
export function useContainerSize(options?: { headerOffset?: number }) {
const { headerOffset = 45 } = options ?? {};
const { headerOffset = 55 } = options ?? {};
const containerRef = ref<HTMLElement | null>(null) as Ref<HTMLElement | null>;
const width = ref(0);
+6 -3
View File
@@ -1,6 +1,7 @@
// src/hooks/useDebounce.ts
import { watch, onUnmounted, Ref } from 'vue';
import { onUnmounted, Ref } from 'vue';
import { useState } from './useState';
import { useEffect } from './useEffect';
export interface UseDebounceOptions {
delay?: number;
@@ -40,7 +41,7 @@ export function useDebounce<T>(source: Ref<T>, options: number | UseDebounceOpti
isFirstCall = true;
};
watch(source, () => {
useEffect(() => {
setIsPending(true);
// 处理 maxWait
@@ -61,7 +62,9 @@ export function useDebounce<T>(source: Ref<T>, options: number | UseDebounceOpti
updateValue();
}, delay);
}
});
return clearTimers;
}, [source]);
// 卸载
onUnmounted(() => {
+16 -19
View File
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// src/hooks/usePagination.ts
import { computed, ref, watch, Ref, triggerRef } from 'vue';
import { computed, ref, Ref, triggerRef } from 'vue';
import { useEffect } from './useEffect';
/**
* 分页配置项
@@ -77,24 +78,20 @@ export function usePagination(options: UsePaginationOptions = {}): UsePagination
const pageSizeRef = ref(options.pageSize ?? defaultPageSize);
const totalRef = ref(options.total ?? 0);
watch(
() => options.current,
(val) => {
if (val !== undefined) currentRef.value = val;
},
);
watch(
() => options.pageSize,
(val) => {
if (val !== undefined) pageSizeRef.value = val;
},
);
watch(
() => options.total,
(val) => {
if (val !== undefined) totalRef.value = val;
},
);
useEffect(() => {
const val = options.current;
if (val !== undefined) currentRef.value = val;
}, [() => options.current]);
useEffect(() => {
const val = options.pageSize;
if (val !== undefined) pageSizeRef.value = val;
}, [() => options.pageSize]);
useEffect(() => {
const val = options.total;
if (val !== undefined) totalRef.value = val;
}, [() => options.total]);
const totalPages = computed(() => {
const total = totalRef.value;
+22 -23
View File
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { ref, Ref, watch, WatchSource, onUnmounted, computed } from 'vue';
import { ref, Ref, WatchSource, onUnmounted, computed } from 'vue';
import { useEffect } from './useEffect';
export interface UseRequestReturn<T> {
/** 纯净的数据,不包含后端外层壳 */
@@ -128,31 +129,29 @@ export function useRequest<T>(
const shouldAutoRun = computed(() => !manual && ready.value);
let hasAutoRun = false; // 标记是否已自动执行过,防止重复触发
watch(
shouldAutoRun,
(val) => {
if (val && !hasAutoRun) {
hasAutoRun = true;
run();
} else if (!val) {
// 当条件不满足时重置 hasAutoRun,使下次满足条件时能再次自动执行
hasAutoRun = false;
}
},
{ immediate: true },
);
useEffect(() => {
const val = shouldAutoRun.value;
if (val && !hasAutoRun) {
hasAutoRun = true;
run();
} else if (!val) {
// 当条件不满足时重置 hasAutoRun,使下次满足条件时能再次自动执行
hasAutoRun = false;
}
}, [shouldAutoRun]);
// refreshDeps 变化时重新请求(初始化时不再重复触发)
if (refreshDeps && refreshDeps.length > 0) {
watch(
refreshDeps,
() => {
if (shouldAutoRun.value) {
run();
}
},
{ deep: true },
);
let skipInitialRefresh = true;
useEffect(() => {
if (skipInitialRefresh) {
skipInitialRefresh = false;
return;
}
if (shouldAutoRun.value) {
run();
}
}, refreshDeps);
}
const getSignal = () => abortController?.signal;
+12 -9
View File
@@ -1,5 +1,6 @@
import { ref, watch, onBeforeUnmount, toValue } from 'vue';
import { ref, onBeforeUnmount, toValue } from 'vue';
import type { Ref, MaybeRefOrGetter } from 'vue';
import { useEffect } from './useEffect';
// --- 类型定义 ---
export type WebSocketStatus = 'connecting' | 'open' | 'closed' | 'error';
@@ -216,14 +217,16 @@ export function useWebSocket(
// --- 监听与副作用 ---
// 监听 URL 变化,如果变了则重新连接
watch(
() => toValue(url),
() => {
if (status.value !== 'closed') {
connect();
}
},
);
let skipInitialUrlWatch = true;
useEffect(() => {
if (skipInitialUrlWatch) {
skipInitialUrlWatch = false;
return;
}
if (status.value !== 'closed') {
connect();
}
}, [() => toValue(url)]);
// 组件卸载时清理资源
onBeforeUnmount(() => {
+65
View File
@@ -32,6 +32,71 @@
}
}
// 面包屑
.breadcrumb {
flex: 1;
margin-left: 8px;
font-size: 14px;
:global {
.ant-breadcrumb-link,
.ant-breadcrumb-separator,
.ant-breadcrumb-item a {
color: rgba(0, 0, 0, 0.65);
}
.ant-breadcrumb-item:last-child {
.ant-breadcrumb-link,
.ant-breadcrumb-separator,
a {
color: rgba(0, 0, 0, 0.88);
font-weight: 500;
cursor: default;
}
}
}
}
// Header 右侧:账号信息 + 退出图标
.headerRight {
margin-left: auto;
display: flex;
gap: 10px;
align-items: center;
}
.userPhone {
font-size: 14px;
color: rgba(0, 0, 0, 0.65);
}
.logoutIcon {
width: 18px;
height: 18px;
opacity: 0.45;
cursor: pointer;
transition: opacity 0.3s;
&:hover {
opacity: 1;
}
}
// 下拉菜单项:图标 + 文字
.menuItem {
display: inline-flex;
align-items: center;
gap: 8px;
:global(.anticon) {
font-size: 14px;
}
}
.menuItemDanger {
color: #ff4d4f;
}
.content {
margin: 16px;
border-radius: 8px;
-46
View File
@@ -1,46 +0,0 @@
.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;
}
+109 -1
View File
@@ -1,11 +1,13 @@
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 { Layout, Menu, Modal, Breadcrumb, Dropdown, message } from 'ant-design-vue';
import type { MenuProps } from 'ant-design-vue';
import {
DashboardOutlined,
EditOutlined,
InfoCircleOutlined,
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
SettingOutlined,
@@ -13,6 +15,10 @@ import {
TrophyOutlined,
} from '@ant-design/icons-vue';
import { useMenuStore } from '@/stores/menuStore';
import { useUserStore } from '@/stores/userStore';
import { useState, useBreadcrumb, auth } from '@/hooks';
import { ChangePasswordModal } from '@/components';
import logoutSvg from '@/assets/img/icon/logout.svg';
import styles from './BasicLayout.module.less';
const { Header, Sider, Content, Footer } = Layout;
@@ -86,6 +92,8 @@ export default defineComponent({
const collapsed = ref(false);
const { menuItems } = useMenuStore();
const { phone } = useUserStore();
const { breadcrumbs } = useBreadcrumb();
const selectedKeys = computed<string[]>(() => [route.path]);
@@ -99,6 +107,53 @@ export default defineComponent({
collapsed.value = !collapsed.value;
};
/** ===== 退出登录 ===== */
const handleLogout = () => {
Modal.confirm({
title: '提示',
content: '是否退出登录?',
okText: '确认',
cancelText: '取消',
onOk: () => {
const { clearUser } = useUserStore();
clearUser();
auth.logout();
},
});
};
/** ===== 修改密码弹窗 ===== */
const [changePwdVisible, setChangePwdVisible] = useState<boolean>(false);
const [changePwdSubmitting, setChangePwdSubmitting] = useState<boolean>(false);
const handleChangePassword = () => {
setChangePwdVisible(true);
};
const handleChangePwdSave = async (payload: { newPassword: string }) => {
if (changePwdSubmitting.value) return;
setChangePwdSubmitting(true);
try {
// TODO: 替换为真实 API 调用
console.log('修改密码:', payload);
message.success('修改成功');
setChangePwdVisible(false);
} catch (err: any) {
message.error(err?.msg || '修改失败');
} finally {
setChangePwdSubmitting(false);
}
};
/** ===== 头像下拉菜单:修改密码 / 退出登录 ===== */
const handleUserMenuClick: MenuProps['onClick'] = ({ key }) => {
if (key === 'changePassword') {
handleChangePassword();
} else if (key === 'logout') {
handleLogout();
}
};
return () => (
<Layout class={styles.container}>
<Sider style={siderStyle} collapsed={collapsed.value} trigger={null} collapsible>
@@ -119,6 +174,49 @@ export default defineComponent({
<span class={styles.trigger} onClick={toggleCollapsed}>
{collapsed.value ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</span>
{/* 面包屑:紧跟在折叠按钮之后 */}
<Breadcrumb separator=">" class={styles.breadcrumb}>
{breadcrumbs.value.map((item, index) => {
const isLast = index === breadcrumbs.value.length - 1;
return (
<Breadcrumb.Item key={item.path || index}>
{isLast || !item.path ? (
<span>{item.title}</span>
) : (
<a onClick={() => router.push(item.path as string)}>{item.title}</a>
)}
</Breadcrumb.Item>
);
})}
</Breadcrumb>
{/* 右侧: 账号信息 + 退出 */}
<div class={styles.headerRight}>
<span class={styles.userPhone}>{phone.value}</span>
<Dropdown trigger={['hover']} placement="bottomLeft">
{{
default: () => <img src={logoutSvg} class={styles.logoutIcon} />,
overlay: () => (
<Menu onClick={handleUserMenuClick}>
<Menu.Item key="changePassword">
<span class={styles.menuItem}>
<EditOutlined />
</span>
</Menu.Item>
<Menu.Divider />
<Menu.Item key="logout">
<span class={`${styles.menuItem} ${styles.menuItemDanger}`}>
<LogoutOutlined />
退
</span>
</Menu.Item>
</Menu>
),
}}
</Dropdown>
</div>
</Header>
<Content class={styles.content}>
@@ -127,6 +225,16 @@ export default defineComponent({
<Footer style={footerStyle}> ©{new Date().getFullYear()}</Footer>
</Layout>
{/* 修改密码弹窗 */}
{changePwdVisible.value && (
<ChangePasswordModal
visible={changePwdVisible.value}
submitting={changePwdSubmitting.value}
onClose={() => setChangePwdVisible(false)}
onSave={handleChangePwdSave}
/>
)}
</Layout>
);
},
+3
View File
@@ -6,10 +6,13 @@ import App from './App';
import router from './router';
import './router/guard'; // 路由守卫:登录鉴权 + 动态菜单加载
import './assets/styles/index.less';
import ypComponent from '@yp-component/root';
import '@yp-component/root/style.css';
const app = createApp(App);
app.use(router);
app.use(Antd);
app.use(ypComponent);
app.mount('#app');
@@ -58,27 +58,47 @@
/* ===== 预览 ===== */
.previewWrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
border: 1px solid #e8e8e8;
position: relative;
width: 100%;
height: 140px;
border: 1px solid #d9d9d9;
border-radius: 6px;
background-color: #fff;
padding: 12px;
overflow: hidden;
background-color: #f5f5f5;
:global {
.ant-spin-nested-loading,
.ant-spin-container {
width: 100%;
height: 100%;
}
}
}
.previewImg {
width: 100%;
max-width: 420px;
max-height: 160px;
object-fit: contain;
border-radius: 4px;
height: 100%;
object-fit: cover;
display: block;
}
.previewActions {
display: flex;
gap: 8px;
.uploadAgainBtn {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
color: #fff;
text-align: center;
padding: 4px 0;
cursor: pointer;
font-size: 12px;
user-select: none;
transition: background 0.2s;
&:hover {
background: rgba(0, 0, 0, 0.65);
}
}
/* ===== 提示 ===== */
@@ -1,4 +1,5 @@
import { defineComponent, ref, reactive, watch } from 'vue';
import { defineComponent, ref, reactive } from 'vue';
import { useEffect } from '@/hooks';
import {
Modal,
Form,
@@ -11,7 +12,8 @@ import {
Spin,
} from 'ant-design-vue';
import { JUMP_TYPE_OPTIONS, EVENT_OPTIONS, REGION_OPTIONS } from '../model/useBannerModel';
import { uploadFilesOneByOne, OssUploadType } from '@/utils/oss';
import { ImageCropper } from '@yp-component/root';
import { uploadFile, OssUploadType } from '@/utils/oss';
import dayjs from 'dayjs';
import styles from './BannerFormModal.module.less';
@@ -34,6 +36,11 @@ const TITLE_MAX = 50;
const PATH_MAX = 200;
const URL_MAX = 500;
/** 图片上传限制:最大 10MB */
const IMAGE_MAX_SIZE = 10 * 1024 * 1024;
/** 裁剪比例:1053:351 = 3:1 */
const CROP_ASPECT_RATIO = 1053 / 351;
interface BannerFormModalProps {
visible: boolean;
record: any;
@@ -42,6 +49,20 @@ interface BannerFormModalProps {
onSave: (formData: any) => void;
}
/**
* 将 base64 字符串转换为 File 对象
*/
function base64ToFile(dataUrl: string, fileName: string): File {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/png';
const bstr = atob(arr[1]);
const u8arr = new Uint8Array(bstr.length);
for (let i = 0; i < bstr.length; i++) {
u8arr[i] = bstr.charCodeAt(i);
}
return new File([u8arr], fileName, { type: mime });
}
/**
* Banner 新增/编辑表单弹窗
*/
@@ -59,6 +80,11 @@ export default defineComponent({
const fileInputRef = ref<HTMLInputElement | null>(null);
const formData = reactive(getDefaultForm());
/** 裁剪弹窗状态 */
const cropperVisible = ref(false);
/** 待裁剪图片的本地预览 URL */
const uploadImageUrl = ref('');
/** 根据 record 初始化表单 */
const initFormFromRecord = (record: any) => {
const fresh = getDefaultForm();
@@ -94,31 +120,27 @@ export default defineComponent({
};
/** 监听 visible 变化重置表单 */
watch(
() => props.visible,
(val) => {
if (val) {
initFormFromRecord(props.record);
setTimeout(() => formRef.value?.clearValidate(), 0);
}
},
{ immediate: true },
);
useEffect(() => {
if (props.visible) {
initFormFromRecord(props.record);
cropperVisible.value = false;
uploadImageUrl.value = '';
setTimeout(() => formRef.value?.clearValidate(), 0);
}
}, [() => props.visible]);
/** 监听 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);
},
);
useEffect(() => {
const newType = formData.jumpType;
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);
}, [() => formData.jumpType]);
/** 触发隐藏的文件选择器 */
const triggerFilePicker = () => {
@@ -126,8 +148,8 @@ export default defineComponent({
fileInputRef.value?.click();
};
/** 处理文件选择 */
const handleFileChange = async (e: Event) => {
/** 处理文件选择 → 打开裁剪弹窗 */
const handleFileChange = (e: Event) => {
const target = e.target as HTMLInputElement;
const file = target.files?.[0];
// 重置 input 以便同一文件可再次选择
@@ -138,40 +160,61 @@ export default defineComponent({
message.error('请选择图片文件');
return;
}
const MAX_SIZE = 5 * 1024 * 1024;
if (file.size > MAX_SIZE) {
message.error('图片大小不能超过 5MB');
if (file.size > IMAGE_MAX_SIZE) {
message.error(`图片大小不能超过 ${IMAGE_MAX_SIZE / 1024 / 1024}MB`);
return;
}
// 本地预览
const localUrl = URL.createObjectURL(file);
// 生成本地预览 URL,打开裁剪弹窗
uploadImageUrl.value = URL.createObjectURL(file);
cropperVisible.value = true;
};
/** 裁剪确认回调:将裁剪后的图片上传到 OSS */
const handleCropConfirm = async (dataUrl: string) => {
cropperVisible.value = false;
// 释放旧的本地预览
if (formData.imageUrl && formData.imageUrl.startsWith('blob:')) {
URL.revokeObjectURL(formData.imageUrl);
}
// 先用 base64 做本地预览
const localUrl = dataUrl;
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('图片上传失败');
},
});
const file = base64ToFile(dataUrl, `banner_${Date.now()}.jpg`);
const result = await uploadFile(file, OssUploadType.Banner as any);
// 释放本地预览
URL.revokeObjectURL(localUrl);
formData.imageUrl = result.url;
formData.imageStatus = 'success';
message.success('图片上传成功');
} catch (err: any) {
console.error('[Banner] 获取上传凭证失败:', err);
console.error('[Banner] 上传失败:', err);
URL.revokeObjectURL(localUrl);
formData.imageUrl = '';
formData.imageStatus = 'error';
message.error(err?.message || '图片上传失败');
}
// 清理裁剪资源
if (uploadImageUrl.value) {
URL.revokeObjectURL(uploadImageUrl.value);
}
uploadImageUrl.value = '';
};
/** 裁剪弹窗取消 */
const onCropperCancel = () => {
cropperVisible.value = false;
if (uploadImageUrl.value) {
URL.revokeObjectURL(uploadImageUrl.value);
}
uploadImageUrl.value = '';
};
/** 删除已上传图片 */
@@ -214,266 +257,293 @@ export default defineComponent({
};
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' && (
<>
<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="关联赛事"
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"
label="Banner标题"
name="title"
rules={[
{ required: true, message: '请输入页面路径' },
{
pattern: /^\//,
message: '页面路径需以 / 开头',
},
{ max: PATH_MAX, message: `路径最多 ${PATH_MAX} 个字符` },
{ required: true, message: '请输入' },
{ max: TITLE_MAX, message: `标题最多 ${TITLE_MAX} 个字符` },
]}
>
<Input
placeholder="/pages/index/index"
maxlength={PATH_MAX}
placeholder="请输入标题"
maxlength={TITLE_MAX}
allowClear
v-model:value={formData.pagePath}
v-model:value={formData.title}
/>
</Form.Item>
)}
{formData.jumpType === 'custom_link' && (
{/* ===== 上传图片(必填,带裁剪) ===== */}
<Form.Item
label="自定义链接"
name="customUrl"
label="上传图片"
name="imageUrl"
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: '请选择结束时间' },
{ required: true, message: '请上传 Banner 图片' },
{
validator: async () => {
const [s, e] = formData.displayTimeRange || [];
if (s && e && new Date(e) < new Date(s)) {
return Promise.reject(new Error('结束时间不能早于开始时间'));
if (!formData.imageUrl || formData.imageUrl.startsWith('blob:')) {
return Promise.reject(new Error('请上传 Banner 图片'));
}
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%' }}
<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 />
JPG/PNG 10MB
</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.uploadAgainBtn} onClick={handleRemoveImage}>
</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' },
]}
>
<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>
{/* ===== 排序 ===== */}
<Form.Item
label="排序"
name="sort"
rules={[
{ required: true, message: '请输入排序' },
{ type: 'number', min: 1, max: 999, message: '排序范围 1-999' },
]}
extra="数字越小越靠前"
{/* ===== 图片裁剪弹窗 ===== */}
{cropperVisible.value && (
<Modal
visible={cropperVisible.value}
title="裁剪图片"
width={800}
footer={null}
onCancel={onCropperCancel}
centered
destroyOnClose
>
<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>
<div style={{ height: '500px' }}>
<ImageCropper
src={uploadImageUrl.value}
aspectRatio={CROP_ASPECT_RATIO}
autoCrop={true}
autoCropArea={0.8}
viewMode={1}
dragMode="move"
movable={true}
scalable={true}
zoomable={true}
cropBoxMovable={true}
cropBoxResizable={true}
onCrop={handleCropConfirm}
/>
</div>
</Modal>
)}
</>
);
},
});
+11 -9
View File
@@ -153,7 +153,7 @@ export default defineComponent({
handleToggleStatus,
} = useBannerModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
const { containerRef, height } = useContainerSize();
/** 删除二次确认 */
const confirmDelete = (record: any) => {
@@ -199,7 +199,7 @@ export default defineComponent({
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="标题" name="searchTitle">
<Input
placeholder="请输入 Banner 标题"
placeholder="请输入"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
@@ -267,13 +267,15 @@ export default defineComponent({
</div>
{/* ===== 新增/编辑弹窗 ===== */}
<BannerFormModal
visible={modalVisible.value}
record={editingRecord.value}
submitting={formSubmitting.value}
onClose={handleCloseModal}
onSave={handleSave}
/>
{modalVisible.value && (
<BannerFormModal
visible={modalVisible.value}
record={editingRecord.value}
submitting={formSubmitting.value}
onClose={handleCloseModal}
onSave={handleSave}
/>
)}
</div>
);
},
@@ -1,45 +0,0 @@
.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;
}
+14 -10
View File
@@ -106,7 +106,7 @@ export default defineComponent({
handlePageChange,
} = useEventListModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
const { containerRef, height } = useContainerSize();
// 弹窗状态
const [regulationModalVisible, setRegulationModalVisible] = useState<boolean>(false);
@@ -285,15 +285,19 @@ export default defineComponent({
</div>
{/* ===== 弹窗区 ===== */}
<EventRegulationModal
visible={regulationModalVisible.value}
onClose={() => setRegulationModalVisible(false)}
/>
<EventDetailModal
visible={detailModalVisible.value}
record={currentRecord.value}
onClose={() => setDetailModalVisible(false)}
/>
{regulationModalVisible.value && (
<EventRegulationModal
visible={regulationModalVisible.value}
onClose={() => setRegulationModalVisible(false)}
/>
)}
{detailModalVisible.value && (
<EventDetailModal
visible={detailModalVisible.value}
record={currentRecord.value}
onClose={() => setDetailModalVisible(false)}
/>
)}
</div>
);
},
+1 -1
View File
@@ -22,7 +22,7 @@
display: flex;
align-items: center;
gap: 20px;
padding: 8px 0;
padding: 12px 16px;
font-size: 14px;
color: #1a1a1a;
+13 -11
View File
@@ -107,7 +107,7 @@ export default defineComponent({
handlePageChange,
} = useOrderModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
const { containerRef, height } = useContainerSize();
// 详情弹窗状态
const [detailVisible, setDetailVisible] = useState<boolean>(false);
@@ -252,16 +252,18 @@ export default defineComponent({
</div>
{/* ===== 详情弹窗 ===== */}
<OrderDetailModal
visible={detailVisible.value}
record={currentRecord.value}
onClose={() => setDetailVisible(false)}
onReRefund={(record) => {
// 关闭详情弹窗,再弹出二次确认
setDetailVisible(false);
promptReRefund(record);
}}
/>
{detailVisible.value && (
<OrderDetailModal
visible={detailVisible.value}
record={currentRecord.value}
onClose={() => setDetailVisible(false)}
onReRefund={(record) => {
// 关闭详情弹窗,再弹出二次确认
setDetailVisible(false);
promptReRefund(record);
}}
/>
)}
</div>
);
},
+1 -1
View File
@@ -72,7 +72,7 @@ export default defineComponent({
handlePageChange,
} = useUserModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
const { containerRef, height } = useContainerSize();
const handleToggleStatus = (record: any) => {
const isActive = record.status === 'active';
@@ -0,0 +1,46 @@
// ===== 汇总(按图片:左对齐两段加粗数字) =====
.summary {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0 32px;
flex-shrink: 0;
padding: 14px 15px;
background: #fff;
border-radius: 8px;
font-size: 14px;
color: rgba(0, 0, 0, 0.85);
}
.summaryItem {
display: inline-flex;
align-items: baseline;
}
.summaryLabel {
color: rgba(0, 0, 0, 0.65);
}
.summaryValue {
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
letter-spacing: 0.3px;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
// ===== 表格 body 容器:占满 flex 剩余空间 =====
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
+105 -1
View File
@@ -1,4 +1,10 @@
import { defineComponent } from 'vue';
import { Button, Input, Table, Form, Space, Pagination, Select, DatePicker } from 'ant-design-vue';
import { usePaymentsModel } from './model/usePaymentsModel';
import { useContainerSize } from '@/hooks';
import styles from './index.module.less';
const { RangePicker } = DatePicker;
/**
* 支付流水
@@ -6,9 +12,107 @@ import { defineComponent } from 'vue';
export default defineComponent({
name: 'FinancePayments',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
summary,
pagination,
handleSearch,
handleReset,
handlePageChange,
PAYMENT_TYPE_OPTIONS,
} = usePaymentsModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="时间" name="timeRange">
<RangePicker
value={filterForm.timeRange as any}
style={{ width: '240px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.timeRange = val)}
/>
</Form.Item>
<Form.Item label="用户昵称" name="searchUserName">
<Input
placeholder="请输入"
style={{ width: '180px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="手机号" name="searchPhone">
<Input
placeholder="请输入"
style={{ width: '180px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="类型" name="type">
<Select
value={filterForm.type}
options={PAYMENT_TYPE_OPTIONS as any}
style={{ width: '140px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.type = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</Button>
</Space>
</Form.Item>
</Form>
</div>
{/* ===== 表格区 ===== */}
<div class="page-table">
{/* ===== 汇总区(按图片样式:左对齐的两段加粗数字) ===== */}
<div class={styles.summary}>
<span class={styles.summaryItem}>
<span class={styles.summaryLabel}></span>
<span class={styles.summaryValue}>{summary.value.totalPay.toFixed(2)}</span>
</span>
<span class={styles.summaryItem}>
<span class={styles.summaryLabel}>退</span>
<span class={styles.summaryValue}>{summary.value.totalRefund.toFixed(2)}</span>
</span>
</div>
<div ref={containerRef} class={styles.tableBody}>
<Table
columns={columns}
dataSource={dataSource.value}
loading={loading.value}
scroll={{ x: 'max-content', y: height.value }}
pagination={false}
/>
</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,201 @@
import { reactive, toRef, Ref } from 'vue';
import { message } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 类型选项(筛选) */
export const PAYMENT_TYPE_OPTIONS = [
{ value: '', label: '全部' },
{ value: '报名', label: '报名' },
{ value: '取消报名', label: '取消报名' },
{ value: '提现', label: '提现' },
] as const;
// ============================================================
// 汇总假数据
// ============================================================
const MOCK_SUMMARY = {
totalPay: 113255.0,
totalRefund: 3255.0,
};
// ============================================================
// 支付流水假数据(5 条)
// ============================================================
const MOCK_DATA = [
{
key: '1',
flowNo: 'xxxxxx',
orderNo: 'xxxxxxxx',
type: '报名',
nickName: '张三',
phone: '12345678997',
amount: 99.0,
thirdFlowNo: 'xxxxxxxxxxxxxxxxxxxx',
tradeTime: '2026-05-26 08:00:00',
},
{
key: '2',
flowNo: '',
orderNo: '',
type: '取消报名',
nickName: '李四',
phone: '12345678998',
amount: 100.0,
thirdFlowNo: '',
tradeTime: '2026-05-26 07:00:00',
},
{
key: '3',
flowNo: '',
orderNo: '',
type: '提现',
nickName: '王五',
phone: '12345678998',
amount: 1000.0,
thirdFlowNo: '',
tradeTime: '2026-05-26 06:00:00',
},
{
key: '4',
flowNo: '',
orderNo: '',
type: '报名',
nickName: '赵六',
phone: '13800138000',
amount: 199.0,
thirdFlowNo: '',
tradeTime: '2026-05-25 19:30:00',
},
{
key: '5',
flowNo: '',
orderNo: '',
type: '取消报名',
nickName: '钱七',
phone: '13900139001',
amount: 50.0,
thirdFlowNo: '',
tradeTime: '2026-05-25 15:20:00',
},
];
// ============================================================
// Model
// ============================================================
/**
* 支付流水页数据模型
*/
export function usePaymentsModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
timeRange: null as [string, string] | null,
searchUserName: '',
searchPhone: '',
type: '',
});
// 可搜索字段防抖
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 [summary, setSummary] = useState(MOCK_SUMMARY);
// ===== 表格状态 =====
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: 'flowNo', key: 'flowNo', width: 140 },
{ title: '订单编号', dataIndex: 'orderNo', key: 'orderNo', width: 140 },
{ title: '类型', dataIndex: 'type', key: 'type', width: 110 },
{ title: '用户昵称', dataIndex: 'nickName', key: 'nickName', width: 120 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 140 },
{
title: '金额',
dataIndex: 'amount',
key: 'amount',
width: 120,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{ title: '第三方流水单号', dataIndex: 'thirdFlowNo', key: 'thirdFlowNo', width: 220 },
{
title: '交易时间',
dataIndex: 'tradeTime',
key: 'tradeTime',
width: 170,
},
];
// ===== 方法 =====
/** 查询(节流 500ms */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
timeRange: filterForm.timeRange,
nickName: debouncedUserName.value,
phone: debouncedPhone.value,
type: filterForm.type,
});
// 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);
/** 重置(节流 500ms */
const handleReset = useThrottleFn(() => {
filterForm.timeRange = null;
filterForm.searchUserName = '';
filterForm.searchPhone = '';
filterForm.type = '';
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,
handleSearch,
handleReset,
handlePageChange,
PAYMENT_TYPE_OPTIONS: PAYMENT_TYPE_OPTIONS as any,
};
}
+127
View File
@@ -0,0 +1,127 @@
// ===== 整页可滚动:内容超出视口时出滚动条 =====
.pageWrap {
height: auto !important;
min-height: 100%;
overflow-y: auto;
overflow-x: hidden;
padding-bottom: 16px;
}
// ===== 顶部标题区 =====
.reportHeader {
display: flex;
justify-content: space-between;
align-items: flex-end;
padding: 4px 4px 0;
flex-shrink: 0;
}
.headerLeft {
display: flex;
flex-direction: column;
gap: 6px;
}
.reportTitle {
font-size: 20px;
font-weight: 600;
color: rgba(0, 0, 0, 0.88);
letter-spacing: 0.5px;
}
.reportSub {
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
letter-spacing: 0.3px;
}
// ===== 顶部 3 张统计卡 =====
.statCards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
flex-shrink: 0;
margin: 16px 0;
}
.statCard {
padding: 20px 24px;
border-radius: 10px;
display: flex;
flex-direction: column;
gap: 8px;
transition: all 0.25s ease;
cursor: default;
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
}
}
.statLabel {
font-size: 13px;
color: rgba(0, 0, 0, 0.55);
letter-spacing: 0.3px;
}
.statValue {
font-size: 26px;
font-weight: 600;
line-height: 1.2;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
letter-spacing: 0.3px;
}
.statDesc {
font-size: 12px;
letter-spacing: 0.3px;
}
// ===== 图表卡 =====
.chartCard {
flex-shrink: 0;
background: #fff;
border-radius: 10px;
padding: 18px 20px 14px;
margin-bottom: 16px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
}
.cardTitle {
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 14px;
display: flex;
align-items: center;
gap: 6px;
}
.cardTitleIcon {
font-size: 14px;
}
// ===== 柱状图(echarts =====
.chartEcharts {
width: 100%;
height: 300px;
}
// ===== 明细表卡(按内容自适应高度,不被压缩) =====
.detailCard {
flex: none;
display: flex;
flex-direction: column;
background: #fff;
border-radius: 10px;
padding: 18px 20px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
:global(.ant-table-thead > tr > th) {
background: #fafafa;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
}
}
+213 -6
View File
@@ -1,15 +1,222 @@
import { defineComponent } from 'vue';
import { defineComponent, ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { Select, Table } from 'ant-design-vue';
import * as echarts from 'echarts';
import { useReportsModel } from './model/useReportsModel';
import styles from './index.module.less';
/**
* 账务报表
*
* 页面结构:
* 1. 顶部标题 + 时间范围选择
* 2. 三张统计卡(总收入 / 总提现 / 平台余额)
* 3. 月度收支趋势(近 6 个月,echarts 柱状图)
* 4. 月度收支明细(表格)
*/
export default defineComponent({
name: 'FinanceReports',
setup() {
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
</div>
);
const {
range,
handleRangeChange,
summary,
chartData,
detailColumns,
detailData,
formatMoney,
RANGE_OPTIONS,
} = useReportsModel();
// ===== 柱状图(echarts =====
const chartRef = ref<HTMLElement>();
let chartInstance: any = null;
const getChartOption = () => {
const months = chartData.value.map((d) => d.month);
const order = chartData.value.map((d) => d.order);
const netIncome = chartData.value.map((d) => d.netIncome);
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
valueFormatter: (v: number) => `¥${formatMoney(v)}`,
},
legend: {
data: ['订单金额', '净收入'],
bottom: 8,
icon: 'roundRect',
itemWidth: 14,
itemHeight: 10,
textStyle: { color: 'rgba(0, 0, 0, 0.65)' },
},
grid: { left: 8, right: 16, top: 24, bottom: 48, containLabel: true },
xAxis: {
type: 'category',
data: months,
axisTick: { show: false },
axisLine: { lineStyle: { color: '#e8e8e8' } },
axisLabel: { color: 'rgba(0, 0, 0, 0.55)' },
},
yAxis: {
type: 'value',
axisLabel: {
color: 'rgba(0, 0, 0, 0.45)',
formatter: (v: number) => (v >= 1000 ? `${v / 1000}k` : `${v}`),
},
splitLine: { lineStyle: { color: '#f5f5f5' } },
},
series: [
{
name: '订单金额',
type: 'bar',
data: order,
barWidth: 30,
itemStyle: { color: '#1677ff', borderRadius: [3, 3, 0, 0] },
},
{
name: '净收入',
type: 'bar',
data: netIncome,
barWidth: 30,
itemStyle: { color: '#52c41a', borderRadius: [3, 3, 0, 0] },
},
],
};
};
const renderChart = () => {
if (!chartRef.value) return;
if (!chartInstance) {
chartInstance = echarts.init(chartRef.value);
}
chartInstance.setOption(getChartOption());
};
const handleResize = () => {
chartInstance?.resize();
};
onMounted(() => {
nextTick(() => {
renderChart();
});
window.addEventListener('resize', handleResize);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
chartInstance?.dispose();
chartInstance = null;
});
// 时间范围切换时刷新图表(接入 API 后生效)
watch(range, () => {
renderChart();
});
return () => {
/** 根据增长率构建箭头 + 颜色(正值 ↑ 绿,负值 ↓ 红,null 时固定文本) */
const changeDesc = (rate: number | null) => {
if (rate == null) return { desc: '= 总收入 - 提现金额', descColor: 'rgba(0, 0, 0, 0.55)' };
const arrow = rate > 0 ? '↑' : '↓';
const sign = rate > 0 ? '+' : '';
return {
desc: `${arrow} 较上月 ${sign}${rate}%`,
descColor: rate > 0 ? '#52c41a' : '#ff4d4f',
};
};
/** 顶部 3 张统计卡配置 */
const statCards = [
{
key: 'totalIncome',
label: '总收入(扣除退款后)',
value: summary.value.totalIncome,
bgColor: '#f6ffed',
accentColor: '#52c41a',
...changeDesc(12.5),
},
{
key: 'totalWithdraw',
label: '总提现金额',
value: summary.value.totalWithdraw,
bgColor: '#fffbe6',
accentColor: '#faad14',
...changeDesc(32),
},
{
key: 'totalBalance',
label: '平台余额(所有用户余额总和)',
value: summary.value.totalBalance,
bgColor: '#e6f4ff',
accentColor: '#1677ff',
...changeDesc(null),
},
];
return (
<div class={['page-container', styles.pageWrap]}>
{/* ===== 顶部标题 + 时间范围 ===== */}
<div class={styles.reportHeader}>
<div class={styles.headerLeft}>
<div class={styles.reportTitle}></div>
<div class={styles.reportSub}>
退
</div>
</div>
<Select
value={range.value}
onUpdate:value={(val: string) => handleRangeChange(val)}
options={[...RANGE_OPTIONS]}
style={{ width: 120 }}
/>
</div>
{/* ===== 统计卡 ===== */}
<div class={styles.statCards}>
{statCards.map((item) => (
<div key={item.key} class={styles.statCard} style={{ backgroundColor: item.bgColor }}>
<div class={styles.statLabel}>{item.label}</div>
<div class={styles.statValue} style={{ color: item.accentColor }}>
¥{formatMoney(item.value)}
</div>
<div class={styles.statDesc} style={{ color: item.descColor }}>
{item.desc}
</div>
</div>
))}
</div>
{/* ===== 柱状图卡(echarts ===== */}
<div class={styles.chartCard}>
<div class={styles.cardTitle}>
<span class={styles.cardTitleIcon}>📊</span>
6
</div>
<div
ref={(el: any) => {
if (el) chartRef.value = el as HTMLElement;
}}
class={styles.chartEcharts}
/>
</div>
{/* ===== 月度收支明细 ===== */}
<div class={styles.detailCard}>
<div class={styles.cardTitle}></div>
<Table
columns={detailColumns}
dataSource={detailData.value}
pagination={false}
size="middle"
bordered={false}
rowKey="key"
/>
</div>
</div>
);
};
},
});
@@ -0,0 +1,163 @@
import { ref } from 'vue';
import { useState } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 时间范围选项 */
export const RANGE_OPTIONS = [
{ value: 'month', label: '本月' },
{ value: '3m', label: '近 3 个月' },
{ value: '6m', label: '近 6 个月' },
{ value: 'year', label: '本年' },
] as const;
// ============================================================
// 假数据(数值自洽:总收入 - 总提现 = 平台余额)
// ============================================================
/** 6 个月柱状图数据(月份标签 + 订单金额 + 净收入) */
const CHART_DATA = [
{ month: '01月', order: 22500, netIncome: 19000, withdraw: 300 },
{ month: '02月', order: 24500, netIncome: 21500, withdraw: 1850 },
{ month: '03月', order: 24800, netIncome: 23200, withdraw: 1400 },
{ month: '04月', order: 26100, netIncome: 24900, withdraw: 1500 },
{ month: '05月', order: 28900, netIncome: 27400, withdraw: 1800 },
{ month: '06月', order: 32500, netIncome: 31860, withdraw: 2100 },
];
/** 月度收支明细(最近 4 个月) */
const DETAIL_DATA = [
{
key: '2026-06',
month: '2026-06',
order: 32500,
refund: 640,
netIncome: 31860,
withdraw: 2100,
},
{
key: '2026-05',
month: '2026-05',
order: 28900,
refund: 1500,
netIncome: 27400,
withdraw: 1800,
},
{
key: '2026-04',
month: '2026-04',
order: 26100,
refund: 1200,
netIncome: 24900,
withdraw: 1500,
},
{
key: '2026-03',
month: '2026-03',
order: 24800,
refund: 1600,
netIncome: 23200,
withdraw: 1400,
},
];
/** 顶部 3 张统计卡数据 */
const SUMMARY = {
totalIncome: 147860, // 总收入(净收入合计)
totalWithdraw: 8950, // 总提现
totalBalance: 138910, // 平台余额 = 总收入 - 总提现
};
// ============================================================
// 工具
// ============================================================
/** 千分位 + 保留 2 位小数 */
function formatMoney(n: number): string {
return (n || 0).toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
// ============================================================
// Model
// ============================================================
/**
* 账务报表数据模型
*/
export function useReportsModel() {
// ===== 时间范围 =====
const [range, setRange] = useState<string>('month');
/** 切换时间范围(演示用:打日志,不改数据) */
const handleRangeChange = (val: string) => {
setRange(val);
// TODO: 接入 API 时按 range 重新拉取汇总 / 图表 / 明细
};
// ===== 汇总 =====
const summary = ref({ ...SUMMARY });
// ===== 图表 =====
const chartData = ref([...CHART_DATA]);
// ===== 明细表 =====
const detailColumns = [
{
title: '月份',
dataIndex: 'month',
key: 'month',
width: 140,
align: 'left' as const,
},
{
title: '订单金额',
dataIndex: 'order',
key: 'order',
align: 'right' as const,
customRender: ({ text }: { text: number }) => `¥${formatMoney(text)}`,
},
{
title: '退款金额',
dataIndex: 'refund',
key: 'refund',
align: 'right' as const,
customRender: ({ text }: { text: number }) => `¥${formatMoney(text)}`,
customCell: (_record: any) => ({ style: { color: '#ff4d4f' } }),
},
{
title: '净收入',
dataIndex: 'netIncome',
key: 'netIncome',
align: 'right' as const,
customRender: ({ text }: { text: number }) => `¥${formatMoney(text)}`,
customCell: (_record: any) => ({
style: { color: '#52c41a', fontWeight: 600 },
}),
},
{
title: '提现金额',
dataIndex: 'withdraw',
key: 'withdraw',
align: 'right' as const,
customRender: ({ text }: { text: number }) => `¥${formatMoney(text)}`,
customCell: (_record: any) => ({ style: { color: '#fa8c16' } }),
},
];
const detailData = ref([...DETAIL_DATA]);
return {
range,
handleRangeChange,
summary,
chartData,
detailColumns,
detailData,
formatMoney,
RANGE_OPTIONS: RANGE_OPTIONS as any,
};
}
@@ -0,0 +1,62 @@
// ===== 自定义标题栏 =====
.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;
}
// ===== 筛选区 =====
.filterBar {
flex-shrink: 0;
padding: 16px 20px;
margin-bottom: 16px;
background: #fafafa;
border: 1px solid #f0f0f0;
border-radius: 6px;
}
// ===== 表格区 =====
.tableWrap {
flex: 1;
min-height: 0;
}
// ===== Modal 外层包裹:去除 antd 默认内边距 =====
/* .walletModalWrap {
:global(.ant-modal-body) {
padding-top: 16px;
padding-bottom: 20px;
}
} */
@@ -0,0 +1,276 @@
import { defineComponent, ref, reactive, computed, watch } from 'vue';
import { Modal, Table, Button, Select, Form, Space, DatePicker } from 'ant-design-vue';
import {
useWalletModel,
TRANSACTION_TYPE_OPTIONS,
TRANSACTION_STATUS_OPTIONS,
} from '../model/useWalletModel';
import styles from './WalletDetailModal.module.less';
const { RangePicker } = DatePicker;
interface WalletDetailModalProps {
visible: boolean;
record: any;
onClose: () => void;
}
/**
* 钱包交易明细弹窗
*/
export default defineComponent({
name: 'WalletDetailModal',
props: {
visible: { type: Boolean, default: false },
record: { type: Object, default: () => ({}) },
onClose: { type: Function, required: true },
},
setup(props: WalletDetailModalProps) {
const { loadTransactions, renderTransactionStatus } = useWalletModel();
// ===== 弹窗内筛选条件 =====
const detailFilter = reactive({
timeRange: null as [string, string] | null,
type: '',
status: '',
});
// ===== 加载明细 =====
const loading = ref<boolean>(false);
const allTransactions = ref<any[]>([]);
const fetchTransactions = async () => {
loading.value = true;
try {
allTransactions.value = await loadTransactions(props.record);
} finally {
loading.value = false;
}
};
/**
* 弹窗内筛选后的数据(用 computed 自动响应全量数据和筛选条件的变化)
* 真实场景应传给后端做查询;此处做前端过滤演示
*/
const filteredTransactions = computed(() => {
return allTransactions.value.filter((item) => {
if (detailFilter.type && item.type !== detailFilter.type) return false;
if (detailFilter.status && item.status !== detailFilter.status) return false;
if (detailFilter.timeRange && detailFilter.timeRange.length === 2) {
const [start, end] = detailFilter.timeRange;
if (item.time < start || item.time > end) return false;
}
return true;
});
});
const handleSearch = () => {
// computed 会自动响应;这里保留方法以便将来扩展(如后端查询)
};
const handleReset = () => {
detailFilter.timeRange = null;
detailFilter.type = '';
detailFilter.status = '';
};
// ===== 分页 =====
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showTotal: (total: number) => `${total}`,
});
/** 筛选条件变化时重置到第 1 页,并同步总数 */
watch(filteredTransactions, (list) => {
pagination.total = list.length;
pagination.current = 1;
});
const handleTableChange = (pag: any) => {
pagination.current = pag.current;
pagination.pageSize = pag.pageSize;
};
/** 监听 visible 变化:打开时加载明细 */
watch(
() => props.visible,
(val) => {
if (val) {
detailFilter.timeRange = null;
detailFilter.type = '';
detailFilter.status = '';
allTransactions.value = [];
fetchTransactions();
}
},
);
// ===== 表格列配置 =====
const detailColumns = [
{
title: '类型',
dataIndex: 'type',
key: 'type',
width: 120,
},
{
title: '金额',
dataIndex: 'amount',
key: 'amount',
width: 110,
align: 'center' as const,
customRender: ({ text }: { text: number }) => {
const num = text || 0;
const isPlus = num > 0;
const isMinus = num < 0;
const color = isPlus ? '#52c41a' : isMinus ? '#ff4d4f' : 'rgba(0,0,0,0.85)';
const sign = isPlus ? '+' : '';
return (
<span style={{ color, fontWeight: 500 }}>
{sign}
{num.toFixed(2)}
</span>
);
},
},
{
title: '余额',
dataIndex: 'balance',
key: 'balance',
width: 110,
align: 'center' as const,
customRender: ({ text }: { text: number }) => `¥${(text || 0).toFixed(2)}`,
},
{
title: '可提现金额',
dataIndex: 'withdrawable',
key: 'withdrawable',
width: 130,
align: 'center' as const,
customRender: ({ text }: { text: number }) => `¥${(text || 0).toFixed(2)}`,
},
{
title: '冻结金额',
dataIndex: 'frozen',
key: 'frozen',
width: 110,
align: 'center' as const,
customRender: ({ text }: { text: number }) => `¥${(text || 0).toFixed(2)}`,
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 90,
align: 'center' as const,
customRender: ({ text }: { text: string }) => renderTransactionStatus(text),
},
{
title: '冻结时间',
dataIndex: 'frozenTime',
key: 'frozenTime',
width: 130,
align: 'center' as const,
},
{
title: '解冻时间',
dataIndex: 'unfreezeTime',
key: 'unfreezeTime',
width: 130,
align: 'center' as const,
},
{
title: '关联单号',
dataIndex: 'relatedNo',
key: 'relatedNo',
width: 130,
align: 'center' as const,
},
{
title: '时间',
dataIndex: 'time',
key: 'time',
width: 130,
align: 'center' as const,
},
];
return () => (
<Modal
title="明细详情"
visible={props.visible}
onCancel={props.onClose}
width={1300}
destroyOnClose
footer={null}
centered
>
<div class={styles.modalBody}>
{/* ===== 弹窗内筛选区 ===== */}
<div class={styles.filterBar}>
<Form layout="inline" model={detailFilter}>
<Form.Item label="时间" name="timeRange">
<RangePicker
value={detailFilter.timeRange as any}
style={{ width: '240px' }}
allowClear
onUpdate:value={(val: any) => (detailFilter.timeRange = val)}
/>
</Form.Item>
<Form.Item label="类型" name="type">
<Select
value={detailFilter.type}
options={TRANSACTION_TYPE_OPTIONS as any}
style={{ width: '140px' }}
allowClear
onUpdate:value={(val: any) => (detailFilter.type = val || '')}
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Select
value={detailFilter.status}
options={TRANSACTION_STATUS_OPTIONS as any}
style={{ width: '140px' }}
allowClear
onUpdate:value={(val: any) => (detailFilter.status = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleSearch}>
</Button>
</Space>
</Form.Item>
</Form>
</div>
{/* ===== 表格区 ===== */}
<div class={styles.tableWrap}>
<Table
columns={detailColumns}
dataSource={filteredTransactions.value}
loading={loading.value}
size="middle"
bordered
pagination={{
current: pagination.current,
pageSize: pagination.pageSize,
total: pagination.total,
showSizeChanger: pagination.showSizeChanger,
showTotal: pagination.showTotal,
}}
onChange={handleTableChange}
scroll={{ x: 'max-content' }}
locale={{ emptyText: '暂无交易明细' }}
/>
</div>
</div>
</Modal>
);
},
});
+107
View File
@@ -0,0 +1,107 @@
// ===== 表格 body 容器:占满 flex 剩余空间,并确保 antd 嵌套 div 逐层传递 height: 100% =====
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
// ===== 顶部 3 张统计卡 =====
.statCards {
display: flex;
gap: 16px;
flex-shrink: 0;
margin-bottom: 16px;
}
.statCard {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 16px;
padding: 22px 24px;
background: #fff;
border: 1px solid #f0f0f0;
border-radius: 10px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
transition: all 0.25s ease;
cursor: default;
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}
}
.statCardLeft {
flex-shrink: 0;
}
.statIconWrap {
width: 52px;
height: 52px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
font-size: 26px;
transition: transform 0.25s ease;
.statCard:hover & {
transform: scale(1.05);
}
}
.statCardRight {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.statLabel {
font-size: 13px;
color: rgba(0, 0, 0, 0.55);
letter-spacing: 0.3px;
}
.statValue {
font-size: 26px;
font-weight: 600;
line-height: 1.2;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
letter-spacing: 0.3px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// ===== 下方白卡片:包裹筛选区 + 表格区 =====
.tableSection {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 16px 20px;
background: #fff;
border: 1px solid #f0f0f0;
border-radius: 10px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
overflow: hidden;
// 表格区紧贴筛选区下方,控制间距
:global(.page-table) {
margin-top: 16px;
}
}
+232 -5
View File
@@ -1,4 +1,43 @@
import { defineComponent } from 'vue';
import { Button, Input, Table, Form, Space, Pagination } from 'ant-design-vue';
import { WalletOutlined, LockOutlined, RiseOutlined } from '@ant-design/icons-vue';
import { useWalletModel } from './model/useWalletModel';
import { useContainerSize } from '@/hooks';
import WalletDetailModal from './components/WalletDetailModal';
import styles from './index.module.less';
interface StatCardItem {
key: string;
label: string;
value: number;
icon: any;
color: string;
bgColor: string;
}
/**
* bodyCell 渲染函数
*/
function renderBodyCell({
column,
record,
onViewDetail,
}: {
column: any;
text: any;
record: any;
onViewDetail: (record: any) => void;
}) {
// 操作列
if (column.key === 'action') {
return (
<Button type="link" size="small" onClick={() => onViewDetail(record)}>
</Button>
);
}
return;
}
/**
* 用户钱包
@@ -6,10 +45,198 @@ 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>
);
const {
filterForm,
loading,
dataSource,
columns,
summary,
pagination,
detailVisible,
currentWallet,
handleSearch,
handleReset,
handlePageChange,
handleViewDetail,
handleCloseDetail,
} = useWalletModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
/** 最终表格列:模型列 + 操作 */
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 100,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => {
/** 顶部统计卡配置 */
const statCards: StatCardItem[] = [
{
key: 'totalBalance',
label: '总余额',
value: summary.value.totalBalance,
icon: WalletOutlined,
color: '#1677ff',
bgColor: 'rgba(22, 119, 255, 0.08)',
},
{
key: 'frozenAmount',
label: '冻结金额',
value: summary.value.frozenAmount,
icon: LockOutlined,
color: '#fa8c16',
bgColor: 'rgba(250, 140, 22, 0.08)',
},
{
key: 'totalWithdraw',
label: '累计提现',
value: summary.value.totalWithdraw,
icon: RiseOutlined,
color: '#52c41a',
bgColor: 'rgba(82, 196, 26, 0.08)',
},
];
return (
<div class="page-container">
{/* ===== 顶部统计卡 ===== */}
<div class={styles.statCards}>
{statCards.map((item) => (
<div key={item.key} class={styles.statCard}>
<div class={styles.statCardLeft}>
<div
class={styles.statIconWrap}
style={{ color: item.color, backgroundColor: item.bgColor }}
>
<item.icon />
</div>
</div>
<div class={styles.statCardRight}>
<div class={styles.statLabel}>{item.label}</div>
<div class={styles.statValue} style={{ color: item.color }}>
¥
{item.value.toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
</div>
</div>
</div>
))}
</div>
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="用户昵称" name="searchUserName">
<Input
placeholder="请输入"
style={{ width: '180px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="手机号" name="searchPhone">
<Input
placeholder="请输入"
style={{ width: '180px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="余额筛选">
<Space.Compact>
<Input
placeholder="请输入"
style={{ width: '130px' }}
value={filterForm.minBalance}
onUpdate:value={(val: any) => (filterForm.minBalance = val ?? '')}
onPressEnter={handleSearch}
allowClear
/>
<Input
style={{
width: '40px',
textAlign: 'center',
backgroundColor: '#fafafa',
pointerEvents: 'none',
color: 'rgba(0,0,0,0.45)',
}}
value="至"
disabled
/>
<Input
placeholder="请输入"
style={{ width: '130px' }}
value={filterForm.maxBalance}
onUpdate:value={(val: any) => (filterForm.maxBalance = val ?? '')}
onPressEnter={handleSearch}
allowClear
/>
</Space.Compact>
</Form.Item>
<Form.Item>
<Space>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</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,
onViewDetail: handleViewDetail,
}),
}}
</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>
{/* ===== 交易明细弹窗 ===== */}
<WalletDetailModal
visible={detailVisible.value}
record={currentWallet.value}
onClose={handleCloseDetail}
/>
</div>
);
};
},
});
@@ -0,0 +1,349 @@
import { computed, reactive, toRef, Ref, h } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 明细类型选项(弹窗内筛选) */
export const TRANSACTION_TYPE_OPTIONS = [
{ value: '', label: '全部' },
{ value: '报名收入', label: '报名收入' },
{ value: '提现', label: '提现' },
{ value: '取消报名退款', label: '取消报名退款' },
] as const;
/** 明细状态选项(弹窗内筛选) */
export const TRANSACTION_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: '正常', label: '正常' },
{ value: '冻结中', label: '冻结中' },
{ value: '已解冻', label: '已解冻' },
] as const;
/** 明细状态映射(用于表格 Tag 渲染) */
const TRANSACTION_STATUS_MAP: Record<string, { label: string; color: string }> = {
: { label: '正常', color: 'blue' },
: { label: '冻结中', color: 'orange' },
: { label: '已解冻', color: 'green' },
};
// ============================================================
// 顶部统计卡假数据
// ============================================================
const MOCK_SUMMARY = {
totalBalance: 86520.0,
frozenAmount: 3200.0,
totalWithdraw: 63080.0,
};
// ============================================================
// 假数据(钱包列表)
// ============================================================
const MOCK_DATA = [
{
key: '1',
userId: 'U20260701001',
nickName: '张三',
phone: '12345678997',
balance: 0,
frozen: 0,
totalWithdraw: 0,
},
{
key: '2',
userId: '',
nickName: '李四',
phone: '12345678998',
balance: 350,
frozen: 200,
totalWithdraw: 1450,
},
{
key: '3',
userId: '',
nickName: '王五',
phone: '12345678999',
balance: 1280,
frozen: 0,
totalWithdraw: 800,
},
{
key: '4',
userId: 'U20260701004',
nickName: '赵六',
phone: '13800138000',
balance: 560,
frozen: 100,
totalWithdraw: 200,
},
{
key: '5',
userId: '',
nickName: '钱七',
phone: '13900139001',
balance: 4200,
frozen: 1500,
totalWithdraw: 5600,
},
{
key: '6',
userId: '',
nickName: '孙八',
phone: '12345678997',
balance: 880,
frozen: 0,
totalWithdraw: 300,
},
];
// ============================================================
// 交易明细假数据(所有用户共用,演示用)
// ============================================================
const MOCK_TRANSACTIONS: any[] = [
{
key: 't-1',
type: '报名收入',
amount: 100,
balance: 600,
withdrawable: 500,
frozen: 100,
status: '已解冻',
frozenTime: '2026-06-10 08:00',
unfreezeTime: '2026-06-12 08:00',
relatedNo: 'xxxxxxxx',
time: '2026-06-10 08:00',
},
{
key: 't-2',
type: '提现',
amount: -500,
balance: 1100,
withdrawable: 500,
frozen: 600,
status: '冻结中',
frozenTime: '2026-06-10 06:00',
unfreezeTime: '-',
relatedNo: 'xxxxxxxx',
time: '2026-06-10 06:00',
},
{
key: 't-3',
type: '取消报名退款',
amount: -100,
balance: 500,
withdrawable: 500,
frozen: 0,
status: '正常',
frozenTime: '-',
unfreezeTime: '-',
relatedNo: 'xxxxxxxx',
time: '2026-06-10 05:00',
},
{
key: 't-4',
type: '报名收入',
amount: 350,
balance: 850,
withdrawable: 750,
frozen: 100,
status: '正常',
frozenTime: '-',
unfreezeTime: '-',
relatedNo: 'xxxxxxxx',
time: '2026-06-09 17:30',
},
{
key: 't-5',
type: '提现',
amount: -250,
balance: 600,
withdrawable: 500,
frozen: 100,
status: '已解冻',
frozenTime: '2026-06-08 10:00',
unfreezeTime: '2026-06-09 08:00',
relatedNo: 'xxxxxxxx',
time: '2026-06-08 10:00',
},
];
// ============================================================
// Model
// ============================================================
/**
* 用户钱包页数据模型
*/
export function useWalletModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
searchUserName: '',
searchPhone: '',
minBalance: '' as string | number,
maxBalance: '' as string | number,
});
// 可搜索字段防抖
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 [summary, setSummary] = useState(MOCK_SUMMARY);
// ===== 表格状态 =====
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 [detailVisible, setDetailVisible] = useState<boolean>(false);
const [currentWallet, setCurrentWallet] = useState<any>({});
const [detailLoading, setDetailLoading] = useState<boolean>(false);
// ===== 表格列配置 =====
const columns = [
{ title: '用户ID', dataIndex: 'userId', key: 'userId', width: 160 },
{ title: '用户昵称', dataIndex: 'nickName', key: 'nickName', width: 120 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 140 },
{
title: '余额',
dataIndex: 'balance',
key: 'balance',
width: 120,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '冻结金额',
dataIndex: 'frozen',
key: 'frozen',
width: 120,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '累计提现',
dataIndex: 'totalWithdraw',
key: 'totalWithdraw',
width: 120,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
];
// ===== 计算属性 =====
const hasFilter = computed(() => {
return (
debouncedUserName.value.trim() !== '' ||
debouncedPhone.value.trim() !== '' ||
filterForm.minBalance !== '' ||
filterForm.maxBalance !== ''
);
});
// ===== 方法 =====
/** 查询(节流 500ms */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
nickName: debouncedUserName.value,
phone: debouncedPhone.value,
minBalance: filterForm.minBalance,
maxBalance: filterForm.maxBalance,
});
// 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);
/** 重置(节流 500ms */
const handleReset = useThrottleFn(() => {
filterForm.searchUserName = '';
filterForm.searchPhone = '';
filterForm.minBalance = '';
filterForm.maxBalance = '';
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();
};
/** 打开明细弹窗 */
const handleViewDetail = (record: any) => {
setCurrentWallet(record);
setDetailVisible(true);
};
/** 关闭明细弹窗 */
const handleCloseDetail = () => {
setDetailVisible(false);
};
/**
* 加载某用户的交易明细
* 真实场景应调用 API;演示阶段所有用户共用同一份假数据
*/
const loadTransactions = async (_record: any): Promise<any[]> => {
setDetailLoading(true);
try {
// 模拟接口延迟
await new Promise((resolve) => setTimeout(resolve, 200));
return [...MOCK_TRANSACTIONS];
} finally {
setDetailLoading(false);
}
};
/** 渲染交易状态 Tag */
const renderTransactionStatus = (status: string) => {
const info = TRANSACTION_STATUS_MAP[status] || { label: status || '-', color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
};
return {
filterForm,
loading,
dataSource,
columns,
summary,
pagination,
hasFilter,
detailVisible,
currentWallet,
detailLoading,
handleSearch,
handleReset,
handlePageChange,
handleViewDetail,
handleCloseDetail,
loadTransactions,
renderTransactionStatus,
TRANSACTION_TYPE_OPTIONS: TRANSACTION_TYPE_OPTIONS as any,
TRANSACTION_STATUS_OPTIONS: TRANSACTION_STATUS_OPTIONS as any,
};
}
@@ -0,0 +1,195 @@
// ===== Modal 外层包裹:去掉 antd 默认内边距 =====
.modalWrap {
:global(.ant-modal-header) {
display: none;
}
}
// ===== 自定义标题栏 =====
.modalHeader {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 14px;
margin-bottom: 8px;
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);
}
}
// ===== 通用区块 =====
.section {
padding: 14px 0;
border-bottom: 1px dashed #f0f0f0;
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
}
.sectionTitle {
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
margin-bottom: 14px;
position: relative;
padding-left: 10px;
&::before {
content: '';
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 3px;
height: 14px;
background: #1677ff;
border-radius: 2px;
}
}
// ===== 描述项栅格(3 列) =====
.descGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
row-gap: 14px;
column-gap: 24px;
}
.descItem {
display: flex;
align-items: baseline;
min-width: 0;
}
.descLabel {
flex-shrink: 0;
color: rgba(0, 0, 0, 0.55);
font-size: 13px;
white-space: nowrap;
}
.descValue {
flex: 1;
min-width: 0;
color: rgba(0, 0, 0, 0.85);
font-size: 13px;
word-break: break-all;
overflow: hidden;
text-overflow: ellipsis;
}
.descValueBold {
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
}
// ===== 审核表单 =====
.formRow {
display: flex;
align-items: flex-start;
margin-bottom: 18px;
&:last-child {
margin-bottom: 0;
}
}
.formLabel {
width: 88px;
flex-shrink: 0;
color: rgba(0, 0, 0, 0.55);
font-size: 13px;
padding-top: 6px;
}
.formLabelTop {
padding-top: 6px;
}
.footer {
display: flex;
justify-content: flex-end;
margin-top: 24px;
}
// ===== 上传 =====
.uploader {
flex: 1;
:global {
.ant-upload-list-picture-card-container {
width: 96px;
height: 96px;
}
.ant-upload-select {
width: 96px;
height: 96px;
margin: 0;
}
}
}
.uploadTrigger {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: rgba(0, 0, 0, 0.45);
font-size: 22px;
background: #fafafa;
border-radius: 4px;
transition: all 0.2s;
&:hover {
color: #1677ff;
background: #f0f7ff;
}
}
.uploadText {
font-size: 12px;
margin-top: 4px;
color: rgba(0, 0, 0, 0.45);
}
// ===== 审核信息(只读,逐行展示) =====
.infoColumn {
display: flex;
flex-direction: column;
row-gap: 14px;
}
.auditImg {
border-radius: 4px;
object-fit: cover;
margin-right: 8px;
}
.noImage {
color: rgba(0, 0, 0, 0.45);
}
@@ -0,0 +1,245 @@
import { defineComponent, reactive, ref, watch } from 'vue';
import { Modal, Radio, Input, Button, Upload, Image, message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useWithdrawModel } from '../model/useWithdrawModel';
import styles from './WithdrawAuditModal.module.less';
const { TextArea } = Input;
interface WithdrawAuditModalProps {
visible: boolean;
record: any;
onClose: () => void;
}
/**
* 提现申请详情 / 审核弹窗
*
* 结构:
* - 基本信息
* - 银行卡信息
* - 支付信息
* - 审核操作
*/
export default defineComponent({
name: 'WithdrawAuditModal',
props: {
visible: { type: Boolean, default: false },
record: { type: Object, default: () => ({}) },
onClose: { type: Function, required: true },
},
setup(props: WithdrawAuditModalProps) {
const { submitAudit } = useWithdrawModel();
// ===== 表单状态 =====
const auditForm = reactive({
pass: true,
remark: '',
});
const imageList = ref<any[]>([]);
const submitting = ref<boolean>(false);
/** 监听 visible:每次打开都重置表单 */
watch(
() => props.visible,
(val) => {
if (val) {
auditForm.pass = true;
auditForm.remark = '';
imageList.value = [];
submitting.value = false;
}
},
);
/** 上传前校验(演示用:限制 5 张 & 5MB */
const beforeUpload = (file: any) => {
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isLt5M) {
message.error('图片大小不能超过 5MB');
return false;
}
imageList.value = [...imageList.value, file];
return false; // 阻止自动上传,由"提交审核"按钮统一处理
};
const handleRemove = (file: any) => {
imageList.value = imageList.value.filter((f) => f.uid !== file.uid);
};
const handleSubmit = async () => {
if (!auditForm.remark.trim()) {
message.warning('请输入审核内容');
return;
}
submitting.value = true;
try {
// 真实场景应上传图片并调用审核 API
const urls = imageList.value.map((f) => f.name || '');
submitAudit(auditForm.pass, auditForm.remark.trim(), urls);
} finally {
submitting.value = false;
}
};
/**
* 通用描述项渲染
*/
const renderItem = (label: string, value: any, isBold = false) => (
<div class={styles.descItem}>
<span class={styles.descLabel}>{label}</span>
<span class={[styles.descValue, isBold ? styles.descValueBold : '']}>{value || '-'}</span>
</div>
);
return () => {
const record = props.record || {};
const bank = record.bank || {};
const pay = record.pay || {};
const isPending = record.auditStatus === '待审核';
return (
<Modal
visible={props.visible}
onCancel={props.onClose}
width={850}
centered
footer={null}
wrapClassName={styles.modalWrap}
title={null}
closable={false}
>
{/* 自定义标题栏 */}
<div class={styles.modalHeader}>
<span class={styles.modalTitle}></span>
<button class={styles.closeBtn} onClick={props.onClose}>
×
</button>
</div>
{/* ===== 基本信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<div class={styles.descGrid}>
{renderItem('申请人昵称:', record.nickName)}
{renderItem('申请人手机号:', record.phone)}
{renderItem('真实姓名:', record.realName)}
{renderItem('申请时间:', record.applyTime)}
{renderItem('打款类型:', record.withdrawType)}
<div style="display: contents;" />
{renderItem('提现金额:', `¥${(record.withdrawAmount || 0).toFixed(2)}`, true)}
{renderItem('费率:', `${((record.feeRate || 0) * 100).toFixed(2)}%`)}
{renderItem('手续费:', `¥${(record.feeAmount || 0).toFixed(2)}`)}
{renderItem('到账金额:', `¥${(record.transferAmount || 0).toFixed(2)}`, true)}
{renderItem('审核状态:', record.auditStatus, true)}
{renderItem('列账状态:', record.transferStatus || '-')}
</div>
</div>
{/* ===== 银行卡信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<div class={styles.descGrid}>
{renderItem('银行卡类型:', bank.cardType)}
{renderItem('持卡人:', bank.holder)}
{renderItem('银行卡号:', bank.cardNo)}
{renderItem('开户行:', bank.bankName)}
{renderItem('开户支行:', bank.branchName)}
</div>
</div>
{/* ===== 支付信息 ===== */}
<div class={styles.section}>
<div class={styles.sectionTitle}></div>
<div class={styles.descGrid}>
{renderItem('到账支付时间:', pay.transferTime || '-')}
{renderItem('商户订单号:', pay.merchantNo)}
</div>
</div>
{/* ===== 审核操作 / 审核信息 ===== */}
<div class={styles.section}>
{isPending ? (
<>
<div class={styles.sectionTitle}></div>
<div class={styles.formRow}>
<span class={styles.formLabel}></span>
<Radio.Group
value={auditForm.pass}
onUpdate:value={(val: boolean) => (auditForm.pass = val)}
>
<Radio value={true}></Radio>
<Radio value={false}></Radio>
</Radio.Group>
</div>
<div class={styles.formRow}>
<span class={[styles.formLabel, styles.formLabelTop]}></span>
<TextArea
v-model={auditForm.remark}
placeholder="请输入审核内容"
rows={4}
maxlength={500}
showCount
style={{ flex: 1 }}
/>
</div>
<div class={styles.formRow}>
<span class={[styles.formLabel, styles.formLabelTop]}></span>
<Upload
listType="picture-card"
fileList={imageList.value}
beforeUpload={beforeUpload}
onRemove={handleRemove}
accept="image/*"
class={styles.uploader}
>
{imageList.value.length >= 3 ? null : (
<div class={styles.uploadTrigger}>
<PlusOutlined />
<div class={styles.uploadText}></div>
</div>
)}
</Upload>
</div>
<div class={styles.footer}>
<Button type="primary" onClick={handleSubmit} loading={submitting.value}>
</Button>
</div>
</>
) : (
<>
<div class={styles.sectionTitle}></div>
<div class={styles.infoColumn}>
{renderItem('审核时间:', record.auditTime)}
{renderItem('审核人:', record.auditor)}
<div class={styles.descItem}>
<span class={styles.descLabel}></span>
{record.auditImages && record.auditImages.length ? (
<Image.PreviewGroup>
{record.auditImages.map((src: string, idx: number) => (
<Image
key={idx}
src={src}
width={64}
height={64}
class={styles.auditImg}
/>
))}
</Image.PreviewGroup>
) : (
<span class={[styles.descValue, styles.noImage]}></span>
)}
</div>
</div>
</>
)}
</div>
</Modal>
);
};
},
});
@@ -0,0 +1,15 @@
// ===== 表格 body 容器:占满 flex 剩余空间,并确保 antd 嵌套 div 逐层传递 height: 100% =====
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
+168 -1
View File
@@ -1,4 +1,43 @@
import { defineComponent } from 'vue';
import { Button, Input, Table, Form, Space, Pagination, Select } from 'ant-design-vue';
import { useWithdrawModel } from './model/useWithdrawModel';
import { useContainerSize } from '@/hooks';
import WithdrawAuditModal from './components/WithdrawAuditModal';
import styles from './index.module.less';
/**
* bodyCell 渲染函数(操作列:根据审核状态切换"审核 / 查看"按钮)
*/
function renderBodyCell({
column,
record,
onAudit,
onView,
}: {
column: any;
text: any;
record: any;
onAudit: (record: any) => void;
onView: (record: any) => void;
}) {
if (column.key === 'action') {
// 待审核:显示「审核」
if (record.auditStatus === '待审核') {
return (
<Button type="link" size="small" onClick={() => onAudit(record)}>
</Button>
);
}
// 其它状态:仅显示「查看」
return (
<Button type="link" size="small" onClick={() => onView(record)}>
</Button>
);
}
return;
}
/**
* 提现申请
@@ -6,9 +45,137 @@ import { defineComponent } from 'vue';
export default defineComponent({
name: 'FinanceWithdraw',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
pagination,
auditVisible,
currentRecord,
handleSearch,
handleReset,
handlePageChange,
handleAudit,
handleCloseAudit,
handleView,
AUDIT_STATUS_OPTIONS,
TRANSFER_STATUS_OPTIONS,
} = useWithdrawModel();
const { containerRef, height } = useContainerSize({ headerOffset: 55 });
/** 最终表格列:模型列 + 操作 */
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 100,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="申请人昵称" name="searchUserName">
<Input
placeholder="请输入"
style={{ width: '160px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="手机号" name="searchPhone">
<Input
placeholder="请输入"
style={{ width: '160px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="真实姓名" name="realName">
<Input
placeholder="请输入"
style={{ width: '160px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="审核状态" name="auditStatus">
<Select
value={filterForm.auditStatus}
options={AUDIT_STATUS_OPTIONS as any}
style={{ width: '140px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.auditStatus = val || '')}
/>
</Form.Item>
<Form.Item label="到账状态" name="transferStatus">
<Select
value={filterForm.transferStatus}
options={TRANSFER_STATUS_OPTIONS as any}
style={{ width: '140px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.transferStatus = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</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,
onAudit: handleAudit,
onView: handleView,
}),
}}
</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>
{/* ===== 审核弹窗 ===== */}
<WithdrawAuditModal
visible={auditVisible.value}
record={currentRecord.value}
onClose={handleCloseAudit}
/>
</div>
);
},
@@ -0,0 +1,342 @@
import { reactive, toRef, Ref } from 'vue';
import { message } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 审核状态选项(筛选) */
export const AUDIT_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: '待审核', label: '待审核' },
{ value: '审核通过', label: '审核通过' },
{ value: '审核不通过', label: '审核不通过' },
] as const;
/** 到账状态选项(筛选) */
export const TRANSFER_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: '到账成功', label: '到账成功' },
{ value: '到账失败', label: '到账失败' },
{ value: '-', label: '-' },
] as const;
/** 提现类型选项(筛选) */
export const WITHDRAW_TYPE_OPTIONS = [
{ value: '', label: '全部' },
{ value: '银行卡', label: '银行卡' },
{ value: '支付宝', label: '支付宝' },
{ value: '微信', label: '微信' },
] as const;
// ============================================================
// 提现假数据(4 条,覆盖各审核/到账状态组合)
// ============================================================
const MOCK_DATA = [
{
key: '1',
nickName: '可乐',
phone: '17762466262',
realName: '可乐',
withdrawType: '银行卡',
withdrawAmount: 1.0,
feeRate: 0.006,
feeAmount: 0.01,
transferAmount: 0.99,
auditStatus: '待审核',
transferStatus: '',
thirdNo: '',
applyTime: '2026-04-11 09:53',
// 银行卡信息
bank: {
cardType: '个人',
holder: '龚',
cardNo: '6215581807006475126',
bankName: '交通银行',
branchName: '交通银行宜昌西坝支行',
},
// 支付信息
pay: {
transferTime: '',
merchantNo: 'WD04111775872421935100',
},
},
{
key: '2',
nickName: '李四',
phone: '12345678998',
realName: '李四',
withdrawType: '支付宝',
withdrawAmount: 200.0,
feeRate: 0.006,
feeAmount: 1.2,
transferAmount: 198.8,
auditStatus: '审核通过',
transferStatus: '到账成功',
thirdNo: 'yyyyyyyyyy',
applyTime: '2026-05-25 14:30:00',
bank: {
cardType: '个人',
holder: '李四',
cardNo: '6222021234567890123',
bankName: '工商银行',
branchName: '工商银行北京中关村支行',
},
pay: {
transferTime: '2026-05-25 14:35:00',
merchantNo: 'WD0000111122223333',
},
// 审核信息(已审核后展示)
auditTime: '2026-05-25 14:32:00',
auditor: '管理员A',
auditImages: [],
},
{
key: '3',
nickName: '王五',
phone: '13800138000',
realName: '王五',
withdrawType: '微信',
withdrawAmount: 500.0,
feeRate: 0.006,
feeAmount: 3.0,
transferAmount: 497.0,
auditStatus: '审核通过',
transferStatus: '到账失败',
thirdNo: 'zzzzzzzzzz',
applyTime: '2026-05-24 11:15:00',
bank: {
cardType: '个人',
holder: '王五',
cardNo: '微信钱包',
bankName: '微信支付',
branchName: '-',
},
pay: {
transferTime: '',
merchantNo: 'WD9999888877776666',
},
// 审核信息(已审核后展示)
auditTime: '2026-05-24 11:20:00',
auditor: '管理员B',
auditImages: [],
},
{
key: '4',
nickName: '赵六',
phone: '13900139001',
realName: '赵六',
withdrawType: '银行卡',
withdrawAmount: 80.0,
feeRate: 0.006,
feeAmount: 0.48,
transferAmount: 79.52,
auditStatus: '审核不通过',
transferStatus: '',
thirdNo: '',
applyTime: '2026-05-23 09:45:00',
bank: {
cardType: '个人',
holder: '赵六',
cardNo: '6217858000123456789',
bankName: '建设银行',
branchName: '建设银行上海陆家嘴支行',
},
pay: {
transferTime: '',
merchantNo: '',
},
// 审核信息(已审核后展示)
auditTime: '2026-05-23 10:00:00',
auditor: '管理员A',
auditImages: [],
},
];
// ============================================================
// Model
// ============================================================
/**
* 提现申请页数据模型
*/
export function useWithdrawModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
searchUserName: '',
searchPhone: '',
realName: '',
auditStatus: '',
transferStatus: '',
});
// 可搜索字段防抖
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 { debouncedValue: debouncedRealName } = useDebounce(
toRef(filterForm, 'realName') 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 [auditVisible, setAuditVisible] = useState<boolean>(false);
const [currentRecord, setCurrentRecord] = useState<any>({});
// ===== 表格列配置 =====
const columns = [
{ title: '申请人昵称', dataIndex: 'nickName', key: 'nickName', width: 120 },
{ title: '申请人手机号', dataIndex: 'phone', key: 'phone', width: 140 },
{ title: '真实姓名', dataIndex: 'realName', key: 'realName', width: 120 },
{
title: '提现类型',
dataIndex: 'withdrawType',
key: 'withdrawType',
width: 110,
},
{
title: '提现金额',
dataIndex: 'withdrawAmount',
key: 'withdrawAmount',
width: 120,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '到账金额',
dataIndex: 'transferAmount',
key: 'transferAmount',
width: 120,
customRender: ({ text }: { text: number }) => `${(text || 0).toFixed(2)}`,
},
{
title: '审核状态',
dataIndex: 'auditStatus',
key: 'auditStatus',
width: 110,
},
{
title: '到账状态',
dataIndex: 'transferStatus',
key: 'transferStatus',
width: 110,
},
{ title: '第三方单号', dataIndex: 'thirdNo', key: 'thirdNo', width: 160 },
{
title: '申请时间',
dataIndex: 'applyTime',
key: 'applyTime',
width: 170,
},
];
// ===== 方法 =====
/** 查询(节流 500ms */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
nickName: debouncedUserName.value,
phone: debouncedPhone.value,
realName: debouncedRealName.value,
auditStatus: filterForm.auditStatus,
transferStatus: filterForm.transferStatus,
});
// 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.realName = '';
filterForm.auditStatus = '';
filterForm.transferStatus = '';
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();
};
/**
* 打开审核弹窗
* 真实场景应调用 API;此处直接用列表中的 record
*/
const handleAudit = (record: any) => {
setCurrentRecord(record);
setAuditVisible(true);
};
/** 关闭审核弹窗 */
const handleCloseAudit = () => {
setAuditVisible(false);
};
/**
* 提交审核结果(在弹窗中调用)
* pass = true 通过 / false 不通过
*/
const submitAudit = (pass: boolean, _remark: string, _images: string[]) => {
setDataSource(
dataSource.value.map((item) =>
item.key === currentRecord.value.key
? { ...item, auditStatus: pass ? '审核通过' : '审核不通过' }
: item,
),
);
message.success(pass ? '已审核通过' : '已审核不通过');
handleCloseAudit();
};
/** 查看:打开同一个详情弹窗(只读展示审核信息) */
const handleView = (record: any) => {
setCurrentRecord(record);
setAuditVisible(true);
};
return {
filterForm,
loading,
dataSource,
columns,
pagination,
auditVisible,
currentRecord,
handleSearch,
handleReset,
handlePageChange,
handleAudit,
handleCloseAudit,
submitAudit,
handleView,
AUDIT_STATUS_OPTIONS: AUDIT_STATUS_OPTIONS as any,
TRANSFER_STATUS_OPTIONS: TRANSFER_STATUS_OPTIONS as any,
};
}
+8 -1
View File
@@ -3,6 +3,7 @@ import { Button, Checkbox, Form, FormItem, Input, message } from 'ant-design-vue
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { auth } from '@/hooks/useAuth';
import { useEffect } from '@/hooks/useEffect';
import { useUserStore } from '@/stores/userStore';
import styles from './index.module.less';
interface LoginForm {
@@ -50,7 +51,13 @@ export default defineComponent({
try {
await new Promise((r) => setTimeout(r, 600));
await auth.login('mock_token_' + Date.now());
const token = 'mock_token_' + Date.now();
// 写入账号信息到 userStore
const { setUser } = useUserStore();
setUser({ phone: form.username, nickname: form.username, token });
await auth.login(token);
message.success('登录成功');
if (rememberMe.value) {
@@ -0,0 +1,33 @@
.form {
:global {
.ant-form-item {
margin-bottom: 16px;
}
}
}
.treeWrapper {
max-height: 380px;
overflow: auto;
padding: 8px 12px;
border: 1px solid #f0f0f0;
border-radius: 4px;
background: #fafafa;
}
.footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
border-top: 1px solid #f0f0f0;
margin-top: 8px;
}
.modal {
:global {
.ant-modal-body {
padding: 16px 24px 0;
}
}
}
@@ -0,0 +1,141 @@
import { defineComponent, ref, reactive } from 'vue';
import { useEffect } from '@/hooks';
import { Modal, Form, Input, Tree, Button } from 'ant-design-vue';
import type { TreeProps } from 'ant-design-vue';
import { roleNameRules, PERMISSION_TREE } from '../controller';
import styles from './RoleFormModal.module.less';
interface RoleFormModalProps {
visible: boolean;
record: any;
submitting?: boolean;
onClose: () => void;
onSave: (formData: any) => void;
}
/** 默认表单数据 */
const getDefaultForm = () => ({
roleName: '',
checkedKeys: [] as string[],
});
/** 编辑模式默认勾选:所有权限(演示用) */
const ALL_KEYS = (() => {
const keys: string[] = [];
const walk = (nodes: any[]) => {
for (const n of nodes) {
keys.push(n.key);
if (n.children?.length) walk(n.children);
}
};
walk(PERMISSION_TREE);
return keys;
})();
export default defineComponent({
name: 'RoleFormModal',
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: RoleFormModalProps) {
const formRef = ref<any>();
const formData = reactive(getDefaultForm());
/** 根据 record 初始化表单 */
const initFormFromRecord = (record: any) => {
const fresh = getDefaultForm();
if (!record) {
Object.assign(formData, fresh);
return;
}
Object.assign(formData, {
...fresh,
roleName: record.roleName || '',
// 编辑时默认全选(演示用,后续应按 record.permissions 回填)
checkedKeys: [...ALL_KEYS],
});
};
/** 监听 visible 重置 */
useEffect(() => {
if (props.visible) {
initFormFromRecord(props.record);
setTimeout(() => formRef.value?.clearValidate(), 0);
}
}, [() => props.visible]);
/** Tree 勾选回调(受控) */
const handleCheck: TreeProps['onCheck'] = (checked) => {
// checked 可能是 { checked: string[], halfChecked: string[] } 或 string[]
const keys = Array.isArray(checked) ? checked : (checked as any).checked;
formData.checkedKeys = keys as string[];
};
/** 提交 */
const handleSubmit = async () => {
try {
await formRef.value?.validate();
} catch {
return;
}
props.onSave({
roleName: formData.roleName,
permissions: formData.checkedKeys,
});
};
return () => {
const isEdit = !!props.record;
return (
<Modal
title={isEdit ? '编辑角色' : '新增角色'}
visible={props.visible}
onCancel={props.onClose}
width={520}
destroyOnClose
footer={null}
centered
class={styles.modal}
>
<Form ref={formRef} layout="vertical" model={formData} class={styles.form} requiredMark>
{/* 角色名称 */}
<Form.Item label="角色名称" name="roleName" rules={roleNameRules}>
<Input
placeholder="请输入"
maxlength={20}
allowClear
v-model:value={formData.roleName}
/>
</Form.Item>
{/* 菜单权限配置 */}
<Form.Item label="菜单权限配置" name="permissions">
<div class={styles.treeWrapper}>
<Tree
checkable
defaultExpandAll
treeData={PERMISSION_TREE as any}
checkedKeys={formData.checkedKeys}
onCheck={handleCheck as any}
/>
</div>
</Form.Item>
</Form>
{/* 底部按钮 */}
<div class={styles.footer}>
<Button onClick={props.onClose}></Button>
<Button type="primary" loading={props.submitting} onClick={handleSubmit}>
</Button>
</div>
</Modal>
);
};
},
});
@@ -0,0 +1,23 @@
.filter {
margin-bottom: 16px;
}
.bottom {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid #f0f0f0;
}
.total {
color: rgba(0, 0, 0, 0.65);
font-size: 13px;
}
.paginationRow {
display: flex;
justify-content: flex-end;
margin-top: 12px;
}
@@ -0,0 +1,136 @@
import { defineComponent, ref, reactive, computed } from 'vue';
import { Modal, Form, Input, Table, Button, Space, Pagination } from 'ant-design-vue';
import { useEffect, useState } from '@/hooks';
import styles from './UserListModal.module.less';
interface UserListModalProps {
visible: boolean;
role: any;
users: any[];
renderStatus: (status: string) => any;
onClose: () => void;
}
export default defineComponent({
name: 'RoleUserListModal',
props: {
visible: { type: Boolean, default: false },
role: { type: Object, default: null },
users: { type: Array, default: () => [] },
renderStatus: { type: Function, required: true },
onClose: { type: Function, required: true },
},
setup(props: UserListModalProps) {
const filterForm = reactive({ searchKeyword: '' });
const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
/** 过滤后的用户列表 */
const filteredUsers = computed(() => {
const kw = filterForm.searchKeyword.trim();
if (!kw) return props.users;
return props.users.filter(
(u: any) => u.realName.includes(kw) || (u.phone && u.phone.includes(kw)),
);
});
/** 监听 visible/users 变化重置分页 */
useEffect(() => {
setPagination({ current: 1, pageSize: 10, total: filteredUsers.value.length });
}, [() => props.visible, () => props.users.length]);
const handleSearch = () => {
setPagination({ ...pagination.value, total: filteredUsers.value.length, current: 1 });
};
const handleReset = () => {
filterForm.searchKeyword = '';
setPagination({ current: 1, pageSize: 10, total: props.users.length });
};
const handlePageChange = (page: number, pageSize: number) => {
setPagination({ ...pagination.value, current: page, pageSize });
};
return () => {
const roleName = props.role?.roleName || '';
const columns = [
{ title: '姓名', dataIndex: 'realName', key: 'realName', width: 120 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 160 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 200 },
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
align: 'center' as const,
customRender: ({ text }: { text: string }) => props.renderStatus(text),
},
];
return (
<Modal
title={`${roleName} · 用户列表`}
visible={props.visible}
onCancel={props.onClose}
width={640}
footer={null}
centered
destroyOnClose
>
{/* 筛选 */}
<div class={styles.filter}>
<Form layout="inline" model={filterForm}>
<Form.Item label="姓名/手机号" name="searchKeyword">
<Input
placeholder="姓名/手机号..."
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" onClick={handleSearch}>
</Button>
<Button onClick={handleReset}></Button>
</Space>
</Form.Item>
</Form>
</div>
{/* 表格 */}
<Table
columns={columns}
dataSource={filteredUsers.value}
size="small"
pagination={false}
bordered
rowKey="key"
/>
{/* 底部:共 X 人 + 关闭按钮 */}
<div class={styles.bottom}>
<div class={styles.total}> {filteredUsers.value.length} </div>
<Button onClick={props.onClose}></Button>
</div>
{/* 分页(右侧) */}
{filteredUsers.value.length > pagination.value.pageSize && (
<div class={styles.paginationRow}>
<Pagination
current={pagination.value.current}
pageSize={pagination.value.pageSize}
total={filteredUsers.value.length}
size="small"
onChange={handlePageChange}
/>
</div>
)}
</Modal>
);
};
},
});
+65
View File
@@ -0,0 +1,65 @@
/**
* 角色权限 - 表单域控制器
*
* 集中管理角色表单的规则、菜单权限树 mock 数据与提示文案。
*/
import type { Rule } from 'ant-design-vue/es/form';
// ============================================================
// 规则
// ============================================================
/** 角色名称规则:必填 + 长度限制 */
export const roleNameRules: Rule[] = [
{ required: true, message: '请输入角色名称' },
{ max: 20, message: '角色名称最多 20 个字符' },
];
// ============================================================
// 菜单权限树(mock
// ============================================================
export interface MenuPermNode {
/** 唯一 key,作为 Tree 节点的 key */
key: string;
/** 显示标题 */
title: string;
/** 子节点 */
children?: MenuPermNode[];
}
/**
* 完整菜单权限树。
* 后续可改为从后端接口拉取(接口应返回该结构)。
*/
export const PERMISSION_TREE: MenuPermNode[] = [
{
key: 'events',
title: '赛事管理',
children: [
{
key: 'events.list',
title: '赛事列表',
children: [
{ key: 'events.list.view', title: '赛事列表-查看' },
{ key: 'events.list.on', title: '赛事列表-上架' },
{ key: 'events.list.off', title: '赛事列表-下架' },
{ key: 'events.rules.view', title: '赛事规程-查看' },
],
},
{
key: 'orders',
title: '订单管理',
children: [
{ key: 'orders.view', title: '订单管理-查看' },
{ key: 'orders.refund', title: '订单管理-重新退款' },
],
},
{ key: 'users', title: '用户列表' },
],
},
{
key: 'events_logs',
title: '赛事操作日志',
},
];
+47
View File
@@ -0,0 +1,47 @@
/**
* 表格 body 容器:占满 flex 剩余空间
*/
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
/* 用户数链接 */
.userCountLink {
font-variant-numeric: tabular-nums;
}
/* ===== 删除确认弹窗 ===== */
.confirmContent {
padding: 4px 24px;
font-size: 14px;
color: rgba(0, 0, 0, 0.85);
strong {
margin: 0 4px;
font-weight: 600;
}
}
.confirmTip {
margin-top: 8px;
font-size: 12px;
color: rgba(0, 0, 0, 0.45);
line-height: 1.5;
}
:global(.deleteConfirmModal) {
.ant-modal-confirm-body {
padding: 24px !important;
}
}
+194 -1
View File
@@ -1,4 +1,76 @@
import { defineComponent } from 'vue';
import { Button, Input, Table, Form, Space, Select, Modal, Pagination } from 'ant-design-vue';
import type { ModalProps } from 'ant-design-vue';
import { useRoleModel } from './model/useRoleModel';
import { useContainerSize } from '@/hooks';
import RoleFormModal from './components/RoleFormModal';
import UserListModal from './components/UserListModal';
import styles from './index.module.less';
/**
* bodyCell 渲染
*/
function renderBodyCell({
column,
record,
onViewUsers,
onEdit,
onDelete,
}: {
column: any;
text: any;
record: any;
onViewUsers: (record: any) => void;
onEdit: (record: any) => void;
onDelete: (record: any) => void;
}) {
if (column.dataIndex === 'userCount') {
return (
<a class={styles.userCountLink} onClick={() => onViewUsers(record)}>
{record.userCount}
</a>
);
}
if (column.key === 'action') {
return (
<Space>
<Button type="link" size="small" onClick={() => onEdit(record)}>
</Button>
<Button type="link" size="small" danger onClick={() => onDelete(record)}>
</Button>
</Space>
);
}
return;
}
/**
* 删除角色二次确认
*/
function confirmDelete({ record, onOk }: { record: any; onOk: (record: any) => void }) {
Modal.confirm({
title: '确认删除',
icon: null,
class: styles.deleteConfirmModal,
content: (
<div class={styles.confirmContent}>
<div>
<span></span>
<strong>{record.roleName}</strong>
<span></span>
</div>
<div class={styles.confirmTip}></div>
</div>
),
okText: '确认',
cancelText: '取消',
okButtonProps: { danger: true } as ModalProps['okButtonProps'],
onOk: () => onOk(record),
});
}
/**
* 角色权限
@@ -6,9 +78,130 @@ import { defineComponent } from 'vue';
export default defineComponent({
name: 'SystemRoles',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
pagination,
formVisible,
editingRecord,
formSubmitting,
userListVisible,
currentRole,
handleSearch,
handleReset,
handlePageChange,
handleAdd,
handleEdit,
handleCloseForm,
handleSave,
handleDelete,
handleViewUsers,
handleCloseUserList,
getRoleUsers,
renderStatus,
} = useRoleModel();
const { containerRef, height } = useContainerSize();
const triggerDelete = (record: any) => confirmDelete({ record, onOk: handleDelete });
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 140,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="角色" name="searchKeyword">
<Input
placeholder="请输入"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item>
<Space>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</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,
onViewUsers: handleViewUsers,
onEdit: handleEdit,
onDelete: triggerDelete,
}),
}}
</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>
{/* ===== 角色表单弹窗 ===== */}
{formVisible.value && (
<RoleFormModal
visible={formVisible.value}
record={editingRecord.value}
submitting={formSubmitting.value}
onClose={handleCloseForm}
onSave={handleSave}
/>
)}
{/* ===== 角色用户列表弹窗 ===== */}
{userListVisible.value && (
<UserListModal
visible={userListVisible.value}
role={currentRole.value}
users={getRoleUsers(currentRole.value?.roleId || '')}
renderStatus={renderStatus}
onClose={handleCloseUserList}
/>
)}
</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';
// ============================================================
// 假数据
// ============================================================
const MOCK_DATA = [
{
key: '1',
roleId: 'R20250601001',
roleName: '超级管理员',
userCount: 1,
createTime: '2025-06-01 09:00:00',
},
{
key: '2',
roleId: 'R20250815001',
roleName: '运营管理员',
userCount: 3,
createTime: '2025-08-15 14:30:00',
},
{
key: '3',
roleId: 'R20251010001',
roleName: '财务',
userCount: 2,
createTime: '2025-10-10 10:15:00',
},
{
key: '4',
roleId: 'R20260120001',
roleName: '客服',
userCount: 4,
createTime: '2026-01-20 16:00:00',
},
];
/** 角色下用户列表 mock */
const MOCK_USERS: Record<string, any[]> = {
R20250601001: [
{
key: '1',
userId: 'U001',
realName: '张超管',
phone: '13900000001',
createTime: '2025-06-01 09:00:00',
status: 'active',
},
],
R20250815001: [
{
key: '1',
userId: 'U002',
realName: '李运营',
phone: '15900000002',
createTime: '2026-01-10 16:00:00',
status: 'disabled',
},
{
key: '2',
userId: 'U003',
realName: '王运营',
phone: '15900000001',
createTime: '2025-10-20 10:00:00',
status: 'active',
},
{
key: '3',
userId: 'U004',
realName: '张运营',
phone: '13900000002',
createTime: '2025-08-15 14:30:00',
status: 'active',
},
],
R20251010001: [
{
key: '1',
userId: 'U005',
realName: '赵财务',
phone: '13800000005',
createTime: '2025-10-10 10:15:00',
status: 'active',
},
{
key: '2',
userId: 'U006',
realName: '钱财务',
phone: '13800000006',
createTime: '2025-10-12 11:00:00',
status: 'active',
},
],
R20260120001: [
{
key: '1',
userId: 'U007',
realName: '孙客服',
phone: '13700000007',
createTime: '2026-01-20 16:00:00',
status: 'active',
},
{
key: '2',
userId: 'U008',
realName: '周客服',
phone: '13700000008',
createTime: '2026-01-21 09:30:00',
status: 'active',
},
{
key: '3',
userId: 'U009',
realName: '吴客服',
phone: '13700000009',
createTime: '2026-01-22 10:00:00',
status: 'active',
},
{
key: '4',
userId: 'U010',
realName: '郑客服',
phone: '13700000010',
createTime: '2026-01-23 14:00:00',
status: 'active',
},
],
};
// ============================================================
// 状态文本/颜色映射
// ============================================================
const STATUS_MAP: Record<string, { label: string; color: string }> = {
active: { label: '正常', color: 'green' },
disabled: { label: '禁用', color: 'red' },
};
// ============================================================
// Model
// ============================================================
/**
* 角色权限页数据模型
*/
export function useRoleModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
searchKeyword: '',
});
// 防抖 300ms
const { debouncedValue: debouncedKeyword } = useDebounce(
toRef(filterForm, 'searchKeyword') 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 [formVisible, setFormVisible] = useState<boolean>(false);
const [editingRecord, setEditingRecord] = useState<any>(null);
const [userListVisible, setUserListVisible] = useState<boolean>(false);
const [currentRole, setCurrentRole] = useState<any>(null);
// ===== 提交态 =====
const [formSubmitting, setFormSubmitting] = useState<boolean>(false);
// ===== 表格列配置 =====
const columns = [
{ title: '角色名称', dataIndex: 'roleName', key: 'roleName', width: 200 },
{
title: '用户数',
dataIndex: 'userCount',
key: 'userCount',
width: 120,
align: 'center' as const,
customRender: ({ text }: { text: number }) => `${text}`,
},
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 200 },
];
// ===== 计算属性 =====
const hasFilter = computed(() => debouncedKeyword.value.trim() !== '');
const isEdit = computed(() => editingRecord.value !== null);
// ===== 方法 =====
/** 查询 */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', { keyword: debouncedKeyword.value });
// 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.searchKeyword = '';
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);
setFormVisible(true);
};
/** 编辑 */
const handleEdit = (record: any) => {
setEditingRecord(record);
setFormVisible(true);
};
/** 关闭表单弹窗 */
const handleCloseForm = () => {
setFormVisible(false);
setEditingRecord(null);
};
/** 提交(新增/编辑) */
const handleSave = useThrottleFn(async (formPayload: any) => {
if (formSubmitting.value) return;
setFormSubmitting(true);
try {
console.log(isEdit.value ? '编辑角色' : '新增角色', formPayload);
// TODO: 替换为真实 API 调用
message.success(isEdit.value ? '编辑成功' : '新增成功');
handleCloseForm();
handleSearch();
} catch (error: any) {
message.error(error.msg || '操作失败');
} finally {
setFormSubmitting(false);
}
}, 500);
/** 删除 */
const handleDelete = useThrottleFn(async (record: any) => {
setLoading(true);
try {
console.log('删除角色:', record.roleId);
// TODO: 替换为真实 API 调用
setDataSource(dataSource.value.filter((item: any) => item.key !== record.key));
message.success('删除成功');
} catch (error: any) {
message.error(error.msg || '删除失败');
} finally {
setLoading(false);
}
}, 500);
/** 打开用户列表弹窗 */
const handleViewUsers = (record: any) => {
setCurrentRole(record);
setUserListVisible(true);
};
/** 关闭用户列表弹窗 */
const handleCloseUserList = () => {
setUserListVisible(false);
setCurrentRole(null);
};
/** 根据 roleId 获取该角色下的用户列表 */
const getRoleUsers = (roleId: string) => MOCK_USERS[roleId] || [];
/** 状态 Tag 渲染 */
const renderStatus = (status: string) => {
const info = STATUS_MAP[status] || { label: status || '-', color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
};
return {
filterForm,
loading,
dataSource,
columns,
pagination,
hasFilter,
formVisible,
editingRecord,
isEdit,
formSubmitting,
userListVisible,
currentRole,
handleSearch,
handleReset,
handlePageChange,
handleAdd,
handleEdit,
handleCloseForm,
handleSave,
handleDelete,
handleViewUsers,
handleCloseUserList,
getRoleUsers,
renderStatus,
};
}
@@ -0,0 +1,52 @@
/* ===== 表单行/列布局 ===== */
.row {
display: flex;
gap: 16px;
flex-wrap: wrap;
}
.col {
flex: 1;
min-width: 0;
}
/* 让 antd Form.Item 在 col 里能正确控制宽度 */
.form {
:global {
.ant-form-item {
flex: 1;
min-width: 0;
}
}
}
/* ===== 密码区重置链接 ===== */
.resetLink {
font-size: 14px;
color: #1677ff;
cursor: pointer;
user-select: none;
&:hover {
color: #4096ff;
}
}
/* ===== 取消重置行 ===== */
.cancelRow {
display: flex;
justify-content: flex-end;
margin-top: -8px;
margin-bottom: 16px;
font-size: 12px;
}
/* ===== 底部按钮 ===== */
.footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
border-top: 1px solid #f0f0f0;
margin-top: 8px;
}
@@ -0,0 +1,222 @@
import { defineComponent, ref, reactive } from 'vue';
import { useEffect } from '@/hooks';
import { Modal, Form, Input, Select, Button } from 'ant-design-vue';
import {
ROLE_FORM_OPTIONS,
PASSWORD_PLACEHOLDER,
realNameRules,
phoneRules,
passwordRules,
confirmPasswordRules,
roleRules,
} from '../controller';
import styles from './UserFormModal.module.less';
interface UserFormModalProps {
visible: boolean;
record: any;
submitting?: boolean;
onClose: () => void;
onSave: (formData: any) => void;
}
/** 默认表单数据 */
const getDefaultForm = () => ({
realName: '',
phone: '',
password: '',
confirmPassword: '',
role: '',
});
export default defineComponent({
name: 'UserFormModal',
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: UserFormModalProps) {
const formRef = ref<any>();
const formData = reactive(getDefaultForm());
/** 编辑模式下是否处于"重置密码"状态 */
const isResetting = ref(false);
/** 根据 record 初始化表单 */
const initFormFromRecord = (record: any) => {
const fresh = getDefaultForm();
if (!record) {
Object.assign(formData, fresh);
isResetting.value = false;
return;
}
Object.assign(formData, {
...fresh,
realName: record.realName || '',
phone: record.phone || '',
role: record.role || '',
});
isResetting.value = false;
};
/** 监听 visible 变化重置表单 */
useEffect(() => {
if (props.visible) {
initFormFromRecord(props.record);
isResetting.value = false;
setTimeout(() => formRef.value?.clearValidate(), 0);
}
}, [() => props.visible]);
/** 点击"重置密码" */
const handleResetPassword = () => {
isResetting.value = true;
formData.password = '';
formData.confirmPassword = '';
};
/** 提交 */
const handleSubmit = async () => {
try {
await formRef.value?.validate();
} catch {
return;
}
// 编辑模式下,未触发重置密码时,不提交密码字段
const payload: any = {
realName: formData.realName,
phone: formData.phone,
role: formData.role,
};
if (props.record) {
if (isResetting.value) {
payload.password = formData.password;
}
} else {
// 新增:密码必传
payload.password = formData.password;
}
props.onSave(payload);
};
/** 关闭 */
const handleClose = () => {
props.onClose();
};
return () => {
const isEdit = !!props.record;
return (
<Modal
title={isEdit ? '编辑用户' : '新增用户'}
visible={props.visible}
onCancel={handleClose}
width={580}
destroyOnClose
footer={null}
centered
>
<Form ref={formRef} layout="vertical" model={formData} class={styles.form} requiredMark>
{/* 姓名 / 手机号:同一行 */}
<div class={styles.row}>
<Form.Item label="姓名" name="realName" rules={realNameRules} class={styles.col}>
<Input
placeholder="真实姓名"
maxlength={8}
allowClear
v-model:value={formData.realName}
/>
</Form.Item>
<Form.Item label="手机号" name="phone" rules={phoneRules} class={styles.col}>
<Input
placeholder="11位手机号"
maxlength={11}
allowClear
v-model:value={formData.phone}
/>
</Form.Item>
</div>
{/* ====== 密码区 + 角色 ====== */}
{isEdit && !isResetting.value ? (
/* 编辑模式未重置:密码占位 + 角色 同一行 */
<div class={styles.row}>
<Form.Item label="密码" class={styles.col}>
<Input
value={PASSWORD_PLACEHOLDER}
readonly
suffix={
<a class={styles.resetLink} onClick={handleResetPassword}>
</a>
}
/>
</Form.Item>
<Form.Item label="角色" name="role" rules={roleRules} class={styles.col}>
<Select
options={ROLE_FORM_OPTIONS as any}
placeholder="请选择角色"
v-model:value={formData.role}
/>
</Form.Item>
</div>
) : (
<>
{/* 新密码 / 确认密码:同一行 */}
<div class={styles.row}>
<Form.Item
label={isEdit ? '新密码' : '初始密码'}
name="password"
rules={passwordRules}
class={styles.col}
>
<Input.Password
placeholder={isEdit ? '请输入新密码' : '至少8位,含字母+数字'}
allowClear
v-model:value={formData.password}
/>
</Form.Item>
<Form.Item
label="确认密码"
name="confirmPassword"
class={styles.col}
rules={confirmPasswordRules(() => formData.password)}
>
<Input.Password
placeholder="再次输入密码"
allowClear
v-model:value={formData.confirmPassword}
/>
</Form.Item>
</div>
{/* 角色:单独一行 */}
<Form.Item label="角色" name="role" rules={roleRules}>
<Select
options={ROLE_FORM_OPTIONS as any}
placeholder="请选择角色"
v-model:value={formData.role}
style={{ width: '200px' }}
/>
</Form.Item>
</>
)}
</Form>
{/* 底部按钮 */}
<div class={styles.footer}>
<Button onClick={handleClose}></Button>
<Button type="primary" loading={props.submitting} onClick={handleSubmit}>
</Button>
</div>
</Modal>
);
};
},
});
+96
View File
@@ -0,0 +1,96 @@
/**
* 用户管理 - 表单域控制器
*
* 集中管理用户新增/编辑弹窗的所有规则校验、下拉选项与常量。
* 各规则数组可直接传给 antd Form.Item 的 rules prop。
*/
import type { Rule } from 'ant-design-vue/es/form';
import { isChinaPhone, isValidPassword, isValidRealName } from '@/utils/form';
// ============================================================
// 常量
// ============================================================
/** 密码占位符(写死长度,避免暴露真实密码长度) */
export const PASSWORD_PLACEHOLDER = '********';
/** 角色下拉选项(表单使用) */
export const ROLE_FORM_OPTIONS = [
{ value: 'admin', label: '超级管理员' },
{ value: 'operator', label: '运营人员' },
{ value: 'auditor', label: '审核人员' },
] as const;
// ============================================================
// 真实姓名规则
// ============================================================
export const realNameRules: Rule[] = [
{ required: true, message: '请输入姓名' },
{ max: 8, message: '姓名最多 8 个字符' },
{
validator: (_rule: unknown, value: string) => {
if (!value) return Promise.resolve();
if (!isValidRealName(value)) {
return Promise.reject(new Error('姓名仅支持中英文或数字,1-8 个字符'));
}
return Promise.resolve();
},
},
];
// ============================================================
// 手机号规则
// ============================================================
export const phoneRules: Rule[] = [
{ required: true, message: '请输入手机号' },
{
validator: (_rule: unknown, value: string) => {
if (!value) return Promise.resolve();
if (!isChinaPhone(value)) {
return Promise.reject(new Error('请输入正确的11位中国大陆手机号'));
}
return Promise.resolve();
},
},
];
// ============================================================
// 密码规则
// ============================================================
export const passwordRules: Rule[] = [
{ required: true, message: '请输入密码' },
{
validator: (_rule: unknown, value: string) => {
if (!value) return Promise.resolve();
if (!isValidPassword(value)) {
return Promise.reject(new Error('密码至少8位,需包含字母与数字'));
}
return Promise.resolve();
},
},
];
/** 确认密码规则:必须与 password 字段一致 */
export function confirmPasswordRules(getPassword: () => string): Rule[] {
return [
{ required: true, message: '请再次输入密码' },
{
validator: (_rule: unknown, value: string) => {
if (!value) return Promise.resolve();
if (value !== getPassword()) {
return Promise.reject(new Error('两次输入的密码不一致'));
}
return Promise.resolve();
},
},
];
}
// ============================================================
// 角色规则
// ============================================================
export const roleRules: Rule[] = [{ required: true, message: '请选择角色' }];
+43
View File
@@ -0,0 +1,43 @@
/**
* 表格 body 容器:占满 flex 剩余空间,
* 确保 antd 嵌套 div 逐层传递 height: 100%
* 使得 Table scroll.y 能正确解析。
*/
.tableBody {
flex: 1;
min-height: 0;
overflow: hidden;
:global {
.ant-spin-nested-loading,
.ant-spin-container,
.ant-table,
.ant-table-container {
height: 100%;
}
}
}
/* ===== 禁用/启用 二次确认弹窗 ===== */
/* 内容块:左右加 padding,按用户要求 */
.confirmContent {
display: flex;
align-items: center;
flex-wrap: wrap;
padding: 4px 0;
font-size: 14px;
color: rgba(0, 0, 0, 0.85);
strong {
margin: 0 4px;
font-weight: 600;
}
}
/* antd Modal.confirm 默认 body 已经有 padding,这里额外覆盖一下确保一致 */
:global(.toggleConfirmModal) {
.ant-modal-confirm-body {
padding: 24px !important;
}
}
+199 -2
View File
@@ -1,14 +1,211 @@
import { defineComponent } from 'vue';
import { Button, Input, Table, Form, Space, Select, Modal, Pagination } from 'ant-design-vue';
import { useUserModel, USER_ROLE_OPTIONS, USER_STATUS_OPTIONS } from './model/useUserModel';
import { useContainerSize } from '@/hooks';
import UserFormModal from './components/UserFormModal';
import styles from './index.module.less';
/**
* 用户管理
* bodyCell 渲染函数
*/
function renderBodyCell({
column,
record,
onEdit,
onToggleStatus,
}: {
column: any;
text: any;
record: any;
onEdit: (record: any) => void;
onToggleStatus: (record: any) => void;
}) {
// 操作列
if (column.key === 'action') {
const isActive = record.status === 'active';
return (
<Space>
<Button type="link" size="small" onClick={() => onEdit(record)}>
</Button>
<Button
type="link"
size="small"
danger={isActive}
style={isActive ? {} : { color: '#52c41a' }}
onClick={() => onToggleStatus(record)}
>
{isActive ? '禁用' : '启用'}
</Button>
</Space>
);
}
return;
}
/**
* 禁用/启用 二次确认弹窗
*/
function confirmToggleStatus({ record, onOk }: { record: any; onOk: (record: any) => void }) {
const isActive = record.status === 'active';
const actionText = isActive ? '禁用' : '启用';
Modal.confirm({
title: `确认${actionText}`,
class: styles.toggleConfirmModal,
content: (
<div class={styles.confirmContent}>
<span>{actionText}</span>
<strong>{record.realName}</strong>
<span></span>
</div>
),
okText: '确认',
cancelText: '取消',
okButtonProps: { danger: isActive },
onOk: () => onOk(record),
});
}
/**
* 系统管理 - 用户管理
*/
export default defineComponent({
name: 'SystemUsers',
setup() {
const {
filterForm,
loading,
dataSource,
columns,
pagination,
modalVisible,
editingRecord,
isEdit,
formSubmitting,
handleSearch,
handleReset,
handlePageChange,
handleAdd,
handleEdit,
handleCloseModal,
handleSave,
handleToggleStatus,
} = useUserModel();
const { containerRef, height } = useContainerSize();
/** 触发禁用/启用的二次确认 */
const triggerToggle = (record: any) => {
confirmToggleStatus({ record, onOk: handleToggleStatus });
};
/** 触发编辑 */
const triggerEdit = (record: any) => {
handleEdit(record);
};
/** 表格最终列:模型列 + 操作 */
const tableColumns = [
...columns,
{
title: '操作',
key: 'action',
width: 140,
fixed: 'right' as const,
align: 'center' as const,
},
];
return () => (
<div class="page-container">
<div style={{ padding: '24px', fontSize: '16px', color: '#999' }}> - </div>
{/* ===== 筛选区 ===== */}
<div class="page-filter">
<Form style={{ rowGap: '10px' }} layout="inline" model={filterForm}>
<Form.Item label="用户" name="searchKeyword">
<Input
placeholder="请输入姓名/手机号"
style={{ width: '200px' }}
allowClear
onPressEnter={handleSearch}
/>
</Form.Item>
<Form.Item label="角色" name="role">
<Select
value={filterForm.role}
options={USER_ROLE_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.role = val || '')}
/>
</Form.Item>
<Form.Item label="状态" name="status">
<Select
value={filterForm.status}
options={USER_STATUS_OPTIONS as any}
style={{ width: '120px' }}
allowClear
onUpdate:value={(val: any) => (filterForm.status = val || '')}
/>
</Form.Item>
<Form.Item>
<Space>
<Button onClick={handleReset}></Button>
<Button type="primary" onClick={handleSearch} loading={loading.value}>
</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,
onEdit: triggerEdit,
onToggleStatus: triggerToggle,
}),
}}
</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>
{/* ===== 新增/编辑弹窗 ===== */}
{modalVisible.value && (
<UserFormModal
visible={modalVisible.value}
record={editingRecord.value}
submitting={formSubmitting.value}
onClose={handleCloseModal}
onSave={handleSave}
/>
)}
</div>
);
},
@@ -0,0 +1,248 @@
import { computed, reactive, toRef, Ref, h } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { useState, useDebounce, useThrottleFn } from '@/hooks';
// ============================================================
// 常量
// ============================================================
/** 角色选项(筛选) */
export const USER_ROLE_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'admin', label: '管理员' },
] as const;
/** 状态选项(筛选) */
export const USER_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'active', label: '正常' },
{ value: 'disabled', label: '禁用' },
] as const;
/** 角色文本/颜色映射(表格渲染) */
const ROLE_MAP: Record<string, { label: string; color: string }> = {
admin: { label: '管理员', color: 'blue' },
operator: { label: '运营人员', color: 'cyan' },
auditor: { label: '审核人员', color: 'purple' },
};
/** 状态文本/颜色映射 */
const STATUS_MAP: Record<string, { label: string; color: string }> = {
active: { label: '正常', color: 'green' },
disabled: { label: '禁用', color: 'red' },
};
// ============================================================
// 假数据
// ============================================================
const MOCK_DATA = [
{
key: '1',
userId: 'U20260526001',
realName: '张三',
phone: '15585658975',
role: 'admin',
status: 'active' as 'active' | 'disabled',
createTime: '2026.05.26 08:00:00',
},
{
key: '2',
userId: 'U20260526002',
realName: '王五',
phone: '13800138000',
role: 'admin',
status: 'disabled' as 'active' | 'disabled',
createTime: '2026.05.26 14:00:00',
},
];
// ============================================================
// Model
// ============================================================
/**
* 系统管理 - 用户列表页数据模型
*/
export function useUserModel() {
// ===== 筛选条件 =====
const filterForm = reactive({
searchKeyword: '', // 用户名/手机号
role: '' as '' | 'admin',
status: '' as '' | 'active' | 'disabled',
});
// 防抖 300ms
const { debouncedValue: debouncedKeyword } = useDebounce(
toRef(filterForm, 'searchKeyword') 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);
// ===== 提交态 =====
const [formSubmitting, setFormSubmitting] = useState<boolean>(false);
// ===== 表格列配置 =====
const columns = [
{ title: '姓名', dataIndex: 'realName', key: 'realName', width: 120 },
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 140 },
{
title: '角色',
dataIndex: 'role',
key: 'role',
width: 120,
align: 'center' as const,
customRender: ({ text }: { text: string }) => {
const info = ROLE_MAP[text] || { label: text || '-', color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
},
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
align: 'center' as const,
customRender: ({ text }: { text: string }) => {
const info = STATUS_MAP[text] || { label: text || '-', color: 'default' };
return h(Tag, { color: info.color }, () => info.label);
},
},
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
];
// ===== 计算属性 =====
const hasFilter = computed(() => {
return (
debouncedKeyword.value.trim() !== '' || filterForm.role !== '' || filterForm.status !== ''
);
});
const isEdit = computed(() => editingRecord.value !== null);
// ===== 方法 =====
/** 查询(节流 500ms */
const handleSearch = useThrottleFn(async () => {
setLoading(true);
try {
console.log('搜索条件:', {
keyword: debouncedKeyword.value,
role: filterForm.role,
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.searchKeyword = '';
filterForm.role = '';
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 {
console.log(isEdit.value ? '编辑用户' : '新增用户', formPayload);
// TODO: 替换为真实 API 调用
message.success(isEdit.value ? '编辑成功' : '新增成功');
handleCloseModal();
handleSearch();
} catch (error: any) {
message.error(error.msg || '操作失败');
} finally {
setFormSubmitting(false);
}
}, 500);
/** 启用/禁用切换(节流 500ms */
const handleToggleStatus = useThrottleFn(async (record: any) => {
setLoading(true);
try {
const newStatus = record.status === 'active' ? 'disabled' : 'active';
const actionText = newStatus === 'active' ? '启用' : '禁用';
console.log(`${actionText}用户:`, record.userId);
// 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);
return {
filterForm,
loading,
dataSource,
columns,
pagination,
hasFilter,
modalVisible,
setModalVisible,
editingRecord,
isEdit,
formSubmitting,
handleSearch,
handleReset,
handlePageChange,
handleAdd,
handleEdit,
handleCloseModal,
handleSave,
handleToggleStatus,
};
}
+11 -4
View File
@@ -1,6 +1,13 @@
import router from '@/router';
import { auth } from '@/hooks/useAuth';
const appTitle = import.meta.env.VITE_APP_TITLE || 'CPMS 运营平台';
/** 导航完成后设置页面标题,避免动态路由加载前误匹配 404 导致 title 闪烁 */
function updateDocumentTitle(title?: string) {
document.title = title ? `${title} - ${appTitle}` : appTitle;
}
/**
* 全局路由守卫
* 核心流程:
@@ -15,10 +22,6 @@ import { auth } from '@/hooks/useAuth';
* 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()) {
@@ -51,3 +54,7 @@ router.beforeEach(async (to, _from, next) => {
next();
});
router.afterEach((to) => {
updateDocumentTitle(to.meta.title as string | undefined);
});
+39
View File
@@ -0,0 +1,39 @@
import { reactive, computed, toRefs } from 'vue';
interface UserState {
/** 手机号 */
phone: string;
/** 昵称 */
nickname: string;
/** 登录 token */
token: string;
}
const state = reactive<UserState>({
phone: '13377981125',
nickname: '',
token: '',
});
export function useUserStore() {
const setUser = (user: Partial<UserState>) => {
if (user.phone !== undefined) state.phone = user.phone;
if (user.nickname !== undefined) state.nickname = user.nickname;
if (user.token !== undefined) state.token = user.token;
};
const clearUser = () => {
state.phone = '';
state.nickname = '';
state.token = '';
};
return {
...toRefs(state),
phone: computed(() => state.phone),
nickname: computed(() => state.nickname),
token: computed(() => state.token),
setUser,
clearUser,
};
}
+47
View File
@@ -0,0 +1,47 @@
/**
* 表单正则校验工具
*
* 只导出纯正则常量与独立的校验函数,不做任何 antd/framework 耦合。
* 各页面的 Form.Item rules 应在对应页面目录的 controller.ts 中组装。
*/
// ============================================================
// 正则常量
// ============================================================
/**
* 中国大陆手机号
* - 11 位数字,第二位 3-9
*/
export const CHINA_PHONE_REGEX = /^1[3-9]\d{9}$/;
/**
* 登录密码
* - 至少 8 位,同时包含字母与数字
* - 允许特殊字符 !@#$%^&*()_+-=
*/
export const LOGIN_PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[\w!@#$%^&*()_+\-=]{8,}$/;
/**
* 真实姓名(中文/英文/数字,1-8 位)
*/
export const REAL_NAME_REGEX = /^[\u4e00-\u9fa5A-Za-z0-9·]{1,8}$/;
// ============================================================
// 校验函数
// ============================================================
/** 校验中国大陆手机号 */
export function isChinaPhone(value: unknown): boolean {
return typeof value === 'string' && CHINA_PHONE_REGEX.test(value);
}
/** 校验密码:至少 8 位 + 同时含字母与数字 */
export function isValidPassword(value: unknown): boolean {
return typeof value === 'string' && LOGIN_PASSWORD_REGEX.test(value);
}
/** 校验真实姓名:1-8 个字符 */
export function isValidRealName(value: unknown): boolean {
return typeof value === 'string' && value.length > 0 && REAL_NAME_REGEX.test(value);
}