UploadCard.tsx
12.9 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import { useState, useCallback, useEffect, useRef } from 'react';
import { App } from 'antd';
import {
InfoCircleFilled,
UploadOutlined,
CheckCircleFilled,
CloseOutlined,
FileExcelOutlined,
LoadingOutlined,
} from '@ant-design/icons';
import type { UploadProps, UploadFile } from 'antd';
import type { RcFile } from 'antd/es/upload/interface';
import { UCard, UUpload, UText, UButton } from '@uj/ui';
import { store } from '@/api';
import type { StoreImportCheckVO } from '@/api/modules/store';
import { validateFileExtension, validateFileSize, UPLOAD_RULES } from '../tools/uploadValidate';
const TEMPLATE_NAME = '【优加】门店上架模版-V1.0.1.xlsx';
export interface UploadCardProps {
file?: File | null;
remark?: string;
/** 上传后 check 接口返回结果(用于回显行数/门店数/场景数/分类数/版本) */
checkResult?: StoreImportCheckVO | null;
/** 父组件触发重新上传的信号:每次递增即自动重跑 runUpload(使用已选 file) */
reUploadTrigger?: number;
onFileChange?: (file: File | null) => void;
onUploadSuccess?: (vo: StoreImportCheckVO) => void;
}
export function UploadCard({
file,
remark,
checkResult,
reUploadTrigger = 0,
onFileChange,
onUploadSuccess,
}: UploadCardProps) {
const { message } = App.useApp();
const [uploading, setUploading] = useState(false);
const [downloading, setDownloading] = useState(false);
const [fileList, setFileList] = useState<UploadFile[]>([]);
// antd Upload 实例,用于编程式打开文件选择框
const uploadRef = useRef<any>(null);
// 记录上一次已处理的 reUploadTrigger,防止 effect 因其它依赖变化而重复触发
const processedTriggerRef = useRef(0);
/** 从 checkResult + 文件名推导要显示的统计文案:共 N 行(X 家门店 × Y 场景 × Z 分类)· 模板版本 vX.X.X */
const statLineText = (() => {
if (!checkResult) return null;
const previewRows = checkResult.previewRows ?? [];
// 门店数:优先 storeName 存在即算 1 家;或从 previewRows 去重
const storeCount = (() => {
if (checkResult.storeName) return 1;
const s = new Set(previewRows.map((r) => r.storeName).filter(Boolean));
return s.size || 1;
})();
const sceneCount =
// 注意:businessScene 是单值(名字里可能带 "/" 是组合名,不拆分),有值就算 1 个场景;
// 多场景统计通过 previewRows 去重派生
(checkResult.businessScene ? 1 : 0) ||
new Set(previewRows.map((r) => r.businessScene).filter(Boolean)).size ||
0;
const categoryCount =
(checkResult.productCategories
? new Set(
checkResult.productCategories
.split('/')
.map((s) => s.trim())
.filter(Boolean),
).size
: 0) ||
new Set(previewRows.map((r) => r.productCategory).filter(Boolean)).size ||
0;
const totalRows =
typeof checkResult.productCategoryRowCount === 'number'
? checkResult.productCategoryRowCount
: typeof checkResult.totalRows === 'number'
? checkResult.totalRows
: previewRows.length || 0;
// 模板版本:优先从文件名解析(xxx-V1.0.1.xlsx → v1.0.1);兜底 TEMPLATE_NAME 里的版本
const fileVersion = (() => {
const name = fileList[0]?.name || TEMPLATE_NAME || '';
const m = name.match(/[Vv](\d+(?:\.\d+){0,3})/);
if (m && m[1]) return `v${m[1]}`;
const mm = TEMPLATE_NAME.match(/[Vv](\d+(?:\.\d+){0,3})/);
return mm ? `v${mm[1]}` : 'v1.0.1';
})();
if (sceneCount > 0 && categoryCount > 0) {
return `共 ${totalRows} 行数据(${storeCount} 家门店 × ${sceneCount} 个业务场景 × ${categoryCount} 个产品分类)· 模板版本 ${fileVersion}`;
}
return `共 ${totalRows} 行数据 · 模板版本 ${fileVersion}`;
})();
// 受控:父组件 file 变化时,同步内部 fileList(解决返回上一步组件重新挂载丢失文件的问题)
useEffect(() => {
if (file) {
setFileList([buildUploadFile(file)]);
} else {
setFileList([]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [file]);
const clearFileState = useCallback(() => {
setFileList([]);
onFileChange?.(null);
}, [onFileChange]);
const handleRemove = useCallback(() => {
clearFileState();
message.info('已移除文件');
return true;
}, [clearFileState, message]);
const handleDownloadTemplate = async (e?: React.MouseEvent) => {
e?.stopPropagation?.();
if (downloading || uploading) return;
setDownloading(true);
try {
await store.downloadImportTemplate(TEMPLATE_NAME);
message.success('模板下载成功');
} catch (e) {
message.error((e as Error).message ?? '模板下载失败');
} finally {
setDownloading(false);
}
};
const buildUploadFile = (f: File): UploadFile => ({
uid: Date.now().toString(),
name: f.name,
size: f.size,
type: f.type,
originFileObj: f as RcFile,
status: 'done',
});
const runUpload = useCallback(
async (f: File) => {
if (!validateFileExtension(f.name)) {
message.error(`仅支持 ${UPLOAD_RULES.ALLOW_EXTS.join(' / ')} 格式`);
return;
}
if (!validateFileSize(f.size)) {
message.error(
`文件大小超过限制,单文件 ≤ 10MB(当前 ${(f.size / 1024 / 1024).toFixed(2)}MB)`,
);
return;
}
setUploading(true);
try {
const vo = await store.uploadImport({ file: f, remark });
setFileList([buildUploadFile(f)]);
onFileChange?.(f);
onUploadSuccess?.(vo);
} catch (e) {
message.error((e as Error).message ?? '上传失败');
clearFileState();
} finally {
setUploading(false);
}
},
[remark, onFileChange, onUploadSuccess, clearFileState, message],
);
const customRequest: NonNullable<UploadProps['customRequest']> = (options) => {
const f = options.file as File;
void runUpload(f).finally(() => {
options.onSuccess?.({ ok: true });
});
};
const uploadProps: UploadProps = {
name: 'file',
multiple: false,
accept: UPLOAD_RULES.ALLOW_EXTS.join(','),
showUploadList: false,
customRequest,
onRemove: handleRemove,
fileList,
};
/**
* Step 2 → 点击失败明细里的【重新上传】:
* 父组件 handleReUpload = 切 Step0 + 清空 checkResult + reUploadCounter++
* 本 effect 监听 reUploadTrigger 变化,清空已选文件并编程式打开文件选择对话框,
* 让用户重新选择文件(选完文件后走正常 customRequest → runUpload → check 接口链路)。
* 注意:不再自动用原文件调用 check 接口,必须由用户重新选文件。
*/
useEffect(() => {
if (reUploadTrigger <= 0) return;
if (reUploadTrigger === processedTriggerRef.current) return;
processedTriggerRef.current = reUploadTrigger;
// 清空文件状态
setFileList([]);
onFileChange?.(null);
// 等 DOM 更新后再打开文件选择框:兼容 antd Upload ref 可能不暴露 upload() 的情况,
// 优先用 ref.upload(),兜底通过 DOM 查找隐藏的 input[type=file] 触发 click
setTimeout(() => {
const inst = uploadRef.current;
if (inst && typeof inst.upload === 'function') {
inst.upload();
return;
}
const input = document.querySelector<HTMLInputElement>(
'.uj-upload-dragger input[type="file"], .ant-upload input[type="file"]',
);
if (input) {
input.value = '';
input.click();
}
}, 0);
}, [reUploadTrigger, onFileChange]);
return (
<UCard
styles={{ body: { padding: 20 } }}
style={{ border: '1px solid #E5E7EB', marginBottom: 20 }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: '#2B5CE6', fontSize: 14 }} />
<span style={{ fontSize: 15, fontWeight: 600 }}>上传门店上架表</span>
</div>
}
extra={
<UText type="secondary" style={{ fontSize: 12 }}>
支持 {UPLOAD_RULES.ALLOW_EXTS.join(' / ')} · 单文件 ≤ 10MB · 单次导入 1 家门店(≤{' '}
{UPLOAD_RULES.MAX_ROWS} 行)
</UText>
}
>
<div style={{ position: 'relative' }}>
<UUpload.Dragger ref={uploadRef} {...uploadProps}>
<div style={{ padding: '30px 0' }}>
<div
style={{
width: 48,
height: 48,
borderRadius: 12,
background: '#EEF2FF',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 16,
}}
>
{uploading ? (
<LoadingOutlined style={{ fontSize: 22, color: '#2B5CE6' }} />
) : (
<UploadOutlined style={{ fontSize: 22, color: '#2B5CE6' }} />
)}
</div>
<p
className="ant-upload-text"
style={{
fontSize: 15,
fontWeight: 500,
color: '#374151',
marginBottom: 8,
}}
>
{uploading ? '上传中,请稍候...' : '点击选择文件,或拖拽到此处'}
</p>
<p
className="ant-upload-hint"
style={{
fontSize: 12,
color: '#9CA3AF',
marginBottom: 6,
}}
>
请使用《{TEMPLATE_NAME}》填写
<UButton
type="link"
size="small"
loading={downloading}
disabled={uploading}
style={{ padding: '0 4px', height: 'auto' }}
onClick={handleDownloadTemplate}
>
下载最新模板
</UButton>
</p>
<div
style={{
fontSize: 12,
color: '#C7CDD6',
}}
>
模板版本:v1.0.1 · 系统将校验模板版本一致性
</div>
</div>
</UUpload.Dragger>
{uploading && (
<div
style={{
position: 'absolute',
inset: 0,
background: 'rgba(255,255,255,0.01)',
cursor: 'not-allowed',
}}
/>
)}
</div>
{fileList[0] && (
<div
style={{
marginTop: 16,
display: 'flex',
alignItems: 'center',
padding: '14px 16px',
background: '#F9FAFB',
borderRadius: 8,
border: '1px solid #E5E7EB',
}}
>
<div
style={{
width: 36,
height: 36,
borderRadius: 8,
background: '#E7F5EE',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
flex: 'none',
}}
>
<FileExcelOutlined style={{ color: '#16A34A', fontSize: 18 }} />
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
marginBottom: 4,
}}
>
<span
style={{
fontSize: 14,
fontWeight: 600,
color: '#1A202C',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{fileList[0].name}
</span>
<CheckCircleFilled style={{ color: '#16A34A', fontSize: 16, flex: 'none' }} />
</div>
<div style={{ fontSize: 12, color: '#6B7280' }}>
{fileList[0].size ? Math.max(1, Math.round(fileList[0].size / 1024)) : '-'} KB
<CheckCircleFilled style={{ color: '#16A34A', fontSize: 12, marginLeft: 6 }} />
</div>
{statLineText && (
<div
style={{
marginTop: 6,
fontSize: 12,
color: '#4B5563',
lineHeight: 1.6,
}}
>
{statLineText}
</div>
)}
</div>
<UButton
type="text"
size="small"
icon={<CloseOutlined />}
onClick={() => handleRemove()}
style={{
color: '#9CA3AF',
padding: '4px 8px',
flex: 'none',
marginLeft: 8,
}}
>
移除
</UButton>
</div>
)}
</UCard>
);
}