salesforcexiaowu
89 分钟以前 8a0af8f743fc1e60a7fee653ae7e524bbf78d077
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
package other.xsy.jinpanPhaseII.trigger;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.RkhdHttpClient;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XObjectService;
import com.rkhd.platform.sdk.trigger.DataResult;
import org.apache.commons.lang.StringUtils;
import other.xsy.oa.common.CommoninterfaceUtil;
import other.xsy.oa.common.XMLParser;
import other.xsy.oa.triggerservice.BidService;
 
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 描述: 项目新增时触发
 */
public class BidAfterInsertTrigger {
 
    private static Logger logger = LoggerFactory.getLogger();
 
    //新建bid调用  insert完了之后 xobjectService查一下把list传进来
    public static void BidAfterInsertTriggerAfterInsertTrigger(List<Bid__c> bidlist){
        List<Bid__c> dataList = bidlist;
 
        List<Bid__c> bidList = new ArrayList<>();
        Map<Long, Bid__c> oldMap = new HashMap<>();
        List<Long> oppIds = new ArrayList<>();
        List<Opportunity> updateOpp = new ArrayList<>();
        List<String> bidIds = new ArrayList<>();
 
        for(XObject object : dataList){
            Bid__c bid = (Bid__c) object;
            if(bid.getPayee_Account__c()!=null){
                bid.setPayee_Account__c(bid.getPayee_Account__c().replaceAll("[ | ]",""));
            }
            if(bid.getOpportunity__c()!=null){
                oppIds.add(bid.getOpportunity__c());
            }
 
            bidList.add(bid);
            bidIds.add(String.valueOf(bid.getId()));
        }
        try{
            List<Bid__c> updateBid = BidService.BidTriggerHandler(bidList,oldMap,true,false);
 
            //BidOpportunityHandler 逻辑 start
            //项目投标新建,修改项目状态
            Map<Long,Long> resultMap = BidService.getBaojiaMap();
            logger.info("resultMap===" + JSONObject.toJSONString(resultMap));
            if(!oppIds.isEmpty()){
                List<Opportunity> oppList = XObjectService.instance().getByIds("opportunity",oppIds);
 
                for(Opportunity opp : oppList){
                    if(!Objects.equals(opp.getStageName__c(), "报价/招投标")){
                        Opportunity tempOpp = new Opportunity();
                        tempOpp.setId(opp.getId());
                        logger.info("opp.getEntityType()"+opp.getEntityType());
                        tempOpp.setSaleStageId(resultMap.get(opp.getEntityType()));
                        updateOpp.add(tempOpp);
                    }
                }
            }
            logger.info("updateOpp==" + JSONObject.toJSONString(updateOpp));
            if(!updateOpp.isEmpty()){
                BatchOperateResult batchResult = XObjectService.instance().update(updateOpp);
                if(!batchResult.getSuccess()){
                    for(OperateResult o :batchResult.getOperateResults()){
                        logger.info("批量更新项目招标失败: " + o.getErrorMessage());
                    }
                }
            }
            //BidOpportunityHandler 逻辑 end
 
            //BPCBidCallOutHandler start
            BidService.BPCBidCallOutHandler(bidIds);
            //BPCBidCallOutHandler end
 
            logger.info("updateBid" + JSONObject.toJSONString(bidList));
            if(!updateBid.isEmpty()){
                BatchOperateResult batchResult = XObjectService.instance().update(updateBid);
                List<OperateResult> results = batchResult.getOperateResults();
                if (batchResult.getSuccess()) {
                    for (OperateResult oresult : results) {
                        logger.info("ID: " + oresult.getDataId());
                    }
                } else {
                    for (OperateResult oresult : results) {
                        logger.info("批量更新项目招标失败: " + oresult.getErrorMessage());
                    }
                }
            }
        } catch (ApiEntityServiceException | CustomConfigException | IOException e) {
            throw new RuntimeException(e);
        }
    }
    //更新之前查 list 组一个map叫oldMap 更新之后查一下对象再组一个map叫newMap
    public static void BidBeforeUpdateTriggerBeforeTrigger(Map<Long, Bid__c> oldMap, Map<Long, Bid__c> newMap){
 
        List<Long> bidIds = new ArrayList<>();
 
        Set<Long> idS = new HashSet<>();
        Set<Long> accidS = new HashSet<>();
        Set<Long> approIds = new HashSet<>();
        Set<Long> approIds2 = new HashSet<>();
 
        for (Long id : newMap.keySet()) {
            bidIds.add(id);
        }
 
        try {
            String sql = "SELECT id, belone_Company__c, is_Self_DepartMent__c, department__c, product_Group__c, department2__c, product_Group2__c, department3__c, product_Group3__c, is_Cancellation_Bid_Term__c, is_Fit__c, " +
                    "tenderee_Type__c, bid_Info_Source__c, pro_Introduce__c, join_Account__c, judge_Way__c, customer_Credit__c, payment_Response__c, advice_And_Require__c, is_Fit_Requiredment_Tec__c, is_Suggest_Bid__c, " +
                    "is_Fit_Requiredment_Delivery__c, cannotBid__c, start_Date__c, is_ReBid__c, annualFrame__c, prequalification__c  FROM Bid__c WHERE id IN (" + StringUtils.join(bidIds, ",") + ")";
            QueryResult<Bid__c> bidResult = XObjectService.instance().query(sql, true, true);
            if (bidResult.getSuccess()) {
                for (Bid__c bid : bidResult.getRecords()) {
                    Map<String, Object> pcMap = new HashMap<>();
                    pcMap.put("id", bid.getId());
                    pcMap.put("belone_Company__c", bid.getBelone_Company__c());
                    pcMap.put("is_Self_DepartMent__c", bid.getIs_Self_DepartMent__c());
                    pcMap.put("department__c", bid.getDepartment__c());
                    pcMap.put("product_Group__c", bid.getProduct_Group__c());
                    pcMap.put("department2__c", bid.getDepartment2__c());
                    pcMap.put("product_Group2__c", bid.getProduct_Group2__c());
                    pcMap.put("department3__c", bid.getDepartment3__c());
                    pcMap.put("product_Group3__c", bid.getProduct_Group3__c());
                    oldMap.put(bid.getId(), bid);
                }
            }
 
            //BidCallOutHandler 更新 时走的逻辑 start
            List<Bid__c> uList = new ArrayList<>();
            for (Long id : newMap.keySet()) {
                Bid__c tempBid = new Bid__c();
                tempBid.setId(id);
 
                Boolean isShowErr = false;
                String nullFiled = ":";
 
                //当天日期-7的时间戳
                // 获取当前时间
                LocalDateTime now = LocalDateTime.now();
 
                // 获取7天前0点的时间
                LocalDateTime sevenDaysAgoMidnight = now.minusDays(7)
                        .withHour(0)
                        .withMinute(0)
                        .withSecond(0)
                        .withNano(0);
 
                // 转换为时间戳
                long before7timestamp = sevenDaysAgoMidnight.atZone(ZoneId.systemDefault())
                        .toInstant()
                        .toEpochMilli();
 
                System.out.println("7天前0点时间戳: " + before7timestamp);
 
                if (oldMap.containsKey(id)) {
                    Bid__c newData = newMap.get(id);
                    Bid__c oldData = oldMap.get(id);
                    if (newMap.get(id).getPayee_Account__c() != null) {
                        tempBid.setPayee_Account__c(newMap.get(id).getPayee_Account__c().replaceAll("[ | ]", ""));
                    }
                    //如果作废,解锁记录
                    if (oldData.getIs_Cancel__c() != newData.getIs_Cancel__c() && newData.getIs_Cancel__c().equals(1)) {
                        if (newData.getLockStatus().equals(2)) {
                            tempBid.setLockStatus(1);
                        }
                        tempBid.setIs_Callout__c(true);
                    }
 
                    //CannotBid 逻辑 start
                    if (tempBid.getCannotBid__c() && ((newData.getStart_Date__c() != oldData.getStart_Date__c() && (newData.getStart_Date__c() > before7timestamp)) || newData.getIs_ReBid__c().equals(1) || newData.getPrequalification__c().equals(1))) {
                        logger.info("*** jin: ");
                        tempBid.setCannotBid__c(false);
                    }
                    //CannotBid 逻辑 end
 
                    //同步标识勾选。
                    if ((oldData.getIsCheck__c() != newData.getIsCheck__c() && newData.getIsCheck__c())     //同步标识勾选
                            || (newData.getIsCheck__c() && newData.getStart_Date__c() != oldData.getStart_Date__c())//或 初次同步后开标日期修改
                            || (newData.getIsCheck__c() && newData.getIs_ReBid__c() != oldData.getIs_ReBid__c())// 或 初次同步后取消投标
                            || (newData.getIsCheck__c() && newData.getAnnualFrame__c() != oldData.getAnnualFrame__c())) {// 或 初次同步后修改是否年度框架招标
                        idS.add(id);
                        accidS.add(newData.getPurchase_Department__c());
                    }
                    // Is_Callout__c测试
                    if ((newData.getApproveStatus__c().equals(4) && oldData.getApproveStatus__c() != newData.getApproveStatus__c() && !newData.getOA_Check__c()) || (oldData.getIs_Callout__c() != oldData.getIs_Callout__c() && newData.getIs_Callout__c())) {
                        if ((newData.getDeposit_Apply_Type__c().equals(1) || newData.getDeposit_Apply_Type__c().equals(2)) && (newData.getIs_Have_Deposit__c() != null && newData.getIs_Have_Deposit__c().equals(1))) {
                            tempBid.setLink_Address__c(null);
                            approIds.add(id);
                        } else if (newData.getIs_Have_Deposit__c() != null && newData.getIs_Have_Deposit__c().equals(1) && newData.getDeposit_Apply_Type__c() != null && newData.getDeposit_Apply_Type__c().equals(3)) {
                            tempBid.setGuartee_Link__c(null);
                            tempBid.setKjzl__c(null);
                            approIds2.add(id);
                        }
                    }
                    OperateResult operateResult = XObjectService.instance().update(tempBid,true);
                    if (operateResult.getSuccess()) {
                        logger.info("*** uList: 批量更新成功!");
                    }
                }
            }
            //标识勾选后,同步至智能平台
            if (!idS.isEmpty()) {
                //接口请求TODO------
                //Utilities_Interface.outboundVporalExecute(idS,'Bid');
                List<String> idslist = new ArrayList<>();
                for (Long id : idS) {
                    idslist.add(String.valueOf(id));
                }
 
                String implResponse = CommoninterfaceUtil.sendInterfaceRequest("Bid", idslist, "outbound");
                //同步IMScode
                implResponse = XMLParser.cleanXmlString(implResponse);
                implResponse.replaceAll("\\\\\\\\r", "");
                implResponse.replaceAll("\\\\\\\\n", "");
                implResponse.replaceAll("\\\\\\\\t", "");
                implResponse = XMLParser.processXmlString(implResponse);
                String s1 = XMLParser.xmlToJson(implResponse);  // 使用当前类的xmlToJson方法
                JSONObject json = JSONObject.parseObject(s1);
 
                //xml转JSONObject  IMScode赋值
                logger.info("json===" + JSONObject.toJSONString(json));
                //要解析imscode去更新到投标上
                if (json.getJSONObject("response").getJSONObject("fields").getString("msg").equals("操作成功")) {
                    JSONObject responese = json.getJSONObject("response");
                    String imsCode = responese.getJSONObject("fields").getString("imsCode");
                    logger.info("imsCode===" + imsCode);
                    Bid__c updatebid = new Bid__c();
                    updatebid.setId(Long.valueOf(idslist.get(0)));
                    updatebid.setBid_Number__c(imsCode);
                    OperateResult uresult = XObjectService.instance().update(updatebid,true);
                    logger.info("updateInq" + JSONObject.toJSONString(updatebid));
                }
            }
 
            if (!approIds.isEmpty()) {
                Map<Long, String> linkMap = new HashMap<Long, String>();
                String contentSql = "SELECT id, ContentDownloadUrl__c,Title__c,LinkedEntityId__c FROM ContentDocumentPublicLink__c WHERE LinkedEntityId__c IN (" + approIds + ")";
                //QueryResult<ContentDocumentPublicLink__c> contentResult = XObjectService.instance().query(contentSql);
//                for(ContentDocumentPublicLink__c cdp:[SELECT ContentDownloadUrl__c,Title__c,LinkedEntityId__c
//                FROM ContentDocumentPublicLink__c
//                WHERE LinkedEntityId__c IN :approIds]){
//                    if(linkMap.containsKey(cdp.LinkedEntityId__c)){
//                        linkMap.put(cdp.LinkedEntityId__c,linkMap.get(cdp.LinkedEntityId__c)+'|'+cdp.ContentDownloadUrl__c+'&name='+cdp.Title__c);
//                    }else{
//                        linkMap.put(cdp.LinkedEntityId__c,cdp.ContentDownloadUrl__c+'&name='+cdp.Title__c);
//                    }
//                }
//                for(Long id: newMap.keySet()){
//                    if(linkMap.containsKey(inq.Id)){
//                        inq.Link_Address__c=linkMap.get(inq.Id);
//                    }
//                }
                //接口-----
                //Utilities_Interface.outboundVporalExecute(approIds,'BidDeposit');
                //请求接口
                List<String> idsList = new ArrayList<>();
                for(Long id : approIds){
                    idsList.add(String.valueOf(id));
                }
                String implResponse = CommoninterfaceUtil.sendInterfaceRequest("BidDeposit", idsList, "outbound");
 
                //同步IMScode
                implResponse = XMLParser.cleanXmlString(implResponse);
                implResponse.replaceAll("\\\\\\\\r", "");
                implResponse.replaceAll("\\\\\\\\n", "");
                implResponse.replaceAll("\\\\\\\\t", "");
                implResponse = XMLParser.processXmlString(implResponse);
                String s1 = XMLParser.xmlToJson(implResponse);  // 使用当前类的xmlToJson方法
                JSONObject json = JSONObject.parseObject(s1);
 
                //xml转JSONObject  IMScode赋值
                logger.info("json===" + JSONObject.toJSONString(json));
                //要解析imscode去更新到投标上
                if (json.getJSONObject("response").getJSONObject("fields").getString("msg").equals("操作成功")) {
                    JSONObject responese = json.getJSONObject("response");
                    String imsCode = responese.getJSONObject("fields").getString("imsCode");
                    logger.info("imsCode===" + imsCode);
                    Bid__c updatebid = new Bid__c();
                    updatebid.setId(Long.valueOf(idsList.get(0)));
                    updatebid.setOA_Check__c(true);
                    updatebid.setOA_Time__c(System.currentTimeMillis());
 
                    OperateResult uresult = XObjectService.instance().update(updatebid,true);
                    if(uresult.getSuccess()){
                        logger.error("229====" + uresult.getErrorMessage());
                    }else{
                        logger.error("349====" + uresult.getErrorMessage());
                    }
                    logger.info("updateInq" + JSONObject.toJSONString(updatebid));
                }
            }
 
            if (!approIds2.isEmpty()) {
                //保函文件链接
                Map<Long, String> linkMap = new HashMap<Long, String>();
                //开具资料文件链接
                Map<Long, String> linkMap2 = new HashMap<Long, String>();
//                for(ContentDocumentPublicLink__c cdp:[SELECT ContentDownloadUrl__c,Title__c,LinkedEntityId__c
//                FROM ContentDocumentPublicLink__c
//                WHERE LinkedEntityId__c IN :approIds2
//                AND Title__c != null
//                AND ContentDownloadUrl__c != null]){
//                    if(linkMap.containsKey(cdp.LinkedEntityId__c)){
//                        if(cdp.Title__c.contains('用户格式')){
//                            linkMap.put(cdp.LinkedEntityId__c,linkMap.get(cdp.LinkedEntityId__c)+'|'+cdp.ContentDownloadUrl__c+'&name='+cdp.Title__c);
//                        }
//                    }else{
//                        if(cdp.Title__c.contains('用户格式')){
//                            linkMap.put(cdp.LinkedEntityId__c,cdp.ContentDownloadUrl__c+'&name='+cdp.Title__c);
//                        }
//                    }
//                    if(linkMap2.containsKey(cdp.LinkedEntityId__c)){
//                        if(cdp.Title__c.contains('招标文件')){
//                            linkMap2.put(cdp.LinkedEntityId__c,linkMap2.get(cdp.LinkedEntityId__c)+'|'+cdp.ContentDownloadUrl__c+'&name='+cdp.Title__c);
//                        }
//                    }else{
//                        if(cdp.Title__c.contains('招标文件')){
//                            linkMap2.put(cdp.LinkedEntityId__c,cdp.ContentDownloadUrl__c+'&name='+cdp.Title__c);
//                        }
//                    }
//                }
//                for(Bid__c inq:(List<Bid__c>)Trigger.new){
//                    if(linkMap.containsKey(inq.Id)){
//                        inq.Guartee_Link__c=linkMap.get(inq.Id);
//                    }
//                    if(linkMap2.containsKey(inq.Id)){
//                        inq.Kjzl__c=linkMap2.get(inq.Id);
//                    }
//                }
                //接口传值-----
                //Utilities_Interface.outboundVporalExecute(approIds2,'BidGuarantee');
                List<String> idsList = new ArrayList<>();
                for(Long id : approIds2){
                    idsList.add(String.valueOf(id));
                }
                String implResponse = CommoninterfaceUtil.sendInterfaceRequest("BidGuarantee", idsList, "outbound");
                //同步IMScode
                implResponse = XMLParser.cleanXmlString(implResponse);
                implResponse.replaceAll("\\\\\\\\r", "");
                implResponse.replaceAll("\\\\\\\\n", "");
                implResponse.replaceAll("\\\\\\\\t", "");
                implResponse = XMLParser.processXmlString(implResponse);
                String s1 = XMLParser.xmlToJson(implResponse);  // 使用当前类的xmlToJson方法
                JSONObject json = JSONObject.parseObject(s1);
 
                //xml转JSONObject  IMScode赋值
                logger.info("json===" + JSONObject.toJSONString(json));
                //要解析imscode去更新到投标上
                if (json.getJSONObject("response").getJSONObject("fields").getString("msg").equals("操作成功")) {
                    JSONObject responese = json.getJSONObject("response");
                    String imsCode = responese.getJSONObject("fields").getString("imsCode");
                    logger.info("imsCode===" + imsCode);
                    Bid__c updatebid = new Bid__c();
                    updatebid.setId(Long.valueOf(idsList.get(0)));
                    updatebid.setOA_Check__c(true);
                    updatebid.setOA_Time__c(System.currentTimeMillis());
 
                    OperateResult uresult = XObjectService.instance().update(updatebid,true);
                    if(uresult.getSuccess()){
                        logger.info("270====" + uresult.getDataId());
                    }else{
                        logger.error("272====" + uresult.getErrorMessage());
                    }
                    logger.info("updateInq" + JSONObject.toJSONString(updatebid));
                }
            }
 
            if (!accidS.isEmpty()) {
                List<String> accIdSet = new ArrayList<>();
                for (Long accid : accidS) {
                    accIdSet.add(String.valueOf(accid));
                }
                //调用接口
                //Utilities_Interface.outboundVporalExecute(accidS,'Account');
                CommoninterfaceUtil.sendInterfaceRequest("Account", accIdSet, "outbound");
            }
 
            //调用after的triger
 
        } catch (ApiEntityServiceException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static void BidBeforeUpdateTriggerAfterTrigger(Map<Long, Bid__c> oldMap, Map<Long, Bid__c> newMap) throws ApiEntityServiceException {
        //获取beforeUpdate 的list
        List<Bid__c> bidList = new ArrayList<>();
 
        List<String> bidIds = new ArrayList<>();
 
 
        for(Long id : newMap.keySet()){
            bidList.add(newMap.get(id));
            bidIds.add(String.valueOf(id));
        }
 
 
        List<Bid__c> bidupdateList = BidService.BidTriggerHandler(bidList, oldMap,true,false);
        if(bidupdateList.size()>0){
            BatchOperateResult batchResult = XObjectService.instance().update(bidupdateList, true,true);
            List<OperateResult> results = batchResult.getOperateResults();
            if (batchResult.getSuccess()) {
                for (OperateResult oresult : results) {
                    logger.info("ID: " + oresult.getDataId());
                }
            } else {
                for (OperateResult oresult : results) {
                    logger.info("批量更新项目招标失败: " + oresult.getErrorMessage());
                }
            }
        }
 
        //BPCBidCallOutHandler start
        BidService.BPCBidCallOutHandler(bidIds);
        //BPCBidCallOutHandler end
 
    }
    /**
     * 市场活动 expense_detail__c 触发  新增后,更新后,删除后,恢复后
     */
    public static void ExpenseDetailTriggerafterInUpDeHf(List<ExpenseDetail__c> newList, List<ExpenseDetail__c> oldList) {
        logger.info("费用报销明细触发器 newList:" + newList);
        try {
            List<DataResult> result = new ArrayList<>();
            if(newList != null && !newList.isEmpty()){
                // 查询市场活动不为空的
                Set<Long> collect = newList.stream()
                        .filter(expenseDetail -> ((ExpenseDetail__c) expenseDetail).getCampaign__c() != null)
                        .map(expenseDetail -> ((ExpenseDetail__c) expenseDetail).getCampaign__c())
                        .collect(Collectors.toSet());
                if(!collect.isEmpty()){
                    for (ExpenseDetail__c expenseDetail__c : oldList) {
                        if (expenseDetail__c.getCampaign__c()!=null) {
                            collect.add(expenseDetail__c.getCampaign__c());
                        }
                    }
                }
                logger.info("需要重新累计的市场活动:"+ JSON.toJSONString(collect));
                if (collect.size()>0){
                    String sql = "select id,amount__c,campaign__c from expenseDetail__c where campaign__c  in (" + parseListToStr2(collect)+")";
                    logger.info("sql:"+sql);
                    QueryResult<ExpenseDetail__c> query = XObjectService.instance().query(sql, true, true);
                    HashMap<Long, Double> map = new HashMap<>();
                    // 先给每个 市场活动的金额 初始为空
                    for (Long l : collect) {
                        map.put(l,0.0);
                    }
                    // 给每个市场活动的金额 进行累计汇总
                    for (ExpenseDetail__c record : query.getRecords()) {
                        if (map.containsKey(record.getCampaign__c())) {
                            map.put(record.getCampaign__c(), map.get(record.getCampaign__c()) + record.getAmount__c());
                        }else {
                            map.put(record.getCampaign__c(), record.getAmount__c());
                        }
                    }
                    logger.info("map:"+JSON.toJSONString(map));
                    ArrayList<Campaign> campaignArrayList = new ArrayList<>();
                    if (!map.isEmpty()){
                        for (Map.Entry<Long, Double> entry : map.entrySet()) {
                            Campaign campaign = new Campaign();
                            campaign.setId(entry.getKey());
                            campaign.setActualCost(entry.getValue());
                            campaignArrayList.add(campaign);
                            result.add(new DataResult(true,"",campaign));
                        }
                        logger.info("campaignArrayList:" + JSON.toJSONString(campaignArrayList));
                        BatchOperateResult update = XObjectService.instance().update(campaignArrayList,true,true);
                    }
                }else {
                    for (XObject xObject : newList) {
                        result.add(new DataResult(true, "",xObject));
                    }
                }
            }
            logger.info("费用报销明细触发器 结果:" + JSON.toJSONString(result));
        }catch (Exception e){
            logger.error("费用报销明细触发器 异常:" + e);
        }
    }
 
    /**
     * 发货单盖章更新 触发
     */
    public static void ReceiptandInspectionNoteTriggerafterUpdate(List<Receipt_and_Inspection_Note__c> newList, List<Receipt_and_Inspection_Note__c> oldList){
        logger.info("发货单盖章更新触发器 newList:" + newList);
        try {
            List<DataResult> results = new ArrayList<>();
            RkhdHttpClient rkhdclient = null;
            try {
                rkhdclient = RkhdHttpClient.instance();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Map<Long,Receipt_and_Inspection_Note__c> newMap = new HashMap<>();
            logger.info("afterUpdateTrigger触发器启动: 更新条数" + newList.size());
            //拿到更新后的新数据
            for (Receipt_and_Inspection_Note__c xObject : newList) {
                newMap.put(xObject.getId(),xObject);
                results.add(new DataResult(true, "", xObject));
            }
            logger.info("新数据" + newMap);
            logger.info("afterUpdate拿到oldlist====" + oldList);
            Map<Long, Receipt_and_Inspection_Note__c> oldMap = new HashMap<>();
            for (Receipt_and_Inspection_Note__c old : oldList) {
                oldMap.put(old.getId(),old);
            }
            logger.info("旧数据" + oldMap);
            Set<Long> raiIdSet = new HashSet<>();
            for(Map.Entry<Long,Receipt_and_Inspection_Note__c> entry : newMap.entrySet()){
                Receipt_and_Inspection_Note__c newPp = entry.getValue();
                Receipt_and_Inspection_Note__c oldPp = oldMap.get(newPp.getId());
 
                if(!Objects.equals(newPp.getDelivery__c(), oldPp.getDelivery__c())
                        || !newPp.getRecycle_Identification__c().equals(oldPp.getRecycle_Identification__c())
                        || !Objects.equals(newPp.getStatue__c(), oldPp.getStatue__c())
                        || !Objects.equals(newPp.getNot_Recycle_Reason__c(), oldPp.getNot_Recycle_Reason__c())
                        || !Objects.equals(newPp.getAcceptance_Type__c(), oldPp.getAcceptance_Type__c())
                        || !Objects.equals(newPp.getClosed_Reason__c(), oldPp.getClosed_Reason__c())
                        || !Objects.equals(newPp.getRemark__c(), oldPp.getRemark__c())
                ){
                    //更新后数据与更新前数据不一致,则执行更新
                    raiIdSet.add(newPp.getId());
                }
            }
 
            if(raiIdSet!=null){
                //todo     调用SAP接口
                //Utilities_Interface.outboundSAPVportalExecute(rlIdSet, 'ReconciliationTo_SAP');
                List<String> stringList = raiIdSet.stream()
                        // 将每个 Long 转换为 String
                        .map(String::valueOf)
                        // 收集为 List
                        .collect(Collectors.toList());
                CommoninterfaceUtil.sendInterfaceRequest("NoteStatusToSAP",stringList,"outbound");
                logger.info("调用外部SAP接口===========");
            }
            logger.info("发货单盖章更新触发器 结果:" + JSON.toJSONString(results));
        }catch (Exception e){
            logger.error("发货单盖章更新触发器 异常:" + e);
        }
    }
 
 
    /**
     * 将集合转换为SQL IN子句格式的字符串
     * @param collection 需要转换的集合
     * @return 格式化后的字符串,如: 'item1', 'item2'
     */
    public static String parseListToStr2(Collection<?> collection) {
        if (collection == null || collection.isEmpty()) {
            return "";
        }
        return collection.stream()
                .map(item -> "'" + item + "'")
                .collect(Collectors.joining(", "));
    }
 
 
}