// public with sharing class RepairAndQISToPDFController {
    public without sharing class RepairAndQISToPDFController {
    
        // public PDFToBlobController(){
        //     apiName = ApexPages.currentPage().getParameters().get('api');
        //     fields = ApexPages.currentPage().getParameters().get('fields');
        //     fileName = ApexPages.currentPage().getParameters().get('fileName');
        //     controlLimit = Long.valueOf(ApexPages.currentPage().getParameters().get('controlLimit')) ;
        //     init();
        // }
     
        // 设置页面展示的数据
        public static void setImgSrcs(SObject obj,String apiName){
            ImgObjs = new List<ImgObj>();
            String content = (String) obj.get(apiName);
    
            // while(content.indexOf('<img') != -1 && content.indexOf('></img>') != -1){
            //     String imgTag = content.substring(content.indexOf('<img'),content.indexOf('></img>')+7);
            //     System.debug('imgTag'+imgTag);
               
            //     ImgObj ImgObj = new ImgObj();
            //     // 使用空格分隔
            //     List<String> imgTagSplit =  imgTag.split('\\s');
            //     System.debug('imgTagSplit'+imgTagSplit);
                
            //     if(imgTag.contains('height')){
            //         for(String str :imgTagSplit){
            //             if(str.startsWith('src=')){
            //                 ImgObj.imgSrc = str.substring(5,str.length()-1);
            //                 break;
            //             }
            //         }
            //         Integer imgheight = Integer.valueOf(imgTagSplit[4].substring(0,imgTagSplit[4].length() - 3));
            //         ImgObj.height =  imgheight >= 900 ? '900px' : imgTagSplit[4];
            //     }else{
            //         for(String str :imgTagSplit){
            //             if(str.startsWith('src=')){
            //                 ImgObj.imgSrc = str.substring(5,str.length()-8);
            //                 break;
            //             }
            //         }
            //         ImgObj.height = '900px';
            //     }
            //     ImgObjs.add(ImgObj);
            //     content = content.substring(content.indexOf('></img>')+7,content.length());
            // }
            ImgObj ImgObj = new ImgObj();
            ImgObj.imgSrc = content;
            ImgObj.height = '900px';
            ImgObjs.add(ImgObj);
            System.debug('ImgObjs++'+ImgObjs);
            
        }
    
        // 生成pdf添加到对应的修理中
        public static PageReference generateAttachment(List<Repair__c> repList){
            PageReference pdfPage ;
            
            List<Repair__c> updateRpr = new List<Repair__c>();
            // List<Attachment> attachments = new List<Attachment>();
            List<ContentVersion> cVersions = new List<ContentVersion>();
            List<ContentDocumentLink> cDocLinks = new List<ContentDocumentLink>();
            Map<String,String> res = new Map<String, String>();
            for(Repair__c re : repList){
                String generatedFields = re.GeneratedPDFField__c;
                if (checkFieldisGeneratedPDF('ProblemDescription__c',re)) {
                    continue;                
                }
                if (re.get('ProblemDescription__c') == null) {
                    continue;
                }
                setImgSrcs(re, 'ProblemDescription__c');            
    
                pdfPage = new PageReference('/apex/repairandqistopdf?api=repair&id='+re.Id);
                Blob pdfBody;
                if(Test.isRunningTest()) { 
                    pdfBody = blob.valueOf('Unit.Test');
                } else {
                    pdfBody = pdfPage.getContentAsPDF();
                }
                ContentVersion version = new ContentVersion();
                version.VersionData = pdfBody;
                version.Title = re.name + '_' + 'Problem_Discription.pdf';
                version.PathOnClient = re.name + '_' + 'Problem_Discription.pdf'+'.pdf';
                cVersions.add(version);
                res.put(version.Title, re.Id);
                // insert version;
                // Attachment attach = new Attachment();
                // attach.Body = pdfBody;
                // attach.Name = re.name + '_' + 'Problem_Discription.pdf';
                // attach.ParentId = re.id;
                // attachments.add(attach);
                re.GeneratedPDFField__c = 'ProblemDescription__c';
                updateRpr.add(re);
            }
            if (cVersions.size()>0) {
                insert cVersions;
            }
            List<Id> idList = new List<Id>();
            for (ContentVersion newVersion : cVersions) {
                idList.add(newVersion.Id);
            }
            cVersions = [select ContentDocumentId,Title from ContentVersion where Id in: idList];
            for (ContentVersion cv : cVersions) {
                ContentDocumentLink cdl = new ContentDocumentLink();
                cdl.ContentDocumentId = cv.ContentDocumentId;
                cdl.LinkedEntityId = res.get(cv.Title);
                cdl.ShareType = 'I';
                cdl.visibility = 'AllUser';
                cDocLinks.add(cdl);
            }
            insert cDocLinks;
            // insert attachments;
            update updateRpr;
            return null;
        }
    
    
        // 生成pdf添加到对应的qis中
        public static PageReference generateAttachment(List<QIS_Report__c> qisReports){
            System.debug('1111111111111111111111111111111111111111111111111generateAttachment执行了-----------');
    
            List<QIS_Report__c> updateQis = new List<QIS_Report__c>();
            // List<Attachment> attachments = new List<Attachment>();
            List<ContentVersion> cVersions = new List<ContentVersion>();
            List<ContentDocumentLink> cDocLinks = new List<ContentDocumentLink>();
            Map<String,String> res = new Map<String, String>();
            PageReference pdfPage ;
            for(QIS_Report__c qis : qisReports){
    
                // 需要生成pdf的字段
                List<String> apiNames = new List<String>();
                apiNames.add('problem_detail_photo__c');
                apiNames.add('Photo_1__c');
                apiNames.add('Photo_2__c');
                apiNames.add('Photo_3__c');
                apiNames.add('Photo_4__c');
                apiNames.add('Photo_OSH_1__c');
                apiNames.add('Photo_OSH_2__c');
                apiNames.add('Photo_OSH_3__c');
                apiNames.add('Photo_OSH_4__c');
    
                for (String apiName : apiNames) {
                    String generatedFields =  qis.GeneratedPDFField__c;
                    if (checkFieldisGeneratedPDF(apiName,qis)) {
                        continue;
                    }
                    if (qis.get(apiName) == null) {
                        continue;
                    }
                    setImgSrcs(qis, apiName);
                    pdfPage = new PageReference('/apex/repairandqistopdf?api=qis&id='+qis.Id+'&field='+apiName);
                    Blob pdfBody;
                    if(Test.isRunningTest()) { 
                        pdfBody = blob.valueOf('Unit.Test');
                    } else {
                       pdfBody = pdfPage.getContentAsPDF();
                    }
                    ContentVersion version = new ContentVersion();
                    version.VersionData = pdfBody;
                    // Attachment attach = new Attachment();
                    // attach.Body = pdfBody;
                    if ('problem_detail_photo__c'.equals(apiName)) {
                        // attach.Name =  substringApiName(qis.name) + '_Problem_Discription.pdf';
                        version.Title = substringApiName(qis.name) + '_Problem_Discription.pdf';
                    }else {
                        // attach.Name = substringApiName(qis.name) + '_' + 'Problem_' + apiName.substring(0,apiName.length()-3) + '.pdf';
                        version.Title = substringApiName(qis.name) + '_' + 'Problem_' + apiName.substring(0,apiName.length()-3) + '.pdf';
                    }
                    version.PathOnClient = substringApiName(qis.name) + '_' + 'Problem_' + apiName.substring(0,apiName.length()-3) + '.pdf'+'.pdf';
                    // attach.ParentId = qis.id;
                    // attachments.add(attach);
                    cVersions.add(version);
                    res.put(version.Title, qis.Id);
                    // insert version;
                    if (generatedFields == null) {
                        qis.GeneratedPDFField__c = apiName;
                    }else {
                        qis.GeneratedPDFField__c += ',' + apiName;
                    }
                }
                updateQis.add(qis);
            }
            if (cVersions.size()>0) {
                insert cVersions;
            }
            List<Id> idList = new List<Id>();
            for (ContentVersion newVersion : cVersions) {
                idList.add(newVersion.Id);
            }
            cVersions = [select ContentDocumentId,Title from ContentVersion where Id in: idList];
            for (ContentVersion cv : cVersions) {
                ContentDocumentLink cdl = new ContentDocumentLink();
                cdl.ContentDocumentId = cv.ContentDocumentId;
                cdl.LinkedEntityId = res.get(cv.Title);
                cdl.ShareType = 'I';
                cdl.visibility = 'AllUsers';
                cDocLinks.add(cdl);
            }
            insert cDocLinks;
            // insert attachments;
            update updateQis;
            
            return null;
        }
    
        // 主要用于生成qis中问题描述对应的pdf文件名称(比较特殊)
        public static String substringApiName(String name){
            for(Integer i = 0; i < 2; i++){
                name = name.substring(name.indexOf('-')+1);
            }
            return name;
        }
    
        public static Boolean checkFieldisGeneratedPDF(String apiName,SObject obj){
            String generatedFields = (String) obj.get('GeneratedPDFField__c');
            if (generatedFields != null) {
                List<String> ele = generatedFields.split(',');
                return ele.contains(apiName);
            }
            return false;
        }
    
    
        public QIS_Report__c QIS_Reports {get; set;}
        public Repair__c repairs {get; set;}
        // 是否为修理
        public Boolean isRepair {get; set;}
    
        // api名称    
        public String api {get; set;}
        // id
        public String objId {get; set;}
    
        // 字段
        public String field {get; set;}
        // 标签
        public String label {get; set;}
    
        // 
        public static List<ImgObj> ImgObjs {get; set;}
    
        public RepairAndQISToPDFController(){
            String fileName = '';
            String url = '';
            api = ApexPages.currentPage().getParameters().get('api');
            objId = ApexPages.currentPage().getParameters().get('id');
    
            if ('repair'.equals(api)) { 
                isRepair = true;
                repairs = [select id,name,ProblemDescription__c,GeneratedPDFField__c from Repair__c where id = :objId];
                setImgSrcs(repairs, 'ProblemDescription__c');
            }else {
                field = ApexPages.currentPage().getParameters().get('field');
                String sql = 'select id,name,GeneratedPDFField__c,'+ field;
                sql += ' from QIS_Report__c where id = \''+objId+'\'';
    
                label = Schema.getGlobalDescribe().get('QIS_Report__c').getDescribe().fields.getMap().get(field).getDescribe().getLabel();
                QIS_Reports = Database.query(sql);
                setImgSrcs(QIS_Reports, field);
    
            }
    
        }
    
        public class ImgObj{
            public String imgSrc {get; set;}
            public String height {get; set;}
        }
    
    }