AccountFormDrawer.tsx
7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { useEffect } from 'react';
import { useMutation } from '@tanstack/react-query';
import { UButton, UDrawer, UForm, useUMessage } from '@uj/ui';
import { user, type OrgNode, type RoleOption, type UserPageItem } from '@/api';
import { CombiForm, type FieldSchema } from '@/components';
import { dataScopeOptions } from '@/constants/dataScope';
import { findOrgPath, toOrgCascaderOptions } from '../tools/account';
interface AccountFormValues extends Record<string, unknown> {
account: string;
name: string;
mobile: string;
email?: string;
orgPath: number[];
dataScope?: number | '';
roleIds: number[];
}
export interface AccountFormDrawerProps {
open: boolean;
account?: UserPageItem;
orgTree: OrgNode[];
roleOptions: RoleOption[];
onClose: () => void;
onSuccess: () => void;
}
export function AccountFormDrawer({
open,
account,
orgTree,
roleOptions,
onClose,
onSuccess,
}: AccountFormDrawerProps) {
const message = useUMessage();
const [form] = UForm.useForm<AccountFormValues>();
const selectedRoleIds = UForm.useWatch('roleIds', form) ?? [];
const isEdit = Boolean(account);
const saveMutation = useMutation({
mutationFn: (values: AccountFormValues) => {
const orgId = values.orgPath.at(-1);
const payload = {
name: values.name.trim(),
mobile: values.mobile,
email: values.email?.trim() || undefined,
orgId: orgId as number,
dataScope: values.dataScope === '' ? undefined : values.dataScope,
roleIds: values.roleIds,
status: account?.status ?? 1,
};
return account
? user.update({ ...payload, userId: account.userId })
: user.create({ ...payload, account: values.account.trim() });
},
onSuccess: () => {
void message.success(isEdit ? '账号已保存' : '账号已创建');
onSuccess();
},
onError: (error: Error) => {
void message.error(error.message || '保存失败,请稍后重试');
},
});
useEffect(() => {
if (!open) return;
const selectedRoleIds = account?.roleCodes?.length
? roleOptions
.filter((item) => item.roleCode && account.roleCodes?.includes(item.roleCode))
.map((item) => item.roleId)
: [];
form.setFieldsValue({
account: account?.account ?? '',
name: account?.name ?? '',
mobile: account?.mobile ?? '',
email: account?.email ?? '',
orgPath: findOrgPath(orgTree, account?.orgId),
dataScope: account?.dataScope ?? '',
roleIds: selectedRoleIds,
});
}, [account, form, open, orgTree, roleOptions]);
const fields: FieldSchema<AccountFormValues>[] = [
{
name: 'account',
label: '账号',
type: 'input',
section: '基本信息',
disabled: isEdit,
inputProps: { maxLength: 20 },
rules: [
{ required: true, message: '请输入账号' },
{ min: 1, max: 20, message: '账号长度为 1-20 个字符' },
],
},
{
name: 'name',
label: '姓名',
type: 'input',
section: '基本信息',
inputProps: { maxLength: 20 },
rules: [
{ required: true, message: '请输入姓名' },
{ min: 1, max: 20, message: '姓名长度为 1-20 个字符' },
],
},
{
name: 'mobile',
label: '手机号',
type: 'input',
section: '基本信息',
inputProps: { inputMode: 'numeric', maxLength: 11 },
normalize: (value) => (typeof value === 'string' ? value.replace(/\D/g, '') : value),
rules: [
{ required: true, message: '请输入手机号' },
{ pattern: /^1\d{10}$/, message: '请输入正确的 11 位手机号' },
],
},
{
name: 'email',
label: '邮箱',
type: 'input',
section: '基本信息',
rules: [{ type: 'email', message: '请输入正确的邮箱地址' }],
},
{
name: 'orgPath',
label: '所属组织',
type: 'cascader',
section: '组织归属',
options: toOrgCascaderOptions(orgTree),
cascaderProps: { changeOnSelect: true, showSearch: true },
rules: [{ required: true, message: '请选择所属组织' }],
},
{
name: 'dataScope',
label: '数据域',
type: 'select',
section: '组织归属',
options: dataScopeOptions,
},
{
name: 'roleIds',
label: '选择角色',
type: 'selectMultiple',
section: '角色分配',
itemStyle: { gridColumn: '1 / -1' },
rules: [{ required: true, message: '请至少选择一个角色' }],
},
];
return (
<UDrawer
open={open}
title={isEdit ? '编辑账号' : '新增账号'}
size={560}
onClose={onClose}
footer={
<div style={footerStyle}>
<UButton type="default" onClick={onClose}>取消</UButton>
<UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}>
保存
</UButton>
</div>
}
>
<CombiForm<AccountFormValues>
mode="form"
form={form}
layout="vertical"
onSubmit={(values) => saveMutation.mutate(values)}
initialValues={{ roleIds: [] }}
fields={fields}
sectionContentStyle={twoColumnStyle}
renderSectionTitle={(title) => <SectionTitle>{title}</SectionTitle>}
renderControl={(field) => {
if (field.name === 'roleIds')
return (
<div style={roleListStyle}>
{roleOptions.map((item) => (
<UButton
key={item.roleId}
type={selectedRoleIds.includes(item.roleId) ? 'primary' : 'default'}
style={roleOptionStyle}
onClick={() => {
const nextRoleIds = selectedRoleIds.includes(item.roleId)
? selectedRoleIds.filter((id) => id !== item.roleId)
: [...selectedRoleIds, item.roleId];
form.setFields([{ name: 'roleIds', value: nextRoleIds, errors: [] }]);
}}
>
{item.roleName}
</UButton>
))}
</div>
);
return undefined;
}}
/>
</UDrawer>
);
}
const footerStyle = { display: 'flex', justifyContent: 'flex-end', gap: 8 };
const twoColumnStyle = { display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 12 };
function SectionTitle({ children }: { children: string }) {
return (
<h3 style={sectionTitleStyle}>
<span style={sectionMarkerStyle} />
{children}
</h3>
);
}
const sectionTitleStyle = {
borderBottom: '1px solid var(--uj-divider)',
alignItems: 'center',
display: 'flex',
gap: 6,
fontSize: 14,
lineHeight: '16px',
margin: '0 0 12px',
padding: '0 0 8px',
};
const sectionMarkerStyle = {
backgroundColor: 'var(--uj-primary)',
borderRadius: 2,
height: 10,
width: 3,
};
const roleListStyle = { display: 'flex', flexWrap: 'wrap', gap: 8 } as const;
const roleOptionStyle = {
alignItems: 'center',
display: 'flex',
height: 30,
margin: 0,
padding: '0 10px',
};