binxie
2023-06-26 1b3fb93f787b8b546a307bf063183f5295d183f8
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
global class updateESignBatchAttachment implements Database.Batchable < sObject > , Database.Stateful {
    //电子签收单-签收单录入表更新签收单  精琢技术 wql 2020-09-25 start
    /*
    ①正常执行 Database.executeBatch(new updateESignBatchAttachment(), 20);
    ②处理某一个签收单  Database.executeBatch(new updateESignBatchAttachment(''), 1);
    ③批量处理某些签收单(不是最终状态的) Database.executeBatch(new updateESignBatchAttachment(['','','']), 20);
    ④处理某一个最终状态的签收单 Database.executeBatch(new updateESignBatchAttachment('',true), 1);
    ⑤批量处理某些最终状态的签收单 Database.executeBatch(new updateESignBatchAttachment('['','','']',true), 20);
    ⑥处理某一天的所有签收单 Database.executeBatch(new updateESignBatchAttachment(2020-09-27), 20);
    ⑦处理某一时间段的所有签收单 Database.executeBatch(new updateESignBatchAttachment(2020-09-27,2020-09-28), 20);
 
    */
    private static final Integer MAXERRORCNT = 20; // 邮件表单位最大错误信息显示数量
    private ScBean scB;
    private ErrorBean eb = new ErrorBean(); // 邮件发送ERRORBEAN
    private String scErrorMessage = ''; // 添加计划错误信息
 
    //手动执行标识
    // private Boolean ManualExecution_Identification;
 
    //存放检索的soql语句
    private String query;
    //存放需要更新的日期
    private Date toDate;
    //存放一段时间的开始日期
    private Date startDate;
    //存放一段时间的结束日期
    private Date endDate;
    //存放需要更新的签收单id
    private String id;
    //存放需要更新的一些签收单
    private List < String > ids;
    //存放已经最终状态的flag
    private Boolean flag;
    //用于执行batch同时记录日志信息
    private BatchIF_Log__c iflog;
    global List < String > emailMessages = new List < String > ();
    global Integer totalCount = 0; // 总件数
    global Integer failedCount = 0; //失败件数
    global Boolean ManualExecution_Identification = false;
    //默认跑所有签收单
    global updateESignBatchAttachment() {
 
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start1\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一天的签收单
    global updateESignBatchAttachment(Date toDate) {
        //手动标识置成true
        this.ManualExecution_Identification = true;
 
        this.toDate = toDate;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start2\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一时间段的 签收单
    global updateESignBatchAttachment(Date startDate, Date endDate) {
        //手动标识置成true
        this.ManualExecution_Identification = true;
        this.startDate = startDate;
        this.endDate = endDate;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start3\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //批量更新签收单
    global updateESignBatchAttachment(List < String > ids) {
        //手动标识置成true
        this.ManualExecution_Identification = true;
        this.ids = ids;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start4\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一条的签收单
    global updateESignBatchAttachment(String id) {
 
        //手动标识置成true
        this.ManualExecution_Identification = true;
        system.debug('手动传参1:' + ManualExecution_Identification);
        this.id = id;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start5\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一条的已处理的签收单
    global updateESignBatchAttachment(String id, boolean flag) {
        //手动标识置成true
        this.ManualExecution_Identification = true;
        this.id = id;
        this.flag = flag;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start6\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //批量更新已处理的签收单
    global updateESignBatchAttachment(List < String > ids, boolean flag) {
        //手动标识置成true
        this.ManualExecution_Identification = true;
        this.ids = ids;
        this.flag = flag;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatchAttachment start7\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        scB = updateESignBatchAttachment.setSc('updateESignFormSchedule', 9, 23, 0, '0 30 2', null);
        if (System.Test.isRunningTest() == false) {
            Boolean haveError = false;
            try {
                system.schedule(scB.scName, scB.scTime, new updateESignFormSchedule());
            } catch (Exception e) {
                haveError = true;
            }
            // 如果哟同名的Batch计划删除已存在的计划重新设置
            if (haveError) {
                haveError = false;
                for (CronTrigger ct : [SELECT Id, CronJobDetailId, CronExpression, CronJobDetail.Name
                                       FROM CronTrigger
                                       WHERE CronJobDetail.Name = :scB.scName]) {
                    System.abortJob(ct.Id);
                }
                try {
                    system.schedule(scB.scName, scB.scTime, new updateESignFormSchedule());
                } catch (Exception e) {
                    scErrorMessage = e.getMessage() + e.getStackTraceString() + '<br/>';
                }
            }
        }
        //签收单 sql
        //检索 id,名字,DN签收状态(经销商),DN签收状态(医院),无前导零DN号,经销商验收结果,医院验收结果
        //销售渠道,营业助理,营业管理部担当,是否处理完毕签收单,ocsm管理省
        query = 'select id,Name,agencyDNSignUpStatus__c,HPDNSignUpStatus__c,DNNameNo0__c,agencyAcceptResult__c,HPAcceptResult__c';
        query += ',Sales_Root_Formula__c,Sales_assistant_name_text__c,RC_Manager__c,agencyConfirmDate__c,salesHPManageConfirmDate__c';
        query += ',isProcessed__c,OCM_man_province_cus__c,agencyReject__c,agencyRejectDate__c,HPReject__c,HPRejectDate__c,Statu_Achievements__r.Opportunity__r.Group_purchase_PCL__c  ';
        query += ' from eSignForm__c ';
        //检索不是最终状态的签收单
        if (flag != true) {
            query += ' where isProcessed__c = false  ';
        } else {
            if (!string.isblank(id)) {
                query += 'where id = :id';
            } else if (ids != null) {
                query += 'where id in: ids';
            }
        }
        //如果传入的是一段时间
        if (startDate != null && endDate != null) {
            query += '  and  createdDate >= : startDate and createdDate <= : endDate';
        }
        //如果传入的是某一天的日期
        else if (toDate != null) {
            query += '  and  createdDate = :toDate ';
        }
        //如果传入的是一批签收单id
        else if (ids != null) {
            query += '  and  id in: ids ';
        }
        //如果传入的是记录类型或者签收单id
        else if (!string.isblank(id)) {
            query += '  and  id = :id ';
        }
        //最后需要排序
        query += ' order by createdDate asc ';
        System.debug('sql语句:' + query);
        return Database.getQueryLocator(query);
    }
    //15分钟batch  bug  23:45 ~ 2:30 之间只运行 头尾各一次
    public static ScBean setSc(String baseName, Integer minhour, Integer maxhour, Integer minMin, String spbefore, String spafter) {
        Datetime dt = Datetime.now();
        Integer year = Integer.valueOf(dt.format('yyyy'));
        Integer month = Integer.valueOf(dt.format('MM'));
        Integer day = Integer.valueOf(dt.format('dd'));
        Integer hour = Integer.valueOf(dt.format('HH'));
        Integer min = Integer.valueOf(dt.format('mm'));
        ScBean b = new ScBean();
        if (hour == maxhour && min >= (minMin + 45)) {
            b.scName = baseName + '001';
            if (spafter != null && String.isNotBlank(spafter)) {
                b.scName = baseName + '005';
                b.scTime = spafter + ' ' + day + ' ' + month + ' ? ' + year;
                
                // system.schedule(sJobame,spafter + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
                return b;
            } else {
                dt = Datetime.now().addDays(1);
                year = Integer.valueOf(dt.format('yyyy'));
                month = Integer.valueOf(dt.format('MM'));
                day = Integer.valueOf(dt.format('dd'));
                hour = Integer.valueOf(dt.format('HH'));
                min = Integer.valueOf(dt.format('mm'));
                if (spbefore != null && String.isNotBlank(spbefore)) {
                    b.scName = baseName + '006';
                    // '0 20 8
                    b.scTime = spbefore + ' ' + day + ' ' + month + ' ? ' + year;
                    // system.schedule(sJobame,spbefore + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
                } else {
                    b.scTime = '0 ' + minMin + ' ' + minhour + ' ' + day + ' ' + month + ' ? ' + year;
                    // system.schedule(sJobame,'0 ' + minMin + ' ' + minhour + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
                }
            }
        } else if (min < minMin) {
            b.scName = baseName + '001';
            b.scTime = '0 ' + minMin + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
            // system.schedule(sJobame,'0 ' + minMin + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
        } else if (min < minMin + 15) {
            b.scName = baseName + '002';
            b.scTime = '0 ' + (minMin + 15) + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
            // system.schedule(sJobame,'0 ' + (minMin + 15) + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
        } else if (min < minMin + 30) {
            b.scName = baseName + '003';
            b.scTime = '0 ' + (minMin + 30) + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
            // system.schedule(sJobame,'0 ' + (minMin + 30) + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
        } else if (min < minMin + 45) {
            b.scName = baseName + '004';
            b.scTime = '0 ' + (minMin + 45) + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
            // system.schedule(sJobame,'0 ' + (minMin + 45) + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
        } else {
            b.scName = baseName + '001';
            b.scTime = '0 ' + minMin + ' ' + (hour + 1) + ' ' + day + ' ' + month + ' ? ' + year;
            // system.schedule(sJobame,'0 ' + minMin + ' ' + (hour + 1) +' ' + day + ' ' + month + ' ? ' + year, new AgencyShareUpdateBatchSchedule());
 
        }
        return b;
    }
 
    public static void removeOtherSc(String likeName, String needName) {
        String likeStr = likeName + '00%';
        for (CronTrigger ct : [SELECT Id, CronJobDetailId, CronExpression, CronJobDetail.Name
                               FROM CronTrigger
                               WHERE CronJobDetail.Name Like :likeStr
                               AND CronJobDetail.Name != :needName]) {
            System.abortJob(ct.Id);
        }
    }
 
    global void execute(Database.BatchableContext BC, list < eSignForm__c > eSignList) {
        //用作录入表的检索条件
        List < String > esFormidList = new List < String > ();
        //存放签收单录入表明细
        List < eSignFormLineItemEntry__c > eSignFormLineItemEntryList = new List < eSignFormLineItemEntry__c > ();
        //用作签收单明细的检索条件
        List < String > eSignFormLineIdList = new List < String > ();
        //更新的签收单明细
        List < eSignFormLineItem__c > eSignFormLuRUList = new List < eSignFormLineItem__c > ();
        //存放最后更新的 录入表id
        List < Id > fileIdList = new List < Id > ();
        //存放最新的 签收单id,签收单录入id
        Map < Id, Id > eSignIdMap = new Map < Id, Id > ();
 
        //存放最新的 签收单id,签收单录入id 用于最后一条签收单录入表不删除
        Map < Id, Id > eSignFormLastIdMap = new Map < Id, Id > ();
 
        //存放最新的 签收单id,签收单录入id 用于文件更新
        Map < Id, Id > eSignFlieIdMap = new Map < Id, Id > ();
 
        //存放录入表id,录入表
        Map < String, eSignFormEntry__c > lasteSignFormEntryMap = new Map < String, eSignFormEntry__c > ();
        //存放最新的 签收单明细id,签收单明细录入id
        Map < Id, Id > eSignFormLineItemEntryIdMap = new Map < Id, Id > ();
        //签收单录入表明细id,签收单录入表明细
        Map < String, eSignFormLineItemEntry__c > lasteSignFormLineItemEntryMap = new Map < String, eSignFormLineItemEntry__c > ();
        //存放 签收单id,文件数量
        Map < String, Integer > fileMap = new Map < String, Integer > ();
        //驳回后删除文件 后  排序问题  精琢技术 wql  2020/12/24 start
        List<Attachment> esignAttachAgencyList = new List<Attachment>();
        List<Attachment> esignAttachHPList = new List<Attachment>();
        Map<String, Integer> fileAgencyMap = new Map<String, Integer>();
        Map<String, Integer> fileHPMap = new Map<String, Integer>();
        //驳回后删除文件 后  排序问题  精琢技术 wql  2020/12/24 end
        //存放ocsm管理省
        List < String > provinceList = new List < String > ();
        //存放15位签收单id,ocsm管理省
        Map < Id, String > provinceMap = new Map < Id, String > ();
        //存放用于更新的签收单数组
        List < eSignForm__c > eSignFormList = new List < eSignForm__c > ();
        //存放签收单录入表id,name
        Map < Id, String > eSignNameMap = new Map < Id, String > ();
        //存放签收单录入表id,type
        Map < Id, String > eSignTypeMap = new Map < Id, String > ();
 
        //删除中间表数据用
        Map < String, eSignFormEntry__c > eSignStringMap = new Map < String, eSignFormEntry__c > ();
        //存放所有签收单录入表id
        List < String > luruIsSubmitList = new List < String > ();
 
        //存放所有签收单录入表id
        List < String > luruIsLastSubmitList = new List < String > ();
        //判断是否有未处理的录入表
        Map < Id, eSignFormEntry__c > unprocessedESignEneryMap = new Map < Id, eSignFormEntry__c > ();
 
        //用于判断删除驳回的附件的筛选条件
        Map < Id, eSignForm__c > rejectESignEneryMap = new Map < Id, eSignForm__c > ();
        //驳回后 删除之前上传的文件id
        List<Attachment> deleteLastFileList = new List<Attachment>();
        //存放未更新前的经销商审批状态
        Map < String, String > oldESignAgencyStatusMap = new Map < String, String > ();
        //存放未更新前的医院审批状态
        Map < String, String > oldESignHPStatusMap = new Map < String, String > ();
        try {
            //循环存放签收单id 用作检索签收单录入表的条件
            system.debug('eSignList:' + eSignList);
            if (eSignList.size() > 0) {
                for (eSignForm__c esForm : eSignList) {
                    //存放签收单id,ocsm管理省 如果询价是集采 则取ocsm管理省为集采课的担当
                    if(esForm.Statu_Achievements__r.Opportunity__r.Group_purchase_PCL__c){
                        provinceMap.put(esForm.Id, '集采课');
                        //检索条件
                        provinceList.add('集采课');
                    }else{
                        provinceMap.put(esForm.Id, esForm.OCM_man_province_cus__c);
                        //检索条件
                        provinceList.add(esForm.OCM_man_province_cus__c);
                    }
                    
                    esFormidList.add(esForm.Id);
 
                    //有经销商驳回或者医院驳回时删除之前附件
                    if (esForm.agencyRejectDate__c != null || esForm.HPRejectDate__c != null) {
                        rejectESignEneryMap.put(esForm.Id, esForm);
                    }
 
 
                }
            }
            system.debug('rejectESignEneryMap:' + rejectESignEneryMap);
            //如果map不为空 则作为筛选条件
            if (rejectESignEneryMap.size()>0) {
                List<Attachment> deleteFileList = [SELECT parentId, createdDate, Name,Description   
                                                   FROM Attachment
                                                   WHERE parentId IN: rejectESignEneryMap.keySet() order by createdDate];
                system.debug('deleteFileList:' + deleteFileList);
                if (deleteFileList.size() > 0) {
                    for (eSignForm__c esFile : rejectESignEneryMap.values()) {
 
                        for (Attachment att : deleteFileList) {
                            if (esFile.agencyRejectDate__c != null || esFile.HPRejectDate__c != null) {
                                if (att.parentId == esFile.Id ) {
                                    //①经销商驳回后需要删除的附件
                                    if (esFile.agencyRejectDate__c != null) {
                                        if (att.Name.substring(0, 1) == 'A' && att.createdDate < esFile.agencyRejectDate__c) {
                                            deleteLastFileList.add(att);
                                        }
                                    }
                                    //②医院驳回后需要删除的附件
                                    if (esFile.HPRejectDate__c != null) {
                                        if (att.Name.substring(0, 1) == 'H' && att.createdDate < esFile.HPRejectDate__c) {
                                            deleteLastFileList.add(att);
                                        }
                                    }
                                }
 
 
                            }
                        }
 
                    }
 
 
                }
            }
            system.debug('驳回后删除的文件:' + deleteLastFileList);
            //先删后增
            if (deleteLastFileList.size() > 0) {
                delete deleteLastFileList;
            }
 
            //检索所有录入表
            List < eSignFormEntry__c > eSignFormEntryList = [select id, Name, entryType__c, eSignForm__c, eSignForm__r.OCM_man_province_cus__c, salesManageConfirmDate__c, salesHPManageConfirmDate__c, agencyScanDayBack__c, agencySignUpDateBack__c, agencyConfirmDateBack__c, HPScanDayBack__c, HPSignUpDateBack__c, HPConfirmDateBack__c,
                                       eSignForm__r.Name, IsSubmit__c, IsHPSubmit__c, IsAgencyConfirmSubmit__c, agencyAutoSignUpStatus__c, HPSignUpStatus__c, Sales_Root_Formula__c, Sales_assistant_ID__c, IsHandled__c, IsHPHandled__c, createdDate, AgencyWorkflowEmailBack__c, HPWorkflowEmailBack__c, AgencyWorkflowEmail__c, HPWorkflowEmail__c, eSignForm__r.Id, agencyDNSignUpStatus__c, HPDNSignUpStatus__c, agencyReject__c, HPReject__c, IsAgencyScan__c, IsHPScan__c
                                       from eSignFormEntry__c
                                       where eSignForm__c IN: esFormidList
                                       order by eSignForm__c, createdDate asc
                                                            ];
 
            if (eSignFormEntryList.size() > 0) {
                for (Id eid : esFormidList) {
                    //遍历所有签收单
                    for (eSignFormEntry__c eSignFormEntryWhole : eSignFormEntryList) {
                        //删除用
                        eSignStringMap.put(eSignFormEntryWhole.Id, eSignFormEntryWhole);
                        //②所有的 用于更新文件(包含已处理未处理的数据 )
                        fileIdList.add(eSignFormEntryWhole.Id);
                        if (eSignFormEntryWhole.IsHandled__c == false) {
                            //未处理的
                            unprocessedESignEneryMap.put(eid, eSignFormEntryWhole);
                        }
                        if (eSignFormEntryWhole.eSignForm__r.Id  == eid) {
                            //存放 签收单id,录入表id 文件用
                            eSignFlieIdMap.put(eSignFormEntryWhole.Id, eid);
                            //存放签收单录入表,id,name 文件用
                            eSignNameMap.put(eid, eSignFormEntryWhole.eSignForm__r.Name);
                        }
 
 
                        //存放录入表id,记录类型 id,type 文件用
                        eSignTypeMap.put(eSignFormEntryWhole.Id, eSignFormEntryWhole.entryType__c);
                    }
                }
 
                system.debug('eSignFlieIdMap:' + eSignFlieIdMap);
                //外层是签收单
                for (Id esFormid : esFormidList) {
                    //内层是签收单录入表
                    for (eSignFormEntry__c eSignFormEntry : eSignFormEntryList) {
 
                        //①取最新的 录入表 + 未处理的
                        if (esFormid.equals(eSignFormEntry.eSignForm__c)) {
 
                            if (!eSignFormEntry.IsHandled__c) {
                                //存放 签收单id,录入表id
                                eSignIdMap.put(esFormid, eSignFormEntry.Id);
                                lasteSignFormEntryMap.put(esFormid, eSignFormEntry);
                                //因为按签收单倒序排,所以第一条就是最新的,直接跳出
                                // break;
                            }
                            eSignFormLastIdMap.put(esFormid, eSignFormEntry.Id);
 
                        }
 
                    }
                }
                //最后更新的录入表id
                for (Id eSignId : eSignIdMap.values()) {
                    luruIsSubmitList.add(eSignId);
                }
                //最后更新的录入表id
                for (Id eSignId : eSignFormLastIdMap.values()) {
                    luruIsLastSubmitList.add(eSignId);
                }
 
                //重新对附件排序  规则变为根据签收单现有附件序号进行排序 精琢技术 wql start
                //暂时存放一下签收单名称
                Map<string, string> tempMap = new Map<string, string>();
                List<Attachment> tempAttList = [SELECT parentId, createdDate, Name,Description  
                                                FROM Attachment
                                                WHERE parentId IN: esFormidList order by createdDate];
                if (tempAttList.size() > 0) {
                    //外层循环签收单
                    for (String es : esFormidList) {
 
                        //内层循环附件
                        for (Attachment att : tempAttList) {
                            //如果id相等
                            if (es.equals(att.parentId)) {
                                //根据名称拆分 存入不同list
                                String name = att.Name;
                                if (name.substring(0, 1).equals('A')) {
                                    esignAttachAgencyList.add(att);
                                } else if (name.substring(0, 1).equals('H')) {
                                    esignAttachHPList.add(att);
                                }
 
                            }
                        }
                        //分别存入到经销商or医院的附件map 用于后期命名
                        if (esignAttachAgencyList.size() > 0) {
                            fileAgencyMap.put(es, esignAttachAgencyList.size());
                        }
                        if (esignAttachHPList.size() > 0) {
                            fileHPMap.put(es, esignAttachHPList.size());
                        }
                        //清空list 供下一个签收单使用
                        esignAttachAgencyList.clear();
                        esignAttachHPList.clear();
 
                    }
                }
                system.debug('fileAgencyMap:' + fileAgencyMap);
                system.debug('fileHPMap:' + fileHPMap);
                //重新对附件排序  规则变为根据签收单现有附件序号进行排序 精琢技术 wql end
 
                //根据所有的签收单录入表id检索所有的签收单明细录入
                List < eSignFormLineItemEntry__c > eSignFormLineItemEntryLists = [select id, eSignFormEntry__r.entryType__c, eSignFormEntry__r.IsHandled__c, eSignFormLineItem__c, eSignFormEntry__c,
                                                   agencyConfirmResult__c, HPConfirmResult__c, HPGoodStatus__c, agencyGoodStatus__c
                                                   from eSignFormLineItemEntry__c where eSignFormEntry__c in : luruIsSubmitList  and eSignFormEntry__r.IsHandled__c = false order by createdDate asc
                                                                                 ];
                if (eSignFormLineItemEntryLists.size() > 0) {
                    for (eSignFormLineItemEntry__c eSignFormLineItemEntry : eSignFormLineItemEntryLists) {
                        eSignFormLineIdList.add(eSignFormLineItemEntry.eSignFormLineItem__c);
                    }
                }
                system.debug('eSignFormLineIdList:' + eSignFormLineIdList);
                if (eSignFormLineIdList.size() > 0) {
                    //根据签收单明细录入表 去检索签收单明细
                    List < eSignFormLineItem__c > eSignFormLineItemList = [select id, agencyGoodStatus__c, HPGoodStatus__c from eSignFormLineItem__c where id IN: eSignFormLineIdList];
                    if (eSignFormLineItemList.size() > 0) {
                        //外层签收单明细
                        for (eSignFormLineItem__c eSignFormLineItem : eSignFormLineItemList) {
                            //内层签收单明细录入
                            for (eSignFormLineItemEntry__c eSignFormLineItemEntry : eSignFormLineItemEntryLists) {
                                //明细id相等存放一个map
                                if (eSignFormLineItem.Id.equals(eSignFormLineItemEntry.eSignFormLineItem__c)) {
                                    eSignFormLineItemEntryIdMap.put(eSignFormLineItem.Id, eSignFormLineItemEntry.Id);
                                    lasteSignFormLineItemEntryMap.put(eSignFormLineItem.Id, eSignFormLineItemEntry);
                                }
                            }
                        }
                    }
                }
 
                system.debug('lasteSignFormLineItemEntryMap:' + lasteSignFormLineItemEntryMap);
                if (eSignFormLineIdList.size() > 0) {
                    //循环 更新签收单
                    for (Id esefId : eSignFormLineIdList) {
 
                        if (lasteSignFormLineItemEntryMap.containsKey(esefId)) {
                            eSignFormLineItemEntry__c luru = lasteSignFormLineItemEntryMap.get(esefId);
                            //new 一个签收单明细对象
                            eSignFormLineItem__c eSignLuRu = new eSignFormLineItem__c();
                            //签收单id
                            eSignLuRu.id = esefId;
                            //货物情况(经销商收货)
                            eSignLuRu.agencyGoodStatus__c = luru.agencyGoodStatus__c;
                            // //经销商确认结果
                            // eSignLuRu.agencyConfirmResult__c = luru.agencyConfirmResult__c;
                            //货物情况(医院收货)
                            eSignLuRu.HPGoodStatus__c = luru.HPGoodStatus__c;
                            // //经销商确认结果
                            // eSignLuRu.HPConfirmResult__c = luru.HPConfirmResult__c;
                            //同一个签收单循环遍历签收单录入表 最后一个录入表会add到更新数组中
                            if (eSignLuRu != null) {
                                system.debug('签收单明细象-----:' + eSignLuRu);
                                eSignFormLuRuList.add(eSignLuRu);
                            }
                        }
 
 
                    }
                }
                System.debug('更新的签收单明细list:' + eSignFormLuRUList);
                system.debug('esFormidList:' + esFormidList);
                if (unprocessedESignEneryMap.size() > 0) {
                    for (Id eSignFormid : unprocessedESignEneryMap.keySet()) {
                        //new 一个签收单对象
                        eSignForm__c eSignForm = new eSignForm__c();
 
                        String name = '';
                        String idlast = '';
                        boolean IsSubmit = false;
                        boolean IsHPSubmit = false;
                        //销售渠道
                        String Sales_Root_Formula;
                        //录入类型
                        String type;
                        System.debug('lasteSignFormEntryMap:' + lasteSignFormEntryMap);
                        if (lasteSignFormEntryMap.containsKey(eSignFormid)) {
                            eSignForm.id = eSignFormid;
                            //签收单id
                            eSignFormEntry__c eSignFormEntry = lasteSignFormEntryMap.get(eSignFormid);
                            //如果经销商确认日为空的话 进去判断更新经销商审批状态
                            if (eSignFormEntry.agencyDNSignUpStatus__c != '签收已完成') {
                                if (eSignFormEntry.agencyConfirmDateBack__c == null) {
                                    if (eSignFormEntry.IsSubmit__c == true) {
                                        eSignForm.agencyAutoSignUpStatus__c = '申请中';
                                        eSignForm.agencyReject__c = false;
                                    } else {
                                        if (eSignFormEntry.agencyScanDayBack__c != null && eSignFormEntry.IsAgencyScan__c) {
                                            eSignForm.agencyAutoSignUpStatus__c = '草案中';
                                            eSignForm.agencyReject__c = false;
 
                                        }
                                    }
                                }
                                //未更新前的经销商审批状态 用于文件累计汇总
                                if(eSignFormEntry.agencyAutoSignUpStatus__c!=null &&eSignFormEntry.agencyAutoSignUpStatus__c!=''){
                                    oldESignAgencyStatusMap.put('A' + eSignForm.id, eSignFormEntry.agencyAutoSignUpStatus__c);
                                }else{
                                    oldESignAgencyStatusMap.put('A' + eSignForm.id, '无');
                                }
                                
                            }
                            if (eSignFormEntry.HPDNSignUpStatus__c != '签收已完成') {
                                //如果医院确认日为空的话 进去判断更新医院审批状态
                                if (eSignFormEntry.salesHPManageConfirmDate__c == null) {
                                    if (eSignFormEntry.IsHPSubmit__c == true) {
                                        eSignForm.HPSignUpStatus__c = '申请中';
                                        eSignForm.HPReject__c = false;
                                    } else {
                                        if (eSignFormEntry.HPScanDayBack__c != null && eSignFormEntry.IsHPScan__c) {
                                            eSignForm.HPSignUpStatus__c = '草案中';
                                            eSignForm.HPReject__c = false;
 
                                        }
                                    }
                                }
                                //未更新前的医院审批状态 用于文件累计汇总
                                if(eSignFormEntry.HPSignUpStatus__c!=null &&eSignFormEntry.HPSignUpStatus__c!=''){
                                    oldESignHPStatusMap.put('H' + eSignForm.id, eSignFormEntry.HPSignUpStatus__c);
                                }else{
                                    oldESignHPStatusMap.put('H' + eSignForm.id, '无');
                                }
                                
                            }
 
                            //如果没变化则不更新
                            if (eSignFormEntry.AgencyWorkflowEmailBack__c != eSignFormEntry.AgencyWorkflowEmail__c) {
                                //经销商邮件
                                eSignForm.AgencyWorkflowEmail__c = eSignFormEntry.AgencyWorkflowEmailBack__c;
                            }
                            //如果没变化则不更新
                            if (eSignFormEntry.HPWorkflowEmailBack__c != eSignFormEntry.HPWorkflowEmail__c) {
                                //医院邮件
                                eSignForm.HPWorkflowEmail__c = eSignFormEntry.HPWorkflowEmailBack__c;
                            }
                            if (eSignFormEntry.agencyDNSignUpStatus__c != '签收已完成') {
                                //经销商扫描日
                                if (eSignFormEntry.agencyScanDayBack__c != null) {
                                    eSignForm.agencyScanDay__c = eSignFormEntry.agencyScanDayBack__c;
                                }
                                //经销商签收日
                                if (eSignFormEntry.agencySignUpDateBack__c != null) {
                                    eSignForm.agencySignUpDate__c = eSignFormEntry.agencySignUpDateBack__c;
                                }
                                //经销商确认日
                                if (eSignFormEntry.agencyConfirmDateBack__c != null) {
                                    eSignForm.agencyConfirmDate__c = eSignFormEntry.agencyConfirmDateBack__c;
                                }
                            }
 
                            if (eSignFormEntry.HPDNSignUpStatus__c != '签收已完成') {
                                //医院扫描日
                                if (eSignFormEntry.HPScanDayBack__c != null) {
                                    eSignForm.HPScanDay__c = eSignFormEntry.HPScanDayBack__c;
                                }
                                //医院签收日
                                if (eSignFormEntry.HPSignUpDateBack__c != null) {
                                    eSignForm.HPSignUpDate__c = eSignFormEntry.HPSignUpDateBack__c;
                                }
                                //医院确认日
                                if (eSignFormEntry.HPConfirmDateBack__c != null) {
                                    eSignForm.HPConfirmDate__c = eSignFormEntry.HPConfirmDateBack__c;
                                }
                            }
 
                            //给营业助理赋值
                            eSignForm.Sales_assistant_name_text__c = eSignFormEntry.Sales_assistant_ID__c;
                            //存一个id
                            idlast = eSignFormEntry.Id;
                            //签收单name用作文件命名
                            name = eSignFormEntry.eSignForm__r.Name;
                            //是否经销商提交
                            IsSubmit = eSignFormEntry.IsSubmit__c;
                            //是否医院提交
                            IsHPSubmit = eSignFormEntry.IsHPSubmit__c;
                            //最后录入表
                            eSignForm.finalUpadteFrom__c = eSignFormEntry.Id;
                            //销售渠道 区分直销还是分销
                            Sales_Root_Formula = eSignFormEntry.Sales_Root_Formula__c;
                            //录入类型
                            type = eSignFormEntry.entryType__c;
 
                        }
                        system.debug('签收单对象-----:' + eSignForm);
                        if (eSignForm != null) {
                            system.debug('eSignFormid:' + eSignFormid);
                            if (eSignForm.id != null) {
 
                                eSignFormList.add(eSignForm);
                            }
 
                        }
                        system.debug('eSignFormList111:' + eSignFormList);
                        if (eSignFormList.size() > 0) {
                            //更新OCSM管理省 担当
                            eSignFormList = updateOwner(provinceList, provinceMap, eSignFormList, false);
                        }
 
 
                    }
                }
 
 
            }
 
            if (eSignFormList.size() <= 0) {
                system.debug('我走到这里了!');
                eSignFormList  = updateOwner(provinceList, provinceMap, eSignList, true);
            }
 
 
            List<Id> fileList = new List<Id> ();
            if (fileIdList.size() > 0) {
                for (Id fileId : fileIdList) {
                    if (!fileList.contains(fileId)) {
                        fileList.add(fileId);
                    }
 
                }
            }
 
            System.debug('fileIdList:' + fileIdList);
            System.debug('fileList:' + fileList);
            //用于最后insert 附件
            List<Attachment> insertAttactment = new List<Attachment>();
            //附件  start
            List<Attachment> attachMentList = [SELECT id, parentId, Body, Name, ContentType,Description  from Attachment where parentId IN :fileList and Description!='电子签收单:已处理'];
            //修复已处理数据 附件没更新  即没有附件能提交的bug 精琢技术 wql 2021/01/19 start 
            List<Attachment> eSignEntryAttachMentList = new List<Attachment>();
            //文件数量 用于文件命名
            Integer agencyCount = 0;
            Integer hpCount = 0;
 
            String name;
            String type ;
            Integer agencyFileCountNum = 0;
            Integer hpFileCountNum = 0;
            Integer i = 0;
            Integer j = 0;
            //记录该签收单的最新经销商附件数量
            Map<id,Integer> eSignAgencyAttSum = new Map<id,Integer> ();
            //记录该签收单的最新医院附件数量
            Map<id,Integer> eSignHpAttSum = new Map<id,Integer> ();
 
            //同一条录入表多个附件标识
            Boolean agencyNumFlag = false;
            Boolean hpNumFlag = false;
 
            //存1条数据内多个附件 一个固定值
            Integer agencySumCount = 0;
            Integer hpSumCount = 0;
 
            if (fileList.size() > 0) {
                system.debug('attachMentList:' + attachMentList);
                system.debug('eSignFlieIdMap:' + eSignFlieIdMap);
                system.debug('eSignNameMap:' + eSignNameMap);
                for (Id eSignFormEntryId : fileList) {
 
                    for (Attachment attach : attachMentList) {
 
                        if (attach.parentId == eSignFormEntryId) {
                            Id eid = eSignFlieIdMap.get(attach.parentId);
                            system.debug('eid:' + eid);
 
                            name = eSignNameMap.get(eid);
                            system.debug('name:' + name);
                            type = eSignTypeMap.get(attach.parentId);
 
                            //因为外层循环是中间表 如果2条以上录入表都有经销商附件 则使用最新构建的经销商附件数量来命名
                            //否则取未更新之前有的经销商附件数量 并且 不是1个录入表多个附件 也就是false的时候 取模拟的最新数量
                            if(eSignAgencyAttSum.size()>0&&!agencyNumFlag){
                                agencyCount = eSignAgencyAttSum.get(eid);
                                //记录一个最新的附件数
                                agencySumCount =agencyCount;
                            }else if(agencySumCount>0){
                                //本次循环内 第一次取附件数最新值 后续都在此基础上i++
                                agencyCount =agencySumCount;
                            }
                            else if(fileAgencyMap.size() > 0){
                                //只有一条数据时,使用此附件数即可 后续在此基础上i++
                                agencyCount = fileAgencyMap.get(eid);
                            }
 
                            //同一个内部循环里置成true
                            agencyNumFlag = true;
                            //经销商附件命名 start
                            // if (fileAgencyMap.size() > 0) {
                            //     agencyCount = fileAgencyMap.get(eid);
                            // }
 
                            system.debug(name + 'agencyCount:' + agencyCount);
                            if (agencyCount == null || agencyCount == 0) {
                                agencyFileCountNum = 1 + i;
                            } else {
                                agencyFileCountNum = agencyCount + 1 + i;
                            }
 
                            //经销商附件命名 end
                            //因为外层循环是中间表 如果2条以上录入表都有医院附件 则使用最新构建的医院附件数量来命名
                            //否则取未更新之前有的医院附件数量 并且 不是1个录入表多个附件 也就是false的时候 取模拟的最新数量
                            if(eSignHpAttSum.size()>0&&!hpNumFlag){
                                hpCount = eSignHpAttSum.get(eid);
                                //记录一个最新的附件数
                                hpSumCount = hpCount;
                            }else if(hpSumCount >0 ){
                                //本次循环内 第一次取附件数最新值 后续都在此基础上j++
                                hpCount =hpSumCount;                        
                            }
                            else if(fileHPMap.size() > 0){
                                //只有一条数据时,使用此附件数即可 后续在此基础上j++
                                hpCount = fileHPMap.get(eid);
                            }
                            //同一个内部循环里置成true
                            hpNumFlag =true;
                            //医院附件命名 start
                            // if (fileHPMap.size() > 0) {
                            //     hpCount = fileHPMap.get(eid);
                            // }
                            system.debug(name + 'hpCount:' + hpCount);
 
                            if (hpCount == null || hpCount == 0) {
                                hpFileCountNum = 1 + j;
                            } else {
                                hpFileCountNum = hpCount + 1 + j;
                            }
                            //构建最新的签收单经销商附件数量
                            if(agencyFileCountNum>0){
                                eSignAgencyAttSum.put(eid,agencyFileCountNum);
                            }
                            //构建最新的签收单医院附件数量
                            if(hpFileCountNum>0){
                                eSignHpAttSum.put(eid,hpFileCountNum);
                            }
                            //医院附件命名 end
                            //用于拆分经销商/医院 区别文件名
                            String finalName = '';
                            String title = '';
 
                            //文件命名
                            if (type == '经销商收货' || type == '经销商确认') {
                                finalName = 'A-' + name;
                                //用于判断多次上传文件命名
                                i++;
                                title = finalName + '--' + agencyFileCountNum;
                            } else if (type == '医院收货' || type == '医院确认') {
                                finalName = 'H-' + name;
                                //用于判断多次上传文件命名
                                j++;
                                title = finalName + '--' + hpFileCountNum;
                            } else {
                                finalName = name;
                            }
 
                            system.debug('文件名:' + title);
                            //判断一下格式,不然下载下来是类型是所有文件
                            // if(attach.ContentType == 'application/pdf'){
                            //     title = title +'.pdf';
                            // }else if(attach.ContentType == 'image/jpeg'){
                            //     title = title +'.jpg';
                            // }
                            //判断一下格式,不然下载下来是类型是所有文件 无法打开
                            if (attach.Name.lastIndexOf('.') > -1) {
                                title = title + attach.Name.substring(attach.Name.lastIndexOf('.'));
                            }
 
                            Attachment newAttachment = attach.clone();
                            newAttachment.parentId = eid;
                            newAttachment.name = title;
                            // newAttachment.ContentType =attach.ContentType;
                            //要更新的签收单附件
                            insertAttactment.add(newAttachment);
                            //反更新录入表的附件 用来判断附件是否被更新
                            Attachment oldAttachment = new  Attachment();
                            oldAttachment.Id = attach.Id;
                            oldAttachment.Description = '电子签收单:已处理';
                            eSignEntryAttachMentList.add(oldAttachment);
 
                        }
 
 
                    }
                    //整单循环后 清空值
                    i = 0;
                    j = 0;
                    agencyNumFlag= false;
                    hpNumFlag =false;
                    agencySumCount =0;
                    hpSumCount=0;
                }
 
            }
 
            //电子签收单 增加本次更新附件数量  2020/01/07 精琢技术 wql start
            //没有附件则根本不会进入
            if (insertAttactment.size() > 0) {
                insert insertAttactment;
                //反向更新录入表附件
                if(eSignEntryAttachMentList.size()>0){
                    update eSignEntryAttachMentList;
                }
 
                //更新已提交的签收单的附件数
                if (eSignFormList.size() > 0) {
                    //外层所有签收单
                    for (eSignForm__c es : eSignFormList) {
 
                        //a为经销商附件的数量 h为医院附件的数量
                        Integer a = 0;
                        Integer h = 0;
 
                        //内层所有需要更新的附件
                        for (Attachment att : insertAttactment) {
                            if (es.Id != null) {
                                if (es.Id.equals(att.parentId)) {
                                    if (es.agencyAutoSignUpStatus__c != null) {
                                        if (es.agencyAutoSignUpStatus__c.equals('申请中') && oldESignAgencyStatusMap.size()>0) {
                                                if(!oldESignAgencyStatusMap.get('A' + es.Id).equals('申请中')){
                                                    if (att.Name.substring(0, 1).equals('A')) {
                                                        a ++;
                                                    }
                                                }
                                            
                                        }
                                    }
                                    if (es.HPSignUpStatus__c != null) {
                                        if (es.HPSignUpStatus__c.equals('申请中') && oldESignHPStatusMap.size()>0) {
                                            if(!oldESignHPStatusMap.get('H' + es.Id).equals('申请中')){
                                                if (att.Name.substring(0, 1).equals('H')) {
                                                    h ++;
                                                }
                                            }
                                            
                                        }
                                    }
 
                                }
                            }
 
                        }
 
                        //只有真正扫码提交的 并且没有附件才会被更新
                        if (es.agencyAutoSignUpStatus__c != null) {
                            if (es.agencyAutoSignUpStatus__c.equals('申请中') && oldESignAgencyStatusMap.size()>0) {
                                if(!oldESignAgencyStatusMap.get('A' + es.Id).equals('申请中')){
                                    es.agencyAttachNum__c = a;
                                }
                                
                            }
                        }
                        //只有真正扫码提交的 并且没有附件才会被更新
                        if (es.HPSignUpStatus__c != null) {
                            if (es.HPSignUpStatus__c.equals('申请中') &&oldESignHPStatusMap.size()>0 ) {
                                if(!oldESignHPStatusMap.get('H' + es.Id).equals('申请中')){
                                     es.HPAttachNum__c = h;
                                }
                               
 
                            }
                        }
 
                        a = 0;
                        h = 0;
 
                    }
                }
                //电子签收单 增加本次更新附件数量  2020/01/07 精琢技术 wql end
                //文件 end
            }
            system.debug('更新的签收单:' + eSignFormList);
            //更新签收单明细并添加日志
            if (eSignFormLuRUList.size() > 0) {
                Database.SaveResult[] lsr = Database.update(eSignFormLuRUList, false);
                eb.setError(lsr, MAXERRORCNT, eSignFormLineItem__c.sObjectType);
                for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                    Database.SaveResult sr = lsr[tIdx];
                    System.debug('sr.isSuccess:' + sr.isSuccess());
                    if (!sr.isSuccess()) {
                        Database.Error emsg = sr.getErrors()[0];
                        iflog.ErrorLog__c += 'ERROR ' + eSignFormList[tIdx].Id + ' eSignFormLineItem__c:' + emsg + '\n';
                    }
                }
            }
            //更新签收单并添加日志
            if (eSignFormList.size() > 0) {
                Database.SaveResult[] lsr = Database.update(eSignFormList, false);
                eb.setError(lsr, MAXERRORCNT, eSignForm__c.sObjectType);
                for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                    Database.SaveResult sr = lsr[tIdx];
                    System.debug('sr.isSuccess:' + sr.isSuccess());
                    if (!sr.isSuccess()) {
                        Database.Error emsg = sr.getErrors()[0];
                        iflog.ErrorLog__c += 'ERROR ' + eSignFormList[tIdx].Id + ' eSignForm__c:' + emsg + '\n';
                    }
                }
            }
 
 
        }catch(NullPointerException npe){
            
                iflog.ErrorLog__c += 'ERROR : eSignForm__c:空指针错误-行号:'+ npe.getLineNumber()+ '\n';
        } 
        catch (Exception e) {
            // Database.rollback(sp);
                
            iflog.ErrorLog__c += 'ERROR : eSignForm__c:'+ e.getMessage() + '\n';
 
        }
        try{
            System.debug('luruIsLastSubmitList:'+luruIsLastSubmitList);
            if (luruIsLastSubmitList.size() > 0) {
                //删除中间表数据(因为住主详关系,删除录入表即可)
                deleteMiddleData(eSignStringMap, luruIsLastSubmitList);
            }
        }catch(Exception e){
            iflog.ErrorLog__c += 'ERROR : eSignForm__c:'+ e.getMessage() + '\n';
        }
        //文件 end
    }
 
    //删除中间表数据(因为住主详关系,删除录入表即可)
    private static void deleteMiddleData(Map < String, eSignFormEntry__c > eSignStringMap, List < String > luruIsSubmitList) {
        system.debug('检索的所有录入表:' + eSignStringMap);
        system.debug('最后录入的id :' + luruIsSubmitList + '----数量:' + luruIsSubmitList.size());
        list < eSignFormEntry__c > eSignFormDeleteList = new list < eSignFormEntry__c > ();
        for (String essm : eSignStringMap.keySet()) {
            for (String lisl : luruIsSubmitList) {
                if (essm.equals(lisl)) {
                    eSignStringMap.remove(lisl);
                }
            }
        }
        for (eSignFormEntry__c esfe : eSignStringMap.values()) {
            eSignFormDeleteList.add(esfe);
        }
        system.debug('删除的数据id:' + eSignFormDeleteList + '----数量:' + eSignFormDeleteList.size());
 
 
 
        //删除签收单录入表其他数据
        if (eSignFormDeleteList.size() > 0) {
            //循环遍历id 删除文件
            List<String> fileDeleteIdList = new List<String> ();
            List<Attachment> deleteAttachmentList = new List<Attachment>();
 
            for (eSignFormEntry__c eSigf : eSignFormDeleteList) {
                fileDeleteIdList.add(eSigf.Id);
            }
            //循环找到文件id
            if (fileDeleteIdList.size() > 0) {
 
                // 2022-02-28 shashiming Apex heap size too large
                // 去掉Body字段
                List<Attachment> attachMentList = [SELECT id, parentId, Name, ContentType,Description  from Attachment where parentId = :fileDeleteIdList];
 
                if (attachMentList.size() > 0) {
                    for (Attachment att : attachMentList) {
                        Attachment am = new Attachment();
                        am.Id = att.Id;
                        deleteAttachmentList.add(am);
                    }
                    //删除文件
                    if (deleteAttachmentList.size() > 0) {
                        delete deleteAttachmentList;
                    }
                }
 
 
            }
            //删除录入表
            delete eSignFormDeleteList;
        }
    }
    @TestVisible
    //更新营业部担当
    private static List < eSignForm__c > updateOwner(List < String > provinceList, Map < Id, String > provinceMap, List < eSignForm__c > eSignFormList, boolean ocsmFlag) {
        //营业担当 map
        Map < String, String > provinceOwnerMap = new Map < String, String > ();
        //营业助理 map
        Map < String, String > provinceGIMap = new Map < String, String > ();
 
        List < eSignForm__c > eSignFormLastList = new List < eSignForm__c >();
        //检索OCSM管理省对象
        List < OCM_Management_Province__c > ompList = [select id, Name, SalesManage__c,GI_assistant__c    from OCM_Management_Province__c where Name IN: provinceList];
        //存放map<省,担当>
        for (OCM_Management_Province__c omp : ompList) {
            //不用map<String,list>的 原因是 想 ocsm管理省 和签收单 营业担当的顺序保持一致
            //String salesManage = omp.SalesManage__c+','+omp.SalesManage2__c+','+omp.SalesManage3__c;
            //provinceOwnerMap.put(omp.Name, salesManage);
            provinceOwnerMap.put(omp.Name, omp.SalesManage__c);
            provinceGIMap.put(omp.Name, omp.GI_assistant__c);
        }
        //①为true的时候 是其他没发生变化只有ocsm省上营业担当改变
        //②为false的时候,有中间表正常更新的情况
        //营业担当123 可能以后不用 20201225 start
        // if(ocsmFlag){
        //     //给最后要更新的签收单的审批者(营业部担当)赋值
        //     for (Integer cnt=0;cnt<eSignFormList.size();cnt++) {
        //         //将逗号分隔的字符串转为数组
        //         //因为其中有逗号,所以肯定不为空
        //         String rcManager =  provinceOwnerMap.get(provinceMap.get(eSignFormList[cnt].Id));
        //         String[] result;
        //         if(rcManager !=null && String.isNotBlank(rcManager)){
        //              result= rcManager.split(',');
        //         }
 
        //         if(result.size()>0&&result!=null){
        //             if(result.contains(eSignFormList[cnt].RC_Manager__c)&&result.contains(eSignFormList[cnt].RC_Manager2__c)&&result.contains(eSignFormList[cnt].RC_Manager3__c)){
        //                 //则不用更新,返回null
        //                 eSignFormList.remove(cnt);
        //                 eSignFormLastList =eSignFormList;
        //             }else{
        //                 eSignForm__c eSignForm = new eSignForm__c();
        //                 eSignForm.Id = eSignFormList[cnt].Id;
        //                 if(result.size()>0){
        //                     if(String.isNotBlank(result[0])&&result[0]!=null&&result[0]!=''&&result[0]!='null'){
        //                         eSignForm.RC_Manager__c = result[0];
        //                     }else{
        //                         eSignForm.RC_Manager__c = null;
        //                     }
        //                     if(String.isNotBlank(result[1])&&result[1]!=null&&result[1]!=''&&result[1]!='null'){
        //                         eSignForm.RC_Manager2__c = result[1];
        //                     }else{
        //                         eSignForm.RC_Manager2__c = null;
        //                     }
        //                     if(String.isNotBlank(result[2])&&result[2]!=null&&result[2]!=''&&result[2]!='null'){
        //                         eSignForm.RC_Manager3__c = result[2];
        //                     }else{
        //                         eSignForm.RC_Manager3__c = null;
        //                     }
        //                 }
        //                 //eSignForm.RC_Manager__c = provinceOwnerMap.get(provinceMap.get(eSignFormList[cnt].Id));
        //                 eSignFormLastList.add(eSignForm);
        //             }
        //         }
 
 
        //     }
        //     return eSignFormLastList;
 
        // }else{
        //     //给最后要更新的签收单的审批者(营业部担当)赋值
        //     for (eSignForm__c esf: eSignFormList) {
        //         //将逗号分隔的字符串转为数组
        //         //因为其中有逗号,所以肯定不为空
        //         String rcManager =  provinceOwnerMap.get(provinceMap.get(esf.Id));
        //         String[] result;
        //         if(rcManager!=null&&String.isNotBlank(rcManager)){
        //             result = rcManager.split(',');
        //         }
 
        //         if(result.size()>0){
        //             if(String.isNotBlank(result[0])&&result[0]!=null&&result[0]!=''&&result[0]!='null'){
        //                 esf.RC_Manager__c = result[0];
        //             }
        //             if(String.isNotBlank(result[1])&&result[1]!=null&&result[1]!=''&&result[1]!='null'){
        //                 esf.RC_Manager2__c = result[1];
        //             }
        //             if(String.isNotBlank(result[2])&&result[2]!=null&&result[2]!=''&&result[2]!='null'){
        //                 esf.RC_Manager3__c = result[2];
        //             }
        //         }
        //         //esf.RC_Manager__c = provinceOwnerMap.get(provinceMap.get(esf.Id));
        //     }
        //     return eSignFormList;
        // }
        //营业担当123 可能以后不用  20201225 end
        if (ocsmFlag) {
            //给最后要更新的签收单的审批者(营业部担当)赋值
            for (Integer cnt = 0; cnt < eSignFormList.size(); cnt++) {
                if (provinceOwnerMap.get(provinceMap.get(eSignFormList[cnt].Id)) != eSignFormList[cnt].RC_Manager__c ||provinceMap.get(eSignFormList[cnt].Id).equals('集采课')) {
 
                    eSignForm__c eSignForm = new eSignForm__c();
                    eSignForm.Id = eSignFormList[cnt].Id;
                    eSignForm.RC_Manager__c = provinceOwnerMap.get(provinceMap.get(eSignFormList[cnt].Id));
                    //集采询价 营业助理需要维护成 集采课的SP、GI助理 精琢技术 wql 2021/01/08 start 
                    if(provinceMap.get(eSignFormList[cnt].Id).equals('集采课')){
                        eSignForm.Sales_assistant_name_text__c = provinceGIMap.get(provinceMap.get(eSignFormList[cnt].Id));
                    }
                    //集采询价 营业助理需要维护成 集采课的SP、GI助理 精琢技术 wql 2021/01/08 end
                    eSignFormLastList.add(eSignForm);
                }
 
            }
            return eSignFormLastList;
 
        } else {
            //给最后要更新的签收单的审批者(营业部担当)赋值
            for (eSignForm__c esf : eSignFormList) {
                if (provinceOwnerMap.get(provinceMap.get(esf.Id)) != null) {
                    esf.RC_Manager__c = provinceOwnerMap.get(provinceMap.get(esf.Id));
                    //集采询价 营业助理需要维护成 集采课的SP、GI助理 精琢技术 wql 2021/01/08 start 
                    if(provinceMap.get(esf.Id).equals('集采课')){
                        esf.Sales_assistant_name_text__c = provinceGIMap.get(provinceMap.get(esf.Id));
                    }
                    //集采询价 营业助理需要维护成 集采课的SP、GI助理 精琢技术 wql 2021/01/08 end
                }
 
            }
            return eSignFormList;
        }
 
    }
 
 
    global void finish(Database.BatchableContext BC) {
 
        //更新该日志的数据信息
        iflog.Log__c += '\nupdateESignBatchAttachment end';
        String tmp = iflog.ErrorLog__c;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        //有错误才添加日志,不然每天每15分钟生成日志太多
        if (tmp.length() > 0) {
            insert iflog;
        }
 
        system.debug('手动传参:' + ManualExecution_Identification);
        //手动传参执行则不进入创建计划的作业
        if (!ManualExecution_Identification) {
            Boolean haveError = false;
            String body = scErrorMessage;
            for (Id objId : eb.messageMap.keySet()) {
                haveError = true;
                body += eb.messageMap.get(objId) + '<br/>';
            }
            if (eb.overMax) {
                body += ':Over ' + MAXERRORCNT + 'Record<br/>';
            }
            updateESignBatchAttachment.removeOtherSc('updateESignFormSchedule', scB.scName);
            if (haveError == true || String.isNotBlank(scErrorMessage)) {
                // BatchユーザId
                //写死精琢用户 上线后应该会修改成自定义标签
                // String batchUserId = '00510000005sEEM';
                String batchUserId = System.Label.Batch_User_Id;
                List<User> us = [Select Id, NAme, Email From User Where Id = : batchUserId];
                if (!us.isEmpty()) {
                    User use = us[0];
                    if (String.isNotBlank(use.Email)) {
                        List<String> MailCc;
                        if (System.Label.ESign_Error_Send_To_CC != 'null') {
                            MailCc = System.Label.ESign_Error_Send_To_CC.split(',');
                        }
                        FixtureUtil.sendMessage(batchUserId,
                                                MailCc,
                                                'updateESignBatchAttachment Error',
                                                body
                                               );
                    }
                }
            }
        }
 
    }
    public class ErrorBean {
        // public String objectName;
        // public String objectLabel;
        public Map<Id, String> messageMap;
        public Boolean overMax;
        // public ErrorBean(Schema.sObjectType obj) {
        //     objectName = obj.getDescribe().getName();
        //     objectLabel = obj.getDescribe().getLabel();
        //     messageMap = new Map<Id, String>();
        //     overMax = false;
        // }
        public ErrorBean() {
            messageMap = new Map<Id, String>();
            overMax = false;
        }
        public void setError (Database.SaveResult[] saveRes, Integer maxCut, Schema.sObjectType obj) {
            if (messageMap.keySet().size() <= maxCut && overMax == false) {
                String objectName = obj.getDescribe().getName();
                String objectLabel = obj.getDescribe().getLabel();
                for (Database.SaveResult saveRe : saveRes) {
                    if (!saveRe.isSuccess()) {
                        if (!messageMap.containsKey(saveRe.getId())) {
                            if (messageMap.keySet().size() >= maxCut) {
                                overMax = true;
                                break;
                            }
                            for (Database.Error err : saveRe.getErrors()) {
 
                                String message = objectName + ':'
                                                 + objectLabel + ':'
                                                 + err.getStatusCode() + ':'
                                                 + err.getFields() + ':'
                                                 + err.getMessage();
                                // 数据里面有复数错误信息的话只获取第一条
                                messageMap.put(saveRe.getId(), message);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
 
    //定时跑任务
    public Class ScBean {
        public String scName;
        public String scTime;
    }
}