chen.lin
10 小时以前 f574055ed80a64cbccd601b200afc437a87b52eb
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import { Box, Card, Grid, LinearProgress, Select, MenuItem, ListItemText } from "@mui/material";
import React, { useState, useRef, useEffect, useMemo } from "react";
import {
    List,
    DatagridConfigurable,
    SearchInput,
    TopToolbar,
    Button,
    SelectColumnsButton,
    EditButton,
    FilterButton,
    CreateButton,
    ExportButton,
    BulkDeleteButton,
    WrapperField,
    useRecordContext,
    useTranslate,
    useNotify,
    useListContext,
    FunctionField,
    TextField,
    NumberField,
    DateField,
    BooleanField,
    ReferenceField,
    TextInput,
    DateTimeInput,
    DateInput,
    SelectInput,
    NumberInput,
    ReferenceInput,
    ReferenceArrayInput,
    AutocompleteInput,
    DeleteButton,
    SimpleForm,
    required,
    Form,
    useRefresh,
    useRedirect,
    useRecordSelection,
} from 'react-admin';
import { PAGE_DRAWER_WIDTH, OPERATE_MODE, DEFAULT_PAGE_SIZE, DEFAULT_ITEM_PAGE_SIZE, DEFAULT_TYPE } from '@/config/setting';
import { styled } from '@mui/material/styles';
import { DataGrid, useGridApiContext, GridActionsCellItem, useGridApiRef } from '@mui/x-data-grid';
import request from '@/utils/request';
import ConfirmationNumberOutlinedIcon from '@mui/icons-material/ConfirmationNumberOutlined';
import CloseSharpIcon from '@mui/icons-material/CloseSharp';
import ConfirmButton from '../../components/ConfirmButton';
import { Delete, Edit, Add } from '@mui/icons-material';
import OutStockSiteDialog from "./OutStockSiteDialog";
 
const StyledDatagrid = styled(DatagridConfigurable)(({ theme }) => ({
    '& .css-1vooibu-MuiSvgIcon-root': {
        height: '.9em'
    },
    '& .RaDatagrid-row': {
        cursor: 'auto'
    },
    '& .column-maktx': {
        width: 200
    },
 
    mt: '60px'
    // '& .RaBulkActionsToolbar-toolbar': {
    //     display: 'none'
    // }
 
}));
 
const OutStockPublic = (props) => {
    const { record, open, setOpen, setManualDialog } = props;
    const notify = useNotify();
    const gridRef = useGridApiRef();
    const [rows, setRows] = useState([]);
    const [fetchRows, setFetchRows] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const translate = useTranslate();
    const [rowSelectedIds, setRowSelectedIds] = useState([]);
    const [selectedMatnr, setSelectedMatnr] = useState([]);
    const [selectedIds, setSelectedIds] = useState([]);
    const [formData, setFormData] = useState({ orderId: record?.id, waveId: DEFAULT_TYPE });
    const [dialog, setDialog] = useState(false);
    const [selectedValue, setSelectedValue] = useState({});
 
    useEffect(() => {
        console.log('useEffect triggered - selectedMatnr:', selectedMatnr, 'fetchRows length:', fetchRows.length);
        if (selectedMatnr.length < 1) {
            console.log('没有选中物料,显示所有数据');
            setRows(fetchRows)
        } else {
            console.log('过滤数据,选中的物料编码:', selectedMatnr);
            const mas = fetchRows.filter(item => {
                const matnrCode = item.matnrCode || item.locItem?.matnrCode;
                const included = selectedMatnr.includes(matnrCode);
                console.log('物料编码:', matnrCode, '是否包含:', included);
                return included;
            });
            console.log('过滤后的数据:', mas);
            setRows(mas)
        }
    }, [selectedMatnr, fetchRows])
 
 
    const ComfirmButton = () => {
        const { selectedIds, data } = useListContext();
        const handleRowClick = async () => {
            console.log('selectedIds:', selectedIds);
            console.log('data:', data);
            console.log('fetchRows:', fetchRows);
            console.log('isLoading:', isLoading);
            
            if (!selectedIds || selectedIds.length === 0) {
                notify('请先选择物料');
                return;
            }
            
            if (!data || data.length === 0) {
                notify('数据加载中,请稍候');
                return;
            }
            
            const ids = data.filter(item => selectedIds.includes(item.id)).map(item => item.id);
            setRowSelectedIds(ids);
            const mas = data.filter(item => selectedIds.includes(item.id)).map(item => item.matnrCode);
            console.log('selectedMatnr:', mas);
            
            // 检查选中的物料是否已全部出库
            const selectedItems = data.filter(item => selectedIds.includes(item.id));
            const allCompleted = selectedItems.every(item => {
                const remaining = (item.anfme || 0) - (item.workQty || 0);
                return remaining <= 0;
            });
            
            if (allCompleted) {
                notify('选中的物料已全部出库(已出数量 >= 计划出库数),没有可出库的库存数据');
                setSelectedMatnr(mas);
                setRows([]);
                return;
            }
            
            //设置库位信息筛选条件
            setSelectedMatnr(mas);
            
            // 如果 fetchRows 还没有数据,重新加载
            if (!fetchRows || fetchRows.length === 0) {
                console.log('fetchRows为空,重新加载数据');
                notify('正在加载库存数据...');
                // 重新加载数据,getWaveRule 会在加载完成后自动处理 selectedMatnr
                await getWaveRule(formData);
            } else {
                // 如果 fetchRows 有数据,立即过滤显示
                const filteredRows = fetchRows.filter(item => {
                    const matnrCode = item.matnrCode || item.locItem?.matnrCode;
                    return mas.includes(matnrCode);
                });
                console.log('filteredRows:', filteredRows);
                setRows(filteredRows);
                
                // 如果过滤后没有数据,提示用户
                if (filteredRows.length === 0) {
                    notify('选中的物料没有可出库的库存数据,可能已全部出库或库存不足');
                }
            }
        }
 
        return (
            <Button 
                label="toolbar.confirm" 
                size="medium" 
                onClick={handleRowClick}
                disabled={isLoading}
            />
        )
    };
 
    const handleClickOpen = () => {
        setDialog(true);
    };
 
    const handleClose = (value) => {
        setDialog(false);
        setSelectedValue(value);
        if (selectedIds.length == 0) {
            const newRows = rows.map(item => {
                return {
                    ...item,
                    siteNo: value?.site
                }
            })
            setRows(newRows);
        } else {
            const newRows = rows.map(item => {
                return selectedIds.includes(item?.id) ? {
                    ...item,
                    siteNo: value?.site
                } : item
            })
            setRows(newRows);
        }
    };
 
    useEffect(() => {
        if (open && record?.id) {
            // 重置状态,确保数据能正确显示
            setSelectedMatnr([]);
            setRows([]);
            setFetchRows([]);
            setIsLoading(false);
            // 确保 formData 正确初始化
            const initialFormData = { orderId: record.id, waveId: DEFAULT_TYPE };
            setFormData(initialFormData);
            getWaveRule(initialFormData)
        }
    }, [open, record?.id])
 
    const getWaveRule = async (data = formData) => {
        if (data.waveId == null || data.waveId == undefined) {
            return
        }
        if (!data.orderId) {
            return
        }
        setIsLoading(true);
        try {
            const { data: { code, data: responseData, msg } } = await request.post('/outStock/order/getOutTaskItems', { ...data });
            if (code === 200) {
                console.log('API返回的数据:', responseData);
                // 处理返回的数据,确保数据结构正确
                const processedData = (responseData || []).map((item, index) => {
                    // 如果数据有 locItem 嵌套结构,需要展开
                    if (item.locItem) {
                        return {
                            ...item.locItem,
                            id: item.locItem.id || `temp_${index}`,
                            siteNo: item.siteNo,
                            staNos: item.staNos || [],
                            sourceId: item.sourceId,
                            source: item.source
                        };
                    }
                    // 如果数据已经是扁平结构,直接返回
                    return {
                        ...item,
                        id: item.id || `temp_${index}`
                    };
                });
                console.log('处理后的数据:', processedData);
                setFetchRows(processedData);
                
                // 如果返回的数据为空,且用户已选中物料,提示原因
                if (processedData.length === 0 && selectedMatnr.length > 0) {
                    notify('选中的物料已全部出库,没有可出库的库存数据');
                } else if (processedData.length === 0) {
                    notify('当前出库单没有可出库的库存数据,可能所有物料已全部出库');
                }
                // useEffect 会自动根据 selectedMatnr 和 fetchRows 来过滤数据
            } else {
                notify(msg);
            }
        } catch (error) {
            console.error('获取库存数据失败:', error);
            notify('获取库存数据失败,请重试');
        } finally {
            setIsLoading(false);
        }
    }
 
    const handleChange = (value, name) => {
        setFormData((prevData) => {
            const newData = {
                ...prevData,
                [name]: value
            };
            // 当策略改变时,重新获取数据
            if (name === 'waveId' && value && prevData.orderId) {
                getWaveRule(newData);
            }
            return newData;
        });
    };
 
 
    return (
        <>
            <Box>
                <Grid sx={{ display: "flex" }} container rowSpacing={2} columnSpacing={2}>
                    <Grid item xl={5.7} gap={2} >
                        <Card>
                            <Form>
                                <ReferenceInput
                                    source="type"
                                    reference="waveRule"
                                >
                                    <AutocompleteInput
                                        label="table.field.waveRule.type"
                                        onChange={(e) => handleChange(e, 'waveId')}
                                        defaultValue={15}
                                        value={formData.type}
                                        validate={required()}
                                    />
                                </ReferenceInput>
                            </Form>
                            <List
                                resource="outStockItem"
                                storeKey='outStockItem'
                                sx={{
                                    flexGrow: 1,
                                    transition: (theme) =>
                                        theme.transitions.create(['all'], {
                                            duration: theme.transitions.duration.enteringScreen,
                                        }),
                                }}
                                title={"menu.outStockItem"}
                                empty={false}
                                filter={{ orderId: record?.id, deleted: 0 }}
                                sort={{ field: "create_time", order: "desc" }}
                                actions={false}
                                pagination={false}
                                perPage={DEFAULT_ITEM_PAGE_SIZE}
                            >
                                <LinearProgress
                                    sx={{ height: "2px", position: 'absolute', top: 0, left: 0, right: 0, }}
                                />
                                <StyledDatagrid
                                    storeKey={"outStockPublic"}
                                    preferenceKey='outStockItem'
                                    bulkActionButtons={<>
                                        <ComfirmButton />
                                    </>}
                                    omit={['id', 'splrName', 'qty', 'poCode',]}
                                >
                                    <NumberField source="id" />
                                    <TextField source="asnCode" label="table.field.outStockItem.orderCode" />
                                    <TextField source="poCode" label="table.field.outStockItem.poCode" />
                                    <TextField source="matnrCode" label="table.field.outStockItem.matnrCode" />
                                    <TextField source="maktx" label="table.field.outStockItem.maktx" />
                                    <NumberField source="anfme" label="table.field.outStockItem.anfme" />
                                    <NumberField source="workQty" label="table.field.outStockItem.workQty" />
                                    <NumberField source="qty" label="table.field.outStockItem.qty" />
                                    <TextField source="stockUnit" label="table.field.outStockItem.stockUnit" />
                                    <TextField source="splrName" label="table.field.outStockItem.splrName" />
                                </StyledDatagrid>
                            </List>
                        </Card>
                    </Grid>
                    <Grid item xl={6.3} gap={2}>
                        <Card sx={{ minHeight: 1050, height: 'calc(100% - 10px)', width: '100%' }}>
                            <Box>
                                <PreviewTable
                                    rows={rows}
                                    gridRef={gridRef}
                                    setRows={setRows}
                                    record={record}
                                    formData={formData}
                                    selectedIds={selectedIds}
                                    setDialog={setDialog}
                                    setSelectedIds={setSelectedIds}
                                />
                            </Box>
                            <Box sx={{ textAlign: 'center' }}>
                                <CloseButton setOpen={setOpen} />
                                <SubmitButton selectedIds={selectedIds} setSelectedIds={setSelectedIds} gridRef={gridRef} record={record} />
                            </Box>
                        </Card>
                    </Grid>
                </Grid>
                <Grid>
                    <OutStockSiteDialog
                        selectedValue={selectedValue}
                        open={dialog}
                        onClose={handleClose}
                    />
                </Grid>
            </Box>
        </>
    );
}
 
const PreviewTable = ({ rows, gridRef, setRows, record, selectedIds, setSelectedIds, setDialog, formData }) => {
    gridRef.current = useGridApiRef();
    const translate = useTranslate();
 
    useEffect(() => {
        if (selectedIds.length > 0) {
            console.log(selectedIds);
        }
    }, [selectedIds])
 
    const baseColumns = [
        // { field: 'id', headerName: 'ID', width: 40 },
        { field: 'locCode', headerName: '库位', width: 110 },
        { field: 'barcode', headerName: '容器', width: 120 },
        { field: 'matnrCode', headerName: '物料编码', width: 120 },
        { field: 'batch', headerName: '批次', width: 90 },
        { field: 'unit', headerName: '单位', width: 60 },
        { field: 'outQty', headerName: '出库数量', width: 110, },
        {
            field: 'anfme', headerName: '库存数量', width: 110,
            renderCell: (params) => (
                <OutStockAnfme value={params.value} />
            )
        },
        {
            field: 'siteNo',
            headerName: '出库口',
            width: 90,
            type: 'singleSelect',
            editable: true,
            renderCell: (params) => (
                <OutStockSiteNo value={params.value} />
            ),
            renderEditCell: (params) => (
                <OutStockSite {...params} />
            ),
        },
    ]
 
    const optAction = {
        field: 'actions',
        type: 'actions',
        headerName: translate('common.field.opt'),
        with: 120,
        getActions: (params) => [
            <GridActionsCellItem
                icon={<Delete />}
                label="Delete"
                onClick={() => handleDelete(params.row, rows, setRows)}
            />,
        ]
    }
 
    const columns = (formData.waveId == 15 || formData.waveId == 16) ? [...baseColumns] : [...baseColumns, optAction];
 
    /**
     * 删除事件
     * @param {*} params 
     */
    const handleDelete = (params, rows, setRows) => {
        const outRows = rows.filter(row => {
            return row.id !== params.id
        })
        setRows(outRows)
    }
 
    const OutStockAnfme = React.memo(function OutStockAnfme(props) {
        const { value } = props;
        return (
            value > 0 ?
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <span>{value}</span>
                </Box>
                :
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <span style={{ color: 'red' }}>{translate('common.edit.title.insuffInventory')}</span>
                </Box>
        );
    });
 
    const OutStockSiteNo = React.memo(function OutStockSiteNo(props) {
        const { value } = props;
        if (!value) {
            return null;
        }
        return (
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>{value}</span>
            </Box>
        );
    });
 
    const CustomToolBar = () => {
        const selectSiteNo = () => {
            setDialog(true)
        }
        return (
            <Box sx={{
                p: 1,
                display: 'flex',
                justifyContent: 'flex-end',
                borderTop: '1px solid rgba(224, 224, 224, 1)'
            }}>
                <Button
                    onClick={selectSiteNo}
                    variant="outlined"
                    label="toolbar.modiftySite"
                    size="medium"
                    sx={{ mr: 1 }} />
            </Box>
        );
    }
 
    const OutStockSite = (params) => {
        const { id, field, siteNo, row: { staNos } } = params;
        const apiRef = useGridApiContext();
        const handleChange = async (event) => {
            await apiRef.current.setEditCellValue(
                { id, field, value: event.target.value },
                event,
            );
            apiRef.current.stopCellEditMode({ id, field });
        };
 
        const handleClose = (event, reason) => {
            if (reason === 'backdropClick') {
                apiRef.current.stopCellEditMode({ id, field });
            }
        };
 
        return (
            <Select
                value={siteNo}
                onChange={handleChange}
                MenuProps={{
                    onClose: handleClose,
                }}
                sx={{
                    height: '100%',
                    '& .MuiSelect-select': {
                        display: 'flex',
                        alignItems: 'center',
                        pl: 1,
                    },
                }}
                autoFocus
                fullWidth
                open
            >
                {staNos.map((option) => {
                    return (
                        <MenuItem
                            key={option}
                            value={option.staNo}
                        >
                            <ListItemText sx={{ overflow: 'hidden' }} primary={option.staNo} />
                        </MenuItem>
                    );
                })}
            </Select >
        )
    }
 
    return (
        <DataGrid
            storeKey={"locItemPreview"}
            rows={rows}
            columns={columns}
            slots={{ toolbar: CustomToolBar }}
            apiRef={gridRef}
            checkboxSelection
            disableRowSelectionOnClick
            hideFooterPagination={true}  // 隐藏分页控件
            hideFooter={false}
            onRowSelectionModelChange={(ids) => {
                setSelectedIds(ids)
            }}
        />
    )
}
 
 
//提交按钮
const SubmitButton = ({ selectedIds, setSelectedIds, gridRef, record }) => {
    const notify = useNotify();
    const refresh = useRefresh();
    const redirect = useRedirect();
    const submit = async () => {
        const items = gridRef.current?.getSortedRows();
        const { data: { code, data, msg } } = await request.post('/outStock/generate/tasks', { items, outId: record?.id });
        if (code == 200) {
            refresh();
            redirect("/task")
        } else {
            notify(msg);
        }
    }
    return (
        <ConfirmButton
            label="toolbar.allComfirm"
            variant="contained"
            size="medium"
            onConfirm={submit}
        />
    )
}
 
//关闭按钮
const CloseButton = ({ setOpen }) => {
    const close = () => {
        setOpen(false)
    }
    return (
        <Button
            label="toolbar.close"
            variant="outlined"
            size="medium"
            onClick={close}
            startIcon={<CloseSharpIcon />}
            sx={{ margin: '3.5em' }} />
    )
}
 
export default OutStockPublic;