global class DeleteFileSchedulable implements Database.Batchable<sObject>,Schedulable,Database.allowsCallouts {

    List<Transaction_Log__c> tranList = new List<Transaction_Log__c>();

    global void execute(SchedulableContext SC) {
        Id execBTId = Database.executeBatch(new DeleteFileSchedulable(), 100);
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'select Id,AWS_Data_Id__c,Status__c,Module__c from Transaction_Log__c where Module__c= \'签收单附件删除\' and Status__c=\'In Process\'';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Transaction_Log__c> scope) {
        if(scope.size() > 0){
            
            Set<String> fileAddressIds = new Set<String>();
            for(Transaction_Log__c tran : scope){
                fileAddressIds.add(tran.AWS_Data_Id__c);
            }
            //1. Get file address id
            system.debug('fileAddressId = '+ JSON.serialize(fileAddressIds));
            PIHelper.PIIntegration documentPI=PIHelper.getPIIntegrationInfo('Document');
            //2. Delete aws file doucment and post aws service
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            String url = documentPI.deleteUrl;
            request.setEndpoint(url);
            request.setMethod('POST');
            request.setHeader('pi-token',documentPI.token);
            request.setHeader('Content-Type', 'application/json');
            request.setBody(JSON.serialize(fileAddressIds));
            HttpResponse response = http.send(request);
            system.debug('response = ' + response);
            if(response.getStatusCode() == 200){
                Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                if(results.get('status')=='0'){
                    System.debug('成功删除签收单附件');
                    for(Transaction_Log__c tran : scope){
                        tran.Status__c = 'Success';
                        tranList.add(tran);
                    }
                    update tranList;
                }
            }
        }
    }
    global void finish(Database.BatchableContext BC) { 
        System.debug('DeleteFileSchedulable finish');
    }
}