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');
        ir = this.getReportData(id);
        //add by rentx 20210913 start 
        isVm = ir.Contract__c == null ? 'FALSE' : 'TRUE';
        //add by rentx 20210913 end
    }
    
    public void saveSign() {
        // 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;
        }
    }
    
    public void savePDF() {
        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;
        }
    }
    
    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 + '\'';
        
        return Database.query(soql);
    }
}