global without sharing class FileUploadController {
    public String staticResource {get; set;}
    public static String sobjectTypeValue = 'Document';
    public String PIPL_Input_PDF_Error_Msg{set;get;}
    public List<FileAddress__c>  fileList{set;get;}
    public Document documentData{set;get;}
    public String parentId{set;get;}
    public FileUploadController(ApexPages.StandardController controller) {
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Document'));
        SObject obj = controller.getRecord();     
        parentId = obj.Id;
        system.debug('Parent Id:'+parentId); 
        fileList=getFileds(parentId);
    }

    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }

    @RemoteAction
    global static Response saveFile(String fileName,String key,String transId,String parentId){
        FileAddress__c file = new FileAddress__c();
        PIHelper.PIIntegration pI=PIHelper.getPIIntegrationInfo('Document');
        file.DownloadLink__c =pI.undeleteUrl+key+'&fileName='+fileName;
        file.DownloadLink2__c =pI.undeleteUrl+key+'&fileName='+fileName;
        file.FileName__c =fileName;
        file.ViewLink__c =pI.queryUrl+key;
        file.ParentRecordId__c =parentId;
        file.AWS_File_Key__c = key;
        Response response =new Response();
        Savepoint sp = Database.setSavepoint();
        try {
            insert file;
            //4. 插入日志 
            //update 20220218 加入新的日志方式
            PIHelper.saveTransLog(sobjectTypeValue,key,transId,file.Id,JSON.serialize(file),'success','');
            response.recordId=file.Id;
            response.status='success';
            return response;
        } catch (Exception e) {
            System.debug('into catch'+e.getMessage());
            PIHelper.saveTransLog(sobjectTypeValue,key,transId,file.Id,JSON.serialize(file),'fail',e.getMessage());
            Database.rollback(sp);
            response.message=e.getMessage();
            response.status='fail';
            return response;
        }
        
       
    }

    public PageReference refreshFiles() {
        system.debug('refresh files');
        fileList=getFileds(parentId);
        system.debug('fileList size:'+String.valueOf(fileList.size()));
        system.debug(JSON.serialize(fileList));
        return null;
    }
    
    public static List<FileAddress__c> getFileds(String parentId){
        if(String.isNotBlank(parentId)){
            return [SELECT Id,ParentRecordId__c, FileName__c,DownloadLink__c,DownloadLink2__c,FileAddress__c.ViewLink__c FROM FileAddress__c where ParentRecordId__c=:parentId order by createddate desc];
        }
        return [SELECT Id, ParentRecordId__c,FileName__c,DownloadLink__c,DownloadLink2__c,FileAddress__c.ViewLink__c FROM FileAddress__c order by createddate desc limit 100];
    }
}