啊鑫
3 天以前 b54eecf57118f38f0e3ddcdce8c2b9412a47bf7e
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
package com.gs.xky.service.Impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gs.xky.dto.LineList;
import com.gs.xky.dto.XkyDetail;
import com.gs.xky.entity.DeliveryNotice;
import com.gs.xky.entity.DeliveryNoticeDetail;
import com.gs.xky.entity.MesInvItemArn;
import com.gs.xky.mapper.DeliveryNoticeMapper;
import com.gs.xky.service.DeliveryNoticeDetailService;
import com.gs.xky.service.DeliveryNoticeService;
import com.gs.xky.service.MesInvItemArnService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * @author 28567
 * @description 针对表【DELIVERY_NOTICE(送货通知单主表)】的数据库操作Service实现
 * @createDate 2025-02-11 20:55:22
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class DeliveryNoticeServiceImpl extends ServiceImpl<DeliveryNoticeMapper, DeliveryNotice>
        implements DeliveryNoticeService {
 
    private static final Logger log = LoggerFactory.getLogger(DeliveryNoticeServiceImpl.class);
    private final DeliveryNoticeDetailService detailService;
    private final MesInvItemArnService invItemArnService;
 
    @Override
    public boolean saveDeliveryNotice(XkyDetail xkyDetail) {
 
        LambdaQueryWrapper<DeliveryNotice> wrapper = new LambdaQueryWrapper<>();
 
        wrapper.eq(DeliveryNotice::getDeliveryNo, xkyDetail.getDeliveryNo());
 
//        long count = count(wrapper);
        DeliveryNotice one = getOne(wrapper, false);
 
        if (one != null) {
            LambdaUpdateWrapper<DeliveryNotice> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(DeliveryNotice::getDeliveryNo, xkyDetail.getDeliveryNo());
            remove(updateWrapper);
 
            LambdaUpdateWrapper<DeliveryNoticeDetail> updateWrapper1 = new LambdaUpdateWrapper<>();
            updateWrapper1.eq(DeliveryNoticeDetail::getPid, one.getId());
            detailService.remove(updateWrapper1);
        }
 
 
        DeliveryNotice deliveryNotice = new DeliveryNotice();
        BeanUtil.copyProperties(xkyDetail, deliveryNotice);
 
        long id = baseMapper.getNextVal();
        deliveryNotice.setId(id);
 
        List<LineList> lineList = xkyDetail.getLineList();
 
        if (CollUtil.isEmpty(lineList)) {
            return true;
        }
 
        List<DeliveryNoticeDetail> noticeDetails = new ArrayList<>();
 
        List<LineList> collect = lineList.stream().filter(s -> "1".equals(s.getStatus())).collect(Collectors.toList());
        for (LineList list : collect) {
            DeliveryNoticeDetail detail = new DeliveryNoticeDetail();
            BeanUtil.copyProperties(list, detail);
            detail.setPid(id);
 
            if (StrUtil.isNotEmpty(detail.getPoLineNo())) {
                String[] split = detail.getPoLineNo().split("-");
                detail.setPoLineNo(split[0]);
                detail.setPlanLineNo(split[1] + "-" + detail.getDeliveryQty());
            }
 
            noticeDetails.add(detail);
        }
 
        return save(deliveryNotice) && detailService.saveBatch(noticeDetails);
    }
 
    @Override
    public void callPdaReceiptBtn(String inStr, String result) {
        baseMapper.callPdaReceiptBtn(inStr, result);
    }
 
    @Override
    public Object[] callPdaReceiptBtn1(String deliveryNo, String userid) {
        // 创建用于接收输出参数的变量
        Integer res = null;
        String msg = null;
 
        try {
            // 调用存储过程
            baseMapper.callPdaReceiptBtn1(deliveryNo, userid, res, msg);
 
            log.info("调用存储过程PRC_RF_PDA_RECEIPT_BTN_test001成功: 送货单号={}, 用户ID={}, 结果码={}, 消息={}",
                    deliveryNo, userid, res, msg);
 
            return new Object[]{res, msg};
        } catch (Exception e) {
            log.error("调用存储过程PRC_RF_PDA_RECEIPT_BTN_test001失败: 送货单号={}, 用户ID={}, 异常={}",
                    deliveryNo, userid, e.getMessage(), e);
            throw e;
        }
    }
 
    @Override
    public Integer processMesInvItemArnStatus(String factory, String company, String userCode, Long id) {
        Integer poResult = 1;
        String poText = "";
 
        // 调用存储过程
        baseMapper.callPrcMesInvItemArnStatus22(factory, company, userCode, id, poResult, poText);
 
        // 返回结果
        return poResult;
    }
 
    //
 
 
    @Override
    public void processMesInvItemArnStatusAsync(List<MesInvItemArn> itemArnMinus) {
        if (itemArnMinus == null || itemArnMinus.isEmpty()) {
            return;
        }
 
        // 记录开始处理的日志
        log.info("【processMesInvItemArnStatusAsync】开始处理{}条数据", itemArnMinus.size());
 
        // 分批处理,每批最多处理20条数据
        int batchSize = 20;
        int totalSize = itemArnMinus.size();
        int batchCount = (totalSize + batchSize - 1) / batchSize;
 
        for (int i = 0; i < batchCount; i++) {
            int fromIndex = i * batchSize;
            int toIndex = Math.min((i + 1) * batchSize, totalSize);
            List<MesInvItemArn> batchItems = itemArnMinus.subList(fromIndex, toIndex);
 
            log.info("【processMesInvItemArnStatusAsync】处理第{}批数据,范围:{}-{}", i + 1, fromIndex, toIndex);
 
            // 异步处理每批数据
            processAsyncBatch(batchItems);
        }
 
        log.info("【processMesInvItemArnStatusAsync】全部数据处理提交完成");
    }
 
    /**
     * 异步处理一批MesInvItemArn数据
     *
     * @param batchItems 当前批次的数据
     */
    @Async("taskExecutor")
    public void processAsyncBatch(List<MesInvItemArn> batchItems) {
        log.info("【processAsyncBatch】异步处理{}条数据开始", batchItems.size());
        processBatch(batchItems);
        log.info("【processAsyncBatch】异步处理{}条数据完成", batchItems.size());
    }
 
    @Override
    public boolean setDeliveryNotice() {
        LambdaQueryWrapper<DeliveryNoticeDetail> nullPoErpNoWrapper = new LambdaQueryWrapper<>();
        nullPoErpNoWrapper.isNull(DeliveryNoticeDetail::getPoErpNo);
        nullPoErpNoWrapper.orderByAsc(DeliveryNoticeDetail::getPid, DeliveryNoticeDetail::getLineNo);
 
        List<DeliveryNoticeDetail> nullPoErpNoList = detailService.list(nullPoErpNoWrapper);
 
        if (CollUtil.isEmpty(nullPoErpNoList)) {
            log.info("没有找到需要更新的PO_ERP_NO为null的记录");
            return true;
        }
 
        log.info("找到{}条PO_ERP_NO为null的记录需要更新", nullPoErpNoList.size());
 
        int updatedCount = 0;
 
        for (DeliveryNoticeDetail nullRecord : nullPoErpNoList) {
            Integer currentLineNo;
            try {
                currentLineNo = Integer.parseInt(nullRecord.getLineNo());
 
                // 如果LINE_NO为1,跳过这条记录,继续处理下一条
                if (currentLineNo == 1) {
                    log.info("跳过LINE_NO为1的记录: ID={}, 继续处理其他记录", nullRecord.getId());
                    continue;
                }
 
            } catch (NumberFormatException e) {
                log.warn("无法解析LINE_NO为数字: {}, 跳过这条记录", nullRecord.getLineNo());
                continue;
            }
 
            // 获取同一PID下所有记录
            LambdaQueryWrapper<DeliveryNoticeDetail> sameParentWrapper = new LambdaQueryWrapper<>();
            sameParentWrapper.eq(DeliveryNoticeDetail::getPid, nullRecord.getPid());
 
            List<DeliveryNoticeDetail> allRecords = detailService.list(sameParentWrapper);
 
            // 按LINE_NO顺序依次向前查找第一个PO_ERP_NO不为null的记录
            DeliveryNoticeDetail nearestRecord = null;
 
            // 从当前LINE_NO-1开始向前查找
            for (int searchLineNo = currentLineNo - 1; searchLineNo >= 1; searchLineNo--) {
                for (DeliveryNoticeDetail candidate : allRecords) {
                    try {
                        Integer candidateLineNo = Integer.parseInt(candidate.getLineNo());
                        if (candidateLineNo.equals(searchLineNo) && StrUtil.isNotEmpty(candidate.getPoErpNo())) {
                            nearestRecord = candidate;
                            break;
                        }
                    } catch (NumberFormatException e) {
                        log.warn("无法解析候选记录LINE_NO为数字: {}", candidate.getLineNo());
                    }
                }
                // 如果找到了就跳出外层循环
                if (nearestRecord != null) {
                    break;
                }
            }
 
            if (nearestRecord != null && StrUtil.isNotEmpty(nearestRecord.getPoErpNo())) {
                LambdaUpdateWrapper<DeliveryNoticeDetail> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(DeliveryNoticeDetail::getId, nullRecord.getId())
                        .set(DeliveryNoticeDetail::getPoErpNo, nearestRecord.getPoErpNo())
                        .set(DeliveryNoticeDetail::getPurchaseType, nearestRecord.getPurchaseType())
                        .set(DeliveryNoticeDetail::getPoLineNo, nearestRecord.getPoLineNo());
 
                boolean updated = detailService.update(updateWrapper);
                if (updated) {
                    updatedCount++;
                    log.info("更新记录ID: {}, LINE_NO: {}, 设置PO_ERP_NO为: {} (来源LINE_NO: {})",
                            nullRecord.getId(), nullRecord.getLineNo(), nearestRecord.getPoErpNo(), nearestRecord.getLineNo());
 
//                    LambdaQueryWrapper<DeliveryNotice> queryWrapper = new LambdaQueryWrapper<>();
//                    queryWrapper.eq(DeliveryNotice::getId, nullRecord.getPid());
//                    DeliveryNotice one = getOne(queryWrapper, false);
//
//                    callPdaReceiptBtn1(one.getDeliveryNo(), "PL017");
                } else {
                    log.error("更新记录ID: {} 失败", nullRecord.getId());
                }
            } else {
                log.error("记录ID: {}, LINE_NO: {} 找不到可用的PO_ERP_NO值,需要人工处理",
                        nullRecord.getId(), nullRecord.getLineNo());
            }
        }
 
        log.info("共更新了{}条记录", updatedCount);
        return updatedCount > 0;
    }
 
    /**
     * 批量处理MesInvItemArn数据
     *
     * @param batchItems 当前批次的数据
     */
    private void processBatch(List<MesInvItemArn> batchItems) {
        // 遍历每个 itemArn
        batchItems.forEach(itemArn -> {
            try {
                // 处理每个 itemArn
                Integer result = processMesInvItemArnStatus("1000", "1000", "PL017", itemArn.getId());
                log.info("【processBatch】处理itemArn: {}, 结果: {}", itemArn.getId(), result);
            } catch (Exception e) {
                // 处理异常,记录详细日志
                log.error("【processBatch】处理itemArn: {} 异常: {}", itemArn.getId(), e.getMessage(), e);
            }
        });
    }
}