CreateBotQrcode.tsx
11.8 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
326
327
328
329
330
331
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
listBotsQrcode,
uploadMedia,
saveEmployeeQrcode,
} from '../api/agent';
import type { BotQrcodeItem, SaveQrcodeResult } from '../api/agent';
const AVATAR_COLORS = ['#00D4AA', '#4A8CFF', '#FFA502', '#FF4757', '#2ED573', '#A855F7', '#EC4899', '#06B6D4'];
function botAvatarColor(botId: string): string {
let hash = 0;
for (let i = 0; i < botId.length; i++) {
hash = botId.charCodeAt(i) + ((hash << 5) - hash);
}
return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
}
function botInitials(name: string): string {
const cleaned = name.replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '');
if (!cleaned) return '●';
const isChinese = /[\u4e00-\u9fff]/.test(cleaned);
if (isChinese) return cleaned.slice(-1);
return cleaned.slice(0, 2).toUpperCase();
}
export function CreateBotQrcode() {
const navigate = useNavigate();
const fileRef = useRef<HTMLInputElement>(null);
const [bots, setBots] = useState<BotQrcodeItem[]>([]);
const [botsLoading, setBotsLoading] = useState(true);
const [botsError, setBotsError] = useState<string | null>(null);
const [selectedBotId, setSelectedBotId] = useState('');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<SaveQrcodeResult | null>(null);
const fetchBots = useCallback(() => {
setBotsLoading(true);
setBotsError(null);
listBotsQrcode()
.then(setBots)
.catch(() => setBotsError('机器人列表加载失败'))
.finally(() => setBotsLoading(false));
}, []);
useEffect(() => {
fetchBots();
}, [fetchBots]);
function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
setError('请选择图片文件');
return;
}
if (file.size > 5 * 1024 * 1024) {
setError('图片不能超过 5MB');
return;
}
setSelectedFile(file);
setPreviewUrl(URL.createObjectURL(file));
setError(null);
setResult(null);
}
function selectBot(bot: BotQrcodeItem) {
setSelectedBotId(bot.bot_id);
setResult(null);
setError(null);
if (bot.has_qrcode && bot.qrcode_url) {
setPreviewUrl(bot.qrcode_url);
} else {
setPreviewUrl(null);
}
setSelectedFile(null);
if (fileRef.current) fileRef.current.value = '';
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setResult(null);
if (!selectedBotId) {
setError('请选择一个机器人');
return;
}
if (!selectedFile) {
setError('请上传二维码图片');
return;
}
setUploading(true);
try {
const uploadResult = await uploadMedia(selectedFile);
setSaving(true);
try {
const saveResult = await saveEmployeeQrcode(selectedBotId, uploadResult.cdn_url);
setResult(saveResult);
setSelectedFile(null);
setPreviewUrl(null);
if (fileRef.current) fileRef.current.value = '';
fetchBots();
} catch {
setError('保存二维码失败');
} finally {
setSaving(false);
}
} catch {
setError('上传图片失败');
} finally {
setUploading(false);
}
}
const selectedBot = bots.find((b) => b.bot_id === selectedBotId);
const isExisting = selectedBot?.has_qrcode ?? false;
if (botsLoading) {
return (
<div className="page">
<div className="page-heading">
<h1>机器人二维码</h1>
<p className="page-desc">绑定或更新机器人的二维码</p>
</div>
<div className="loading-block">
<div className="loading-spinner" />
<span>正在加载机器人列表...</span>
</div>
</div>
);
}
return (
<div className="page">
<div className="page-heading">
<h1>机器人二维码</h1>
<p className="page-desc">选择机器人并上传二维码图片,系统将自动上传 OSS 并完成绑定</p>
</div>
{error && (
<div className="alert alert-error">
<span className="alert-icon">!</span>
<span>{error}</span>
</div>
)}
{result && (
<div className="alert alert-success">
<span className="alert-icon">✓</span>
<span>
机器人 <code className="tag">{result.employee_id}</code> 二维码{isExisting ? '更新' : '绑定'}成功
</span>
</div>
)}
<form onSubmit={handleSubmit}>
<div className="bq-layout">
{/* ============ Left: Bot Cards ============ */}
<div className="bq-panel bq-panel-bots">
<div className="bq-panel-header bq-panel-header-stacked">
<div className="bq-panel-heading">
<span className="bq-panel-title">选择机器人</span>
<span className="bq-panel-subtitle">选择一个机器人进行二维码绑定或更新</span>
</div>
<span className="bq-panel-count">
{bots.filter((b) => b.has_qrcode).length}/{bots.length} 已绑定
</span>
</div>
{botsError ? (
<div className="inline-error" style={{ margin: '16px' }}>
<span>{botsError}</span>
<button className="btn btn-ghost btn-sm" onClick={fetchBots}>重试</button>
</div>
) : bots.length === 0 ? (
<div className="bq-empty">
<div className="bq-empty-icon">!</div>
<div className="bq-empty-title">暂无数据</div>
<div className="bq-empty-desc">未找到机器人</div>
</div>
) : (
<div className="bq-card-list">
{bots.map((bot) => {
const selected = selectedBotId === bot.bot_id;
const color = botAvatarColor(bot.bot_id);
return (
<label
key={bot.bot_id}
className={`bq-card${selected ? ' selected' : ''}${bot.has_qrcode ? ' has-qrcode' : ''}`}
style={{ '--accent-color': color } as React.CSSProperties}
>
<input
type="radio"
name="bot_id"
value={bot.bot_id}
checked={selected}
onChange={() => selectBot(bot)}
/>
<div className="bq-card-accent" />
<div
className="bq-card-avatar"
style={{ background: color + '18', color }}
>
{botInitials(bot.bot_name || bot.bot_id)}
</div>
<div className="bq-card-body">
<div className="bq-card-name-row">
<div className="bq-card-name">{bot.bot_name || bot.bot_id}</div>
<div className={`bq-card-status${bot.has_qrcode ? ' bound' : ' unbound'}`}>
<span className="bq-card-status-dot" />
<span className="bq-card-status-label">{bot.has_qrcode ? '已绑定' : '未绑定'}</span>
</div>
</div>
<div className="bq-card-id">{bot.bot_id}</div>
</div>
{selected && <div className="bq-card-check">✓</div>}
</label>
);
})}
</div>
)}
</div>
{/* ============ Right: Upload Area ============ */}
<div className="bq-panel bq-panel-upload">
<div className="bq-panel-header">
<span className="bq-panel-title">
{selectedBot
? isExisting ? '更新二维码' : '新增二维码'
: '二维码图片'}
</span>
{selectedBot && (
<span className="bq-panel-bot-tag" style={{ color: botAvatarColor(selectedBot.bot_id) }}>
{selectedBot.bot_name || selectedBot.bot_id}
</span>
)}
</div>
<div className="bq-upload-area" onClick={() => fileRef.current?.click()}>
{previewUrl ? (
<div className="bq-preview-wrap">
<img src={previewUrl} alt="二维码预览" className="bq-preview-img" />
{isExisting && !selectedFile && (
<div className="bq-preview-overlay">当前已绑定的二维码,点击上传新图片替换</div>
)}
</div>
) : (
<div className="bq-upload-placeholder">
<div className="bq-upload-icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
</div>
<div className="bq-upload-text">点击上传二维码图片</div>
<div className="bq-upload-hint">JPG / PNG,最大 5MB</div>
</div>
)}
<input
ref={fileRef}
type="file"
accept="image/*"
className="upload-input"
onChange={handleFileSelect}
/>
</div>
{previewUrl && (
<div className="bq-upload-actions">
<button
type="button"
className="btn btn-ghost btn-sm"
onClick={() => {
setSelectedFile(null);
if (isExisting && selectedBot?.qrcode_url) {
setPreviewUrl(selectedBot.qrcode_url);
} else {
setPreviewUrl(null);
}
if (fileRef.current) fileRef.current.value = '';
}}
>
{isExisting && !selectedFile ? '取消' : '重新选择'}
</button>
</div>
)}
{selectedBot && selectedFile && (
<div className="bq-summary">
<div className="bq-summary-label">绑定对象</div>
<div className="bq-summary-value">
<span
className="bq-summary-dot"
style={{ background: botAvatarColor(selectedBot.bot_id) }}
/>
{selectedBot.bot_name || selectedBot.bot_id}
<span className="bq-summary-id">{selectedBot.bot_id}</span>
</div>
</div>
)}
</div>
</div>
<div className="form-footer" style={{ marginTop: '24px' }}>
<button
type="submit"
className="btn btn-primary"
disabled={uploading || saving || !selectedBotId || !selectedFile}
>
{uploading ? '上传图片中...' : saving ? '保存中...' : isExisting ? '更新二维码' : '创建绑定'}
</button>
<button type="button" className="btn btn-ghost" onClick={() => navigate('/')}>
取消
</button>
</div>
</form>
</div>
);
}