public with sharing class QISPDFController {
    public QIS_Report__c qr { get; private set; }
    public User usr { get; private set; }
    public Boolean inGuarantee { get; private set; }
    public string staticResource { get; private set; }
    public string staticResourceFile { get; private set; }
    
    //  HWAG-BC68W3  故障发生日为空时， 它为真  start
    public Boolean outOfGuarantee { get; private set; }
    //  HWAG-BC68W3  故障发生日为空时， 它为真  end

    public string Photo_1_Text { get; private set; }
    public string Photo_2_Text { get; private set; }
    public string Photo_3_Text { get; private set; }
    public string Photo_4_Text { get; private set; }
    

    public QISPDFController() {
        qr = new QIS_Report__c();
        usr = new User();
        inGuarantee = false;
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('QIS_Report__c'));
        staticResourceFile = JSON.serialize(PIHelper.getPIIntegrationInfo('Document'));
        
    }
    
    public void init() {
        String id = ApexPages.currentPage().getParameters().get('id');
        
        Schema.DescribeSobjectResult d = QIS_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 += ', Hospital_Department__r.Phone, Hospital_Department__r.Parent.Parent.State_Master__r.Name, Hospital_Department__r.Parent.Parent.City_Master__r.Name, Hospital__r.Name'
              + ', RC__r.Alias__c, RC_manager__r.Alias__c, OSH_Manager__r.Alias__c, OSH_Manager__r.BuchangApprovalManager__c, OSH_Manager__r.BuchangApprovalManager__r.Alias__c';

        soql += ' from QIS_Report__c where Id = \'' + id + '\'';
        
        List<QIS_Report__c> qrList = Database.query(soql);
        if (qrList.size() > 0) {
            qr = qrList[0];
            // TODO 一つのSOQLで出来る？
            usr = [select Name, Manager.Name, fen_corp_name__c, Salesdepartment__c from User where Id = :qr.OwnerId];
            // HWAG-BC68W3 
            /*
            if (qr.QIS_Submit_day__c >= Date.today()) {
            */
           if (qr.Faliour_date__c == null) {
                outOfGuarantee = true;
           }
           if ( qr.Faliour_date__c !=null && qr.guarantee_period_formula__c >= qr.Faliour_date__c) {
            //HWAG-BC68W3 end
            	inGuarantee = true;
            }

            Photo_1_Text = getImageByUrl(qr.Photo_1_Text__c);
            Photo_2_Text = getImageByUrl(qr.Photo_2_Text__c);
            Photo_3_Text = getImageByUrl(qr.Photo_3_Text__c);
            Photo_4_Text = getImageByUrl(qr.Photo_4_Text__c);
        }
    }

    public static String getImageByUrl(string urlStr){
        //urlStr = 'https://ocsm--stagefull--c.documentforce.com/servlet/rtaImage?eid=a0f1000000cS7qH&feoid=00N10000006P4rz&refid=0EM10000002WIgq';
        // 'https://ocsm--stagefull.my.salesforce.com/services/data/v51.0/sobjects/QIS_Report__c/a0f1000000IJay1/richTextImageFields/Photo_1__c/0EM100000017hLN
        System.debug('urlStr='+urlStr);
        Id eid = getUrlParameters(urlStr,'eid');
        if (string.isBlank(eid)) {
            System.debug('eid not found');
            return null;
        }

        Id feoid = getUrlParameters(urlStr,'feoid');
        if (string.isBlank(feoid)) {
            System.debug('feoid not found');
            return null;
        }

        Id refid = getUrlParameters(urlStr,'refid');
        if (string.isBlank(refid)) {
            System.debug('refid not found');
            return null;
        }

        string body = MetaDataUtility.ToolingQuery('select id,FullName from CustomField where id=\''+feoid+'\'');
        if(string.isBlank(body)){
            System.debug('body is blank');
            return null;
        }
        string sobjecttype = eid.getSobjectType().getDescribe().getName();
        List<object> lo = (List<object>)(((Map<string,object>)JSON.deserializeUntyped(body)).get('records'));
        Map<string,object> mso = (Map<string,object>)(lo[0]);
        string f = ((string)mso.get('FullName')).replace(sobjecttype+'.', '');

        String urlForClassic = 'https://'+System.URL.getOrgDomainUrl().getHost()+'/services/data/v53.0/sobjects/'+sobjecttype+'/'+eid+'/richTextImageFields/'+f+'/'+refid;
        
        system.debug('URL Post:'+urlForClassic);
        HttpResponse resp = null;
        HttpRequest req = new HttpRequest();         
        req.setMethod('GET');        
        req.setEndpoint(urlForClassic); 
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getsessionid());      
        Http client = new Http();    
        resp = client.send(req);
        system.debug('getStatusCode:'+resp.getStatusCode());
        return 'data:image/png;base64,' + EncodingUtil.base64Encode(resp.getBodyAsBlob());
    }

    public static String getUrlParameters(string url,string para){
        //string url = 'https://sfpi-mebg-test.olympuschina.com:8081/stg/api/file/convert?from=https%3A%2F%2Focsm--stagefull--c.visualforce.com%2Fapex%2FQISPDF%3Fid%3Da0f1000000cS7qH&fileName=QISPDF';
        if (string.isBlank(url) || string.isBlank(para)) {
            return null;
        }
        Pattern p = Pattern.compile('(?<=' + para + '=)[^&]*');
        Matcher m = p.matcher(url);
        if (m.find()) {
            return m.group();
        }else {
            system.debug('no found '+para+' in url='+url);
            return null;
        }
        
    }
}