global class updateESignBatch implements Database.Batchable < sObject > , Database.Stateful {
    //电子签收单-签收单录入表更新签收单  精琢技术 wql 2020-09-25 start
    /*
    ①正常执行 Database.executeBatch(new updateESignBatch(), 20);
    ②处理某一个签收单  Database.executeBatch(new updateESignBatch(''), 1);
    ③批量处理某些签收单(不是最终状态的) Database.executeBatch(new updateESignBatch(['','','']), 20);
    ④处理某一个最终状态的签收单 Database.executeBatch(new updateESignBatch(''，true), 1);
    ⑤批量处理某些最终状态的签收单 Database.executeBatch(new updateESignBatch('['','','']'，true), 20);
    ⑥处理某一天的所有签收单 Database.executeBatch(new updateESignBatch(2020-09-27), 20);
    ⑦处理某一时间段的所有签收单 Database.executeBatch(new updateESignBatch(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 updateESignBatch() {

        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'ESignBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'updateESignBatch start1\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一天的签收单
    global updateESignBatch(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 = 'updateESignBatch start2\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一时间段的 签收单
    global updateESignBatch(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 = 'updateESignBatch start3\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //批量更新签收单
    global updateESignBatch(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 = 'updateESignBatch start4\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一条的签收单
    global updateESignBatch(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 = 'updateESignBatch start5\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //更新某一条的已处理的签收单
    global updateESignBatch(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 = 'updateESignBatch start6\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    //批量更新已处理的签收单
    global updateESignBatch(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 = 'updateESignBatch start7\n';
        iflog.ErrorLog__c = '';
        // insert iflog;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        scB = updateESignBatch.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>();
        List<FileAddress__c> esignAttachAgencyList = new List<FileAddress__c>();        //zhj Attachment To AWS 2023-02-06
        List<FileAddress__c> esignAttachHPList = new List<FileAddress__c>();            //zhj Attachment To AWS 2023-02-06
        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>();
        List<FileAddress__c> deleteLastFileList = new List<FileAddress__c>();       //zhj Attachment To AWS 2023-02-06
        //存放未更新前的经销商审批状态
        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];
                List<FileAddress__c> deleteFileList = [SELECT ParentRecordId__c, createdDate, FileName__c  
                                                        FROM FileAddress__c
                                                        WHERE ParentRecordId__c IN: rejectESignEneryMap.keySet() order by createdDate];  //zhj Attachment To AWS 2023-02-06
                system.debug('deleteFileList:' + deleteFileList);
                if (deleteFileList.size() > 0) {
                    for (eSignForm__c esFile : rejectESignEneryMap.values()) {
                        //for (Attachment att : deleteFileList) {
                        for (FileAddress__c att : deleteFileList) {             //zhj Attachment To AWS 2023-02-06
                            if (esFile.agencyRejectDate__c != null || esFile.HPRejectDate__c != null) {
                                if (att.ParentRecordId__c == esFile.Id ) {
                                    //①经销商驳回后需要删除的附件
                                    if (esFile.agencyRejectDate__c != null) {
                                        //zhj Attachment To AWS 2023-02-06
                                        // if (att.Name.substring(0, 1) == 'A' && att.createdDate < esFile.agencyRejectDate__c) {
                                        //     deleteLastFileList.add(att);
                                        // }
                                        if (att.FileName__c.substring(0, 1) == 'A' && att.createdDate < esFile.agencyRejectDate__c) {
                                            deleteLastFileList.add(att);
                                        }
                                    }
                                    //②医院驳回后需要删除的附件
                                    if (esFile.HPRejectDate__c != null) {
                                        //zhj Attachment To AWS 2023-02-06
                                        // if (att.Name.substring(0, 1) == 'H' && att.createdDate < esFile.HPRejectDate__c) {
                                        //     deleteLastFileList.add(att);
                                        // }
                                        if (att.FileName__c.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>();
                //zhj Attachment To AWS 2023-02-06
                // List<Attachment> tempAttList = [SELECT parentId, createdDate, Name,Description  
                //                                 FROM Attachment
                //                                 WHERE parentId IN: esFormidList order by createdDate];
                List<FileAddress__c> tempAttList = [SELECT ParentRecordId__c, createdDate, FileName__c 
                                                FROM FileAddress__c
                                                WHERE ParentRecordId__c IN: esFormidList order by createdDate];
                if (tempAttList.size() > 0) {
                    //外层循环签收单
                    for (String es : esFormidList) {
                        //zhj Attachment To AWS 2023-02-06
                        //内层循环附件
                        // 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);
                        //         }

                        //     }
                        // }
                        for (FileAddress__c att : tempAttList) {
                            //如果id相等
                            if (es.equals(att.ParentRecordId__c)) {
                                //根据名称拆分 存入不同list
                                String name = att.FileName__c;
                                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 附件
            //zhj Attachment To AWS 2023-02-06
            //List<Attachment> insertAttactment = new List<Attachment>();
            List<FileAddress__c> insertAttactment = new List<FileAddress__c>();
            //附件  start
            //List<Attachment> attachMentList = [SELECT id, parentId, Body, Name, ContentType,Description  from Attachment where parentId IN :fileList and Description!='电子签收单：已处理'];
            List<FileAddress__c> attachMentList = [SELECT id, ParentRecordId__c, FileName__c,subInfoType__c,AWS_File_Key__c,DownloadLink__c,ViewLink__c  from FileAddress__c where ParentRecordId__c IN :fileList and subInfoType__c  !='电子签收单：已处理'];
            //修复已处理数据 附件没更新  即没有附件能提交的bug 精琢技术 wql 2021/01/19 start 
            //List<Attachment> eSignEntryAttachMentList = new List<Attachment>();
            List<FileAddress__c> eSignEntryAttachMentList = new List<FileAddress__c>();
            //文件数量 用于文件命名
            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 (FileAddress__c attach : attachMentList) {          //zhj Attachment To AWS 2023-02-06

                        if (attach.ParentRecordId__c == eSignFormEntryId) {
                            Id eid = eSignFlieIdMap.get(attach.ParentRecordId__c);
                            system.debug('eid:' + eid);

                            name = eSignNameMap.get(eid);
                            system.debug('name:' + name);
                            type = eSignTypeMap.get(attach.ParentRecordId__c);

                            //因为外层循环是中间表 如果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';
                            // }
                            //判断一下格式，不然下载下来是类型是所有文件 无法打开
                            //zhj Attachment To AWS 2023-02-06 start
                            if (attach.FileName__c.lastIndexOf('.') > -1) {
                                title = title + attach.FileName__c.substring(attach.FileName__c.lastIndexOf('.'));
                            }

                            //Attachment newAttachment = attach.clone();
                            FileAddress__c newAttachment = attach.clone();
                            newAttachment.ParentRecordId__c = eid;
                            newAttachment.FileName__c = title;
                            // newAttachment.ContentType =attach.ContentType;
                            //要更新的签收单附件
                            insertAttactment.add(newAttachment);
                            //反更新录入表的附件 用来判断附件是否被更新
                            //Attachment oldAttachment = new  Attachment();
                            FileAddress__c oldAttachment = new  FileAddress__c();
                            oldAttachment.Id = attach.Id;
                            //oldAttachment.Description = '电子签收单：已处理';
                            oldAttachment.subInfoType__c = '电子签收单：已处理';
                            //zhj Attachment To AWS 2023-02-06 end
                            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) {
                        for (FileAddress__c att : insertAttactment) {   //zhj Attachment To AWS 2023-02-06
                            if (es.Id != null) {
                                if (es.Id.equals(att.ParentRecordId__c)) {
                                    if (es.agencyAutoSignUpStatus__c != null) {
                                        if (es.agencyAutoSignUpStatus__c.equals('申请中') && oldESignAgencyStatusMap.size()>0) {
                                                if(!oldESignAgencyStatusMap.get('A' + es.Id).equals('申请中')){
                                                    if (att.FileName__c.substring(0, 1).equals('A')) {      //zhj Attachment To AWS 2023-02-06
                                                        a ++;
                                                    }
                                                }
                                            
                                        }
                                    }
                                    if (es.HPSignUpStatus__c != null) {
                                        if (es.HPSignUpStatus__c.equals('申请中') && oldESignHPStatusMap.size()>0) {
                                            if(!oldESignHPStatusMap.get('H' + es.Id).equals('申请中')){
                                                if (att.FileName__c.substring(0, 1).equals('H')) {          //zhj Attachment To AWS 2023-02-06
                                                    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>();
            List<FileAddress__c> deleteAttachmentList = new List<FileAddress__c>();     //zhj Attachment To AWS 2023-02-06

            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];
                List<FileAddress__c> attachMentList = [SELECT id, ParentRecordId__c, FileName__c,AWS_File_Key__c  from FileAddress__c where ParentRecordId__c = :fileDeleteIdList];       //zhj Attachment To AWS 2023-02-06
                List<Transaction_Log__c> tranList = new List<Transaction_Log__c>();
                if (attachMentList.size() > 0) {
                    for (FileAddress__c att : attachMentList) {
                        FileAddress__c am = new FileAddress__c();           //zhj Attachment To AWS 2023-02-06
                        am.Id = att.Id;
                        deleteAttachmentList.add(am);
                        //zhj 新增日志，删除AWS的附件 2023-02-17
                        Transaction_Log__c tran = new Transaction_Log__c();
                        tran.AWS_Data_Id__c = att.AWS_File_Key__c;
                        tran.Status__c = 'In Process';
                        tran.Module__c = '签收单附件删除';
                        tranList.add(tran);
                    }
                    //新增日志，删除AWS的附件 zhj 2023-02-17
                    if(tranList.size() > 0){
                        insert tranList;
                    }
                    //删除文件
                    if (deleteAttachmentList.size() > 0) {
                        delete deleteAttachmentList;
                    }
                }


            }
            //删除录入表
            System.debug('删除录入表 : ' + eSignFormDeleteList);
            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 += '\nupdateESignBatch 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/>';
            }
            updateESignBatch.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,
                                                'updateESignBatch 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;
    }

    public static void improveTestRate(){
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}