AddOrUpdate.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
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
import {
postOrderErpTicketsUpload,
postProcureBillAddOrModify,
} from '@/services';
import { useModel } from '@@/exports';
import { UploadOutlined } from '@ant-design/icons';
import {
ActionType,
EditableProTable,
ModalForm,
ProCard,
ProColumns,
ProForm,
ProFormDependency,
ProFormField,
ProFormSwitch,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Form, Upload, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
export default ({ record, onfinish }) => {
const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
const [controlled, setControlled] = useState<boolean>(false);
const [processedRecord, setProcessedRecord] = useState(record);
const formRef = useRef(null);
const editorFormRef = useRef(null);
const { getProducts } = useModel('enum');
const actionRef = useRef<ActionType>();
// 使用 useEffect 为 procureBillDetailList 中的每个元素添加 key
useEffect(() => {
if (record?.procureBillDetailList) {
const updatedProcureBillDetailList = record.procureBillDetailList.map(
(item) => ({
...item,
key: item.key || `key-${Math.random().toString(36).substr(2, 9)}`, // 动态生成唯一 key
}),
);
setProcessedRecord({
...record,
procureBillDetailList: updatedProcureBillDetailList,
});
}
}, [record]);
const columns: ProColumns[] = [
{
title: '商品',
dataIndex: 'productId',
valueType: 'select',
request: async () => {
const res = await getProducts();
return res.map((item) => ({
...item,
label: item.name,
value: item.id,
productUnitName: item.baseUnitName,
productUnitPrice: item.unitPrice,
}));
},
fieldProps: (_, { rowIndex }) => ({
onSelect: (value, option) => {
console.log('option111111' + JSON.stringify(option));
const currentTableData = editorFormRef.current?.getRowsData?.();
if (currentTableData) {
const updatedData = [...currentTableData];
updatedData[rowIndex] = {
...updatedData[rowIndex],
productUnitName: option.productUnitName,
productUnitPrice: option.productUnitPrice,
};
formRef.current?.setFieldsValue({
procureBillDetailList: updatedData,
});
}
},
}),
},
{
title: '单位',
dataIndex: 'productUnitName',
valueType: 'text',
editable: false,
},
{
title: '单价',
dataIndex: 'productUnitPrice',
valueType: 'digit',
editable: false,
},
{
title: '数量',
dataIndex: 'number',
valueType: 'digit',
},
{
title: '备注',
dataIndex: 'notes',
valueType: 'textarea',
},
{
title: '附件',
dataIndex: 'annexUpload',
renderFormItem: (_, { record }) => (
<Upload
fileList={
record.annexList?.map((url) => ({
uid: url,
name: url.split('/').pop(),
status: 'done',
url,
})) || []
}
onPreview={(file) => {
window.open(file.url || file.thumbUrl); // 打开文件预览
}}
customRequest={async (options) => {
const { file, onSuccess, onError } = options;
const formData = new FormData();
formData.append('file', file);
try {
const res = await postOrderErpTicketsUpload({
data: formData,
headers: { 'Content-Type': 'multipart/form-data' },
});
if (res.message === '成功') {
message.success(`${file.name} 上传成功`);
// 更新文件列表
const currentData = formRef.current?.getFieldValue(
'procureBillDetailList',
);
const currentRow = currentData.find(
(row) => row.key === record.key,
);
const existingAnnex = currentRow?.annexList || []; // 取现有的 annex 数据
const updatedAnnex = [...existingAnnex, res.data]; // 合并新的文件 URL
// 更新表单数据
const updatedData = currentData.map((row) =>
row.key === record.key
? { ...row, annexList: updatedAnnex }
: row,
);
formRef.current?.setFieldValue(
'procureBillDetailList',
updatedData,
);
onSuccess?.('上传成功');
} else {
message.error(`${file.name} 上传失败`);
onError?.(new Error('上传失败'));
}
} catch (error) {
message.error(`${file.name} 上传错误`);
onError?.(error);
}
}}
onRemove={(file) => {
const currentData =
formRef.current?.getFieldValue('procureBillDetailList') || [];
const updatedData = currentData.map((row) => {
if (row.key === record.key) {
return {
...row,
annexList: row.annexList.filter((url) => url !== file.url), // 移除对应文件 URL
};
}
return row;
});
formRef.current?.setFieldsValue({
procureBillDetailList: updatedData,
});
// 触发状态更新
setProcessedRecord((prevRecord) => ({
...prevRecord,
procureBillDetailList: updatedData,
}));
}}
>
<Button icon={<UploadOutlined />}>上传附件</Button>
</Upload>
),
render: (_, record) => (
<div>
{record.annexList?.map((url, index) => {
const shortName =
url.split('/').pop()?.slice(0, 15) || `附件 ${index + 1}`;
return (
<a
key={index}
href={url}
target="_blank"
rel="noopener noreferrer"
title={url} // 悬停显示完整链接
style={{
display: 'block',
marginBottom: '4px',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
maxWidth: '200px', // 限制显示宽度
}}
>
{shortName.length < url.split('/').pop()?.length
? `${shortName}...`
: shortName}
</a>
);
})}
</div>
),
},
{
title: '附件',
hideInTable: true,
dataIndex: 'annexList',
},
{
title: '操作',
valueType: 'option',
render: (text, record, _, action) => [
<a
key="editable"
onClick={() => {
action?.startEditable?.(record.key);
}}
>
编辑
</a>,
<a
key="delete"
onClick={() => {
const tableDataSource = formRef.current?.getFieldValue(
'procureBillDetailList',
);
formRef.current?.setFieldsValue({
table: tableDataSource.filter((item) => item.key !== record.key),
});
}}
>
删除
</a>,
],
},
];
const [form] = Form.useForm();
return (
<ModalForm
formRef={formRef}
initialValues={processedRecord}
validateTrigger="onBlur"
title="新建表单"
trigger={
record?.id ? (
<Button type="link">修改</Button>
) : (
<Button type="primary">新建</Button>
)
}
form={form}
autoFocusFirstInput
width={1500}
modalProps={{
destroyOnClose: true,
onCancel: () => console.log('run'),
}}
submitTimeout={2000}
onFinish={async (values) => {
const res = await postProcureBillAddOrModify({
data: {
...record,
...values,
},
});
if (res) {
message.success(res.message);
onfinish();
}
return true;
}}
>
<EditableProTable
rowKey="key"
scroll={{
x: 960,
}}
editableFormRef={editorFormRef}
headerTitle="可编辑表格"
maxLength={5}
name="procureBillDetailList"
controlled={controlled}
recordCreatorProps={{
position: 'bottom',
record: () => ({
key: `key-${Math.random().toString(36).substr(2, 9)}`,
}),
}}
actionRef={actionRef}
toolBarRender={() => [
<ProFormSwitch
key="render"
fieldProps={{
style: {
marginBlockEnd: 0,
},
checked: controlled,
onChange: (value) => {
setControlled(value);
},
}}
checkedChildren="数据更新通知 Form"
unCheckedChildren="保存后通知 Form"
noStyle
/>,
<Button
key="rows"
onClick={() => {
const rows = editorFormRef.current?.getRowsData?.();
console.log(rows);
}}
>
获取 table 的数据
</Button>,
]}
columns={columns}
editable={{
type: 'multiple',
editableKeys,
onChange: setEditableRowKeys,
actionRender: (row, config, defaultDom) => {
return [defaultDom.save, defaultDom.delete, defaultDom.cancel];
},
}}
/>
<ProForm.Item>
<ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
<ProFormDependency name={['procureBillDetailList']}>
{({ procureBillDetailList }) => (
<ProFormField
ignoreFormItem
fieldProps={{
style: {
width: '100%',
},
}}
mode="read"
valueType="jsonCode"
text={JSON.stringify(procureBillDetailList)}
/>
)}
</ProFormDependency>
</ProCard>
</ProForm.Item>
<ProFormTextArea name="notes" label="备注" />
</ModalForm>
);
};