GroupCodeEditor.tsx
10.5 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
UAlert,
UButton,
UCard,
UEmpty,
UForm,
UInput,
UModal,
UResult,
useUMessage,
} from '@uj/ui';
import { CombiForm, DataTable, PageShell, type FieldSchema } from '@/components';
import { getLiveCodeDetail, liveCodeApi } from '@/api';
import { useAccess } from '@/access';
import { UC } from '@/permissions/codes';
import { errorDetail } from '@/utils/error';
import { goTo } from '../Leads/navigate';
import './customerGroup.css';
type Group = Record<string, unknown> & {
groupChatId: string;
groupChatName: string;
disabled?: boolean;
free?: boolean;
};
type Detail = Record<string, unknown> & { groupList?: Group[]; id?: string | number };
type Values = { liveName: string; storeId: string; remark?: string; lockTime: string };
type Props = { params?: { id?: string; mode?: string } };
const text = (value: unknown) =>
value === undefined || value === null || value === '' ? '-' : String(value);
function GroupPicker({
open,
liveCodeId,
selected,
onCancel,
onConfirm,
}: {
open: boolean;
liveCodeId?: string;
selected: Group[];
onCancel: () => void;
onConfirm: (groups: Group[]) => void;
}) {
const [name, setName] = useState('');
const [keys, setKeys] = useState<React.Key[]>(selected.map((item) => item.groupChatId));
const [picked, setPicked] = useState<Group[]>(selected);
useEffect(() => {
if (open) {
setKeys(selected.map((item) => item.groupChatId));
setPicked(selected);
}
}, [open, selected]);
const query = useQuery({
queryKey: ['live-code-groups', name, liveCodeId],
enabled: open,
queryFn: () =>
liveCodeApi.getGroupChatList<Group[]>({
groupChatName: name,
...(liveCodeId ? { id: liveCodeId } : {}),
}),
});
const data = query.data ?? [];
return (
<UModal
open={open}
title="选择企微群聊"
width={1080}
onCancel={onCancel}
onOk={() => onConfirm(picked)}
>
<div className="uj-combo-search">
<UInput
value={name}
placeholder="请输入群聊名称"
maxLength={100}
onChange={(event) => {
setName(event.target.value);
}}
/>
<UButton type="primary" onClick={() => void query.refetch()}>
查询
</UButton>
</div>
{query.isError ? (
<UAlert
type="error"
showIcon
title="企微群聊加载失败"
description={errorDetail(query.error)}
/>
) : null}
<DataTable<Group>
rowKey="groupChatId"
columns={[
{ title: '群聊名称', dataIndex: 'groupChatName', render: text },
{
title: '群状态',
dataIndex: 'groupStatus',
width: 140,
render: (_, item) => (item.free ? '空闲' : '占用'),
},
]}
dataSource={data}
loading={query.isPending || query.isFetching}
rowSelection={{
selectedRowKeys: keys,
onChange: (nextKeys) => {
setKeys(nextKeys);
setPicked((old) => {
const current = new Map(data.map((item) => [item.groupChatId, item]));
return [
...old.filter(
(item) => !current.has(item.groupChatId) && nextKeys.includes(item.groupChatId),
),
...data.filter((item) => nextKeys.includes(item.groupChatId)),
];
});
},
getCheckboxProps: (item) => ({
disabled: Boolean(item.disabled),
}),
}}
pagination={false}
/>
</UModal>
);
}
export default function GroupCodeEditor({ params }: Props) {
const editing = params?.mode === 'edit';
const { canPoint } = useAccess();
const message = useUMessage();
const [form] = UForm.useForm<Values>();
const [groups, setGroups] = useState<Group[]>([]);
const [pickerOpen, setPickerOpen] = useState(false);
const [saving, setSaving] = useState(false);
const stores = useQuery({
queryKey: ['live-code-dealers'],
queryFn: () => liveCodeApi.getCarDealerList<Record<string, unknown>[]>(),
});
const detail = useQuery({
queryKey: ['live-code-detail', params?.id],
enabled: editing && Boolean(params?.id),
...getLiveCodeDetail.queryOptions,
queryFn: () => liveCodeApi.getLiveCodeDetail<Detail>({ id: params?.id }),
});
useEffect(() => {
if (!detail.data) return;
const { groupList, ...values } = detail.data;
form.setFieldsValue({
liveName: text(values.liveName),
storeId: text(values.storeId),
remark: values.remark ? String(values.remark) : '',
lockTime: text(values.lockTime),
});
setGroups(groupList ?? []);
}, [detail.data, form]);
const fields: FieldSchema<Values>[] = useMemo(
() => [
{
name: 'liveName',
label: '活码名称',
type: 'input',
inputProps: { maxLength: 20 },
rules: [{ required: true, message: '请输入活码名称' }],
},
{
name: 'storeId',
label: '4S店',
type: 'select',
options: (stores.data ?? []).map((item) => ({
value: String(item.mainMerchantId ?? ''),
label: String(item.mainMerchantName ?? ''),
})),
selectProps: { showSearch: true, optionFilterProp: 'label' },
rules: [{ required: true, message: '请选择4S店' }],
},
{
name: 'remark',
label: '备注',
type: 'textarea',
textareaProps: { maxLength: 200, showCount: true, rows: 4 },
itemStyle: { gridColumn: 'span 2' },
},
{
name: 'lockTime',
label: '锁定时长(分钟)',
type: 'input',
inputProps: { inputMode: 'numeric', maxLength: 3 },
rules: [
{ required: true, message: '请输入锁定时长' },
{ pattern: /^(?:[1-9]|[1-9]\d|1[01]\d|120)$/, message: '请输入1至120的整数' },
],
},
],
[stores.data],
);
const save = async (values: Values) => {
if (!groups.length) {
message.warning('请至少关联一个企微群聊');
return;
}
const store = (stores.data ?? []).find((item) => String(item.mainMerchantId ?? '') === values.storeId);
setSaving(true);
try {
const payload = {
...values,
lockTime: Number(values.lockTime),
storeName: String(store?.mainMerchantName ?? ''),
groupChatIds: groups.map((item) => ({
groupChatId: item.groupChatId,
groupChatName: item.groupChatName,
})),
};
if (editing) await liveCodeApi.updateLiveCode({ ...payload, id: params?.id });
else await liveCodeApi.addLiveCode(payload);
message.success('保存成功');
goTo('customer-group');
} catch (error) {
message.error(errorDetail(error));
} finally {
setSaving(false);
}
};
if (!(editing ? canPoint(UC.GROUP_UPDATE) : canPoint(UC.GROUP_CREATE)))
return <UResult status="403" title="无操作群活码的权限" subTitle="请联系管理员开通权限。" />;
return (
<PageShell title={editing ? '修改群活码' : '创建群活码'}>
<div className="uc-detail-stack">
<UCard className="uc-detail-card">
<CardHead title="基础信息" />
<div className="uc-detail-card__body">
<div className="uc-group-form">
<CombiForm
mode="form"
form={form}
fields={fields}
layout="horizontal"
labelWidth={140}
sectionContentStyle={{
display: 'grid',
gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
gap: '0 24px',
}}
onSubmit={(values) => void save(values)}
/>
</div>
</div>
</UCard>
<UCard className="uc-detail-card">
<CardHead
title="群池配置"
aux={`已关联 ${groups.length} 个群`}
actions={
<UButton type="primary" onClick={() => setPickerOpen(true)}>
从企微后台添加群聊
</UButton>
}
/>
<div className="uc-detail-card__body">
<p className="uc-group-tip">
支持最多选择1000个群聊,系统将按列表顺序自动分配状态为“空闲”的群。序号即分配顺序。
</p>
{groups.length ? (
<div className="uc-group-pool">
{groups.map((item, index) => (
<span key={item.groupChatId} className="uc-group-chip">
<span className="uc-group-chip__index">{index + 1}</span>
<span className="uc-group-chip__name" title={item.groupChatName}>
{item.groupChatName}
</span>
{!item.disabled ? (
<button
type="button"
className="uc-group-chip__remove"
aria-label={`移除${item.groupChatName}`}
onClick={() =>
setGroups((old) =>
old.filter((row) => row.groupChatId !== item.groupChatId),
)
}
>
×
</button>
) : null}
</span>
))}
</div>
) : (
<UEmpty description="尚未关联群聊" />
)}
</div>
</UCard>
<div className="uc-group-actions">
<UButton onClick={() => goTo('customer-group')}>取消</UButton>
<UButton type="primary" loading={saving} onClick={() => form.submit()}>
保存
</UButton>
</div>
</div>
<GroupPicker
open={pickerOpen}
liveCodeId={params?.id}
selected={groups}
onCancel={() => setPickerOpen(false)}
onConfirm={(items) => {
setGroups(items.slice(0, 1000));
setPickerOpen(false);
}}
/>
</PageShell>
);
}
function CardHead({ title, aux, actions }: { title: string; aux?: string; actions?: ReactNode }) {
return (
<div className="uc-detail-card__head">
<h2 className="uc-detail-card__title">{title}</h2>
{aux ? <span className="uc-detail-card__aux">{aux}</span> : null}
{actions ? <div className="uc-detail-card__actions">{actions}</div> : null}
</div>
);
}