public with sharing class InsReportPDFOuterController {
    public Inspection_Report__c ir { get; private set; }
    //add by rentx 20210913 start 
    public String isVm {get;set;}
    //add by rentx 20210913 end
    
    public string signStr { get; set; }
    
    public void init() {
        String id = ApexPages.currentPage().getParameters().get('id');
        System.debug('id>>>>>' + id);
        ir = this.getReportData(id);
        System.debug('ir>>>');
        //add by rentx 20210913 start 
        isVm = ir.Contract__c == null ? 'FALSE' : 'TRUE';
        //add by rentx 20210913 end
    }
    
    public void saveSign() {
        // 20231103   Lightning文件修改 Start
        // // Sign画像は一つでいいじゃない？Delete⇒Insertにする
        // List<Attachment> atts = [select Id from Attachment where ParentId = :ir.Id and Name = :(ir.Name + '_Sign')];
        // if (atts.size() > 0) delete atts;
        
        // Attachment ac = new Attachment();
        // ac.Body = EncodingUtil.base64Decode(this.signStr.removeStart('data:image/png;base64,'));
        // ac.Name = ir.Name + '_Sign';
        // ac.ParentId = ir.Id;
        // ac.ContentType = 'jpg';
        // try {
        //     insert ac;
        //     //TODO status「サイン済み」にする
        //     ir.ResponsiblePerson_Sign__c = '<img src="/servlet/servlet.FileDownload?file=' + ac.Id + '"/>';
        //     ir.SignUrl__c = '/servlet/servlet.FileDownload?file=' + ac.Id;
        //     ir.Status__c = '已签字';
        //     update ir;
        // } catch (Exception ex) {
        //     ApexPages.addMessages(ex);
        //     //return;
        // }

        List<ContentDocumentLink> links = [select ContentDocumentId from ContentDocumentLink where LinkedEntityId =: ir.Id];
        if (links.size() > 0) {
            List<Id> idList = new List<Id>();
            for (ContentDocumentLink link : links) {
                idList.add(link.ContentDocumentId);
            }
            List<ContentDocument> cons = [select Id from ContentDocument where Id in: idList and Title =: (ir.Name + '_Sign')];
            if (cons.size() > 0) {
                delete cons;
            }
        }
        ContentVersion version = new ContentVersion();
        version.Title = ir.Name + '_Sign';
        version.VersionData = EncodingUtil.base64Decode(this.signStr.removeStart('data:image/png;base64,'));
        version.PathOnClient = ir.Name + '_Sign.jpg';
        version.ContentLocation = 's';
        try {
            insert version;
            version = [select Id,ContentDocumentId from ContentVersion where Id =: version.Id];
            ContentDocumentLink link = new ContentDocumentLink();
            link.LinkedEntityId = ir.Id;
            link.ShareType = 'I';
            link.ContentDocumentId = version.ContentDocumentId;
            link.Visibility = 'AllUsers';
            insert link;
            //     //TODO status「サイン済み」にする
            // ir.ResponsiblePerson_Sign__c = '<img src="/lightning/r/ContentDocument/'+ link.ContentDocumentId + '/view"/>';
            // ir.SignUrl__c = '/lightning/r/ContentDocument/'+ link.ContentDocumentId + '/view';
            ir.ResponsiblePerson_Sign__c = '<img src="/sfc/servlet.shepherd/version/download/'+ version.Id + '"/>';
            ir.SignUrl__c = '/sfc/servlet.shepherd/version/download/'+ version.Id;
            ir.Status__c = '已签字';
            update ir;
        } catch (Exception e) {
            System.debug('error---'+e.getmessage()+'  '+e.getlinenumber());
            ApexPages.addMessages(e);
        }
        // 20231103   Lightning文件修改 End
    }
    
    public void savePDF() {
        // 20231103   Lightning文件修改 Start
        // String pdfPageURL = '/apex/InsReportPDF?id=' + ir.Id;
        // PageReference pageRef = new PageReference(pdfPageURL);

        // Attachment att = new Attachment();
        // // TODO TestMethodはgetContentをサポートしない
        // if (!Test.isRunningTest()) {
        //     att.body = pageRef.getContent();
        // } else {
        //     att.body = EncodingUtil.base64Decode('test');
        // }
        // att.Name = ir.Name + '_点检报告书_' + String.valueOf(Datetime.now()) + '.pdf';
        // att.ParentId = ir.Id;
        // try {
        //     insert att;
        // } catch (Exception ex) {
        //     ApexPages.addMessages(ex);
        //     //return;
        // }
        String pdfPageURL = '/apex/InsReportPDF?id=' + ir.Id;
        PageReference pageRef = new PageReference(pdfPageURL);
        ContentVersion version = new ContentVersion();
        if (!Test.isRunningTest()) {
            version.VersionData = pageRef.getContentAsPDF();
        } else {
            version.VersionData = EncodingUtil.base64Decode('test');
        }
        // version.Title = ir.Name + '_点检报告书_' + String.valueOf(Datetime.now()) + '.pdf';
        version.Title = ir.Name + '_点检报告书_' + String.valueOf(Datetime.now());
        version.ContentLocation = 's';
        version.PathOnClient = ir.Name + '_点检报告书_' + String.valueOf(Datetime.now()) + '.pdf';
        try {
            insert version;
            version = [select ContentDocumentId from ContentVersion where Id =: version.Id];
            ContentDocumentLink link = new ContentDocumentLink();
            link.LinkedEntityId = ir.Id;
            link.ShareType = 'I';
            link.Visibility = 'AllUsers';
            link.ContentDocumentId = version.ContentDocumentId;
            insert link;
        } catch (Exception e) {
            ApexPages.addMessages(e);
            // ApexPages.addMessage(e);
        }
        // 20231103   Lightning文件修改 End
    }
    
    private Inspection_Report__c getReportData(String id) {
        Schema.DescribeSobjectResult d = Inspection_Report__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = d.fields.getMap();
        
        String soql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', ';
            }
            fields += field;
        }
        soql += fields;
        soql += ' from Inspection_Report__c where Id = \'' + id + '\'';
        
        System.debug('soql = ' + soql);
        return Database.query(soql);
    }
}