global without sharing class ConsumApplyEquipmentSetDetailDailyBatch implements Database.Batchable<sObject>, Database.Stateful {
    global List<String> emailMessages = new List<String>();
    global Integer totalCount = 0; // 総処理件数
    global Integer totalCountDone = 0; // 処理済件数
    global Integer failedCount = 0; // 処理失敗件数

    global Id csmApyId;
    Boolean IsNeedExecute = false; // 2021-03-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件
    global ConsumApplyEquipmentSetDetailDailyBatch(Id csmApyId) {
        this.csmApyId = csmApyId;
    }
    //2021-06-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
    global ConsumApplyEquipmentSetDetailDailyBatch(Id csmApyId,Boolean needExecute) {
        this.csmApyId = csmApyId;
        this.IsNeedExecute = needExecute;
    }
    //2021-06-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'select id,name from Consum_Apply__c';
        if (csmApyId != null) {
            query = query + ' where id = \'' + csmApyId +'\'';
        } else {
            query = query + ' where Status__c = \'已出库指示\'';
        }
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext bc, List<Consum_Apply__c> csmApyList) {
        totalCount += csmApyList.size();
        Savepoint sp = Database.setSavepoint();
        try {
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [SELECT Id, Name
                        , Shippment_loaner_time2__c
                        , Loaner_received_time__c
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply__c in :csmApyList
                      AND Shippment_loaner_time2__c != null
                      AND Loaner_received_time__c = null];
            for (Consum_Apply_Equipment_Set_Detail__c caesd : caesdList) {
                if (caesd.Shippment_loaner_time2__c <= system.now().addDays(-7)) {
                    caesd.Loaner_received_time__c = system.now();
                    caesd.Received_Confirm__c = '默认签收-OK';
                }
            }

            List<Database.SaveResult> updResult = Database.update(caesdList, false);
            if (this.emailMessages.size() < 100) {
                this.emailMessages = FixtureUtil.setSaveError(updResult, Consum_Apply_Equipment_Set_Detail__c.sObjectType, caesdList, this.emailMessages);
            }
            totalCountDone += csmApyList.size();
        }
        catch (Exception e) {
            emailMessages.add(e.getMessage());
            failedCount += csmApyList.size();
            Database.rollback(sp);
        }
    }

    global void finish(Database.BatchableContext bc) {
        BatchEmailUtil be = new BatchEmailUtil();
        String[] toList = new String[]{UserInfo.getUserEmail()};
        String emailLabel = 'BatchNotify';
        for (OrgWideEmailAddress tmpEmailObj : [SELECT Id, Address, DisplayName 
                FROM OrgWideEmailAddress
                WHERE DisplayName like :emailLabel]) {
            toList = new String[]{tmpEmailObj.Address};
        }
        String title = '消耗品的默认签收';
        List<String> ccList = new List<String>();
        for (Consum_Apply_Meta__mdt camd : [SELECT Id
                    , Key__c
                    , ValueLong__c
                 FROM Consum_Apply_Meta__mdt
                WHERE Package__c = 'ConsumTrialNotUploadRemindBatch'
                  AND (Key__c = 'ErrorMailAddress'
                          OR Key__c = 'ErrorMailTitle'
                      )
                ORDER BY Key__c]) {
            if (camd.Key__c == 'ErrorMailAddress') {
                if (String.isNotBlank(camd.ValueLong__c)) {
                    ccList.addAll(camd.ValueLong__c.split(','));
                }
            }
            else if (camd.Key__c == 'ErrorMailTitle') {
                title = camd.ValueLong__c;
            }
        }
        if (!(totalCountDone == totalCount && 0 == emailMessages.size())) {
            be.failedMail(toList, ccList, title,
                String.join(this.emailMessages, '\n'),
                totalCount, totalCountDone, failedCount);
            be.send();
        }

        //2021-06-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        if(!Test.isRunningTest() &&IsNeedExecute==true){
            //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
            Id execBTId = Database.executebatch(new monitorUpdateESignBatch(),5);
        }
        //2021-06-08  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end
    }
    @TestVisible private static void test() {
        if (false == Test.isRunningTest()) return;
        Integer i = 0;
        
    }
}